48

我的片段中有地图视图。我需要刷新地图并根据条件添加不同的标记。所以,我应该在添加新标记之前从地图中删除最后一个标记。

实际上,几周前应用程序运行良好,但突然发生了。我的代码是这样的:

private void displayData(final List<Venue> venueList) {

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();
.
.
.
}

上次它运行良好(在 Android 团队在 2013 年 I/O 宣布新的 Google Map API 之前)。然而,在那之后我调整了我的代码以使用这个新的 API。现在,我不知道为什么这种方法googleMap.clear();不起作用!

任何建议将不胜感激。谢谢

=======

更新

=======

完整代码:

private void displayData(final List<Venue> venueList) {

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);

        // Add marker of user's position
        MarkerOptions userIndicator = new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("You are here")
                .snippet("lat:" + lat + ", lng:" + lng);
        googleMap.addMarker(userIndicator);

        // Add marker of venue if there is any
        if(venueList != null) {
            for(int i=0; i < venueList.size(); i++) {
                Venue venue = venueList.get(i);
                String guys = venue.getMaleCount();
                String girls= venue.getFemaleCount();
                String checkinStatus = venue.getCan_checkin();
                if(checkinStatus.equalsIgnoreCase("true"))
                    checkinStatus = "Checked In - ";
                else
                    checkinStatus = "";

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getName())
                        .snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));

                googleMap.addMarker(markerOptions);
            }
        }

        // Move the camera instantly to where lat and lng shows.
        if(lat != 0  && lng != 0)
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));

        googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                String str = marker.getId();
                Log.i(TAG, "Marker id: " + str);
                str = str.substring(1);
                int markerId = Integer.parseInt(str);
                markerId -= 1; // Because first item id of marker is 1 while list starts at 0
                Log.i(TAG, "Marker id " + markerId + " clicked.");

                // Ignore if User's marker clicked
                if(markerId < 0)
                    return;

                try {
                    Venue venue = venueList.get(markerId);
                    if(venue.getCan_checkin().equalsIgnoreCase("true")) {
                        Fragment fragment = VenueFragment.newInstance(venue);
                        if(fragment != null)
                            changeFragmentLister.OnReplaceFragment(fragment);
                        else
                            Log.e(TAG, "Error! venue shouldn't be null");
                    }
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(IndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
        });
4

5 回答 5

47

好的,最后我找到了一种替代方法来解决我的问题。有趣的问题是,当您为地图分配标记时,它的 id 是“m0”。当您从地图中删除它并分配新标记时,您希望 id 应该是“m0”,但它是“m1”。因此,它向我表明该 id 是不可信的。所以我在片段的List<Marker> markerList = new ArrayList<Marker>();某个地方定义了。onActivityCreated()

然后将上面的代码更改为以下代码。如果他们有类似的标记问题,希望它可以帮助其他人。

private void displayData(final List<Venue> venueList) {
        Marker marker;

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();
        markerList.clear();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);

        // Add marker of user's position
        MarkerOptions userIndicator = new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("You are here")
                .snippet("lat:" + lat + ", lng:" + lng);
        marker = googleMap.addMarker(userIndicator);
//        Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
        markerList.add(marker);

        // Add marker of venue if there is any
        if(venueList != null) {
            for (Venue venue : venueList) {
                String guys = venue.getMaleCount();
                String girls = venue.getFemaleCount();
                String checkinStatus = venue.getCan_checkin();
                if (checkinStatus.equalsIgnoreCase("true"))
                    checkinStatus = "Checked In - ";
                else
                    checkinStatus = "";

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getName())
                        .snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));

                marker = googleMap.addMarker(markerOptions);
//                Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
                markerList.add(marker);
            }
        }

        // Move the camera instantly to where lat and lng shows.
        if(lat != 0  && lng != 0)
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));

        googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                int markerId = -1;

                String str = marker.getId();
                Log.i(TAG, "Marker id: " + str);
                for(int i=0; i<markerList.size(); i++) {
                    markerId = i;
                    Marker m = markerList.get(i);
                    if(m.getId().equals(marker.getId()))
                        break;
                }

                markerId -= 1; // Because first item of markerList is user's marker
                Log.i(TAG, "Marker id " + markerId + " clicked.");

                // Ignore if User's marker clicked
                if(markerId < 0)
                    return;

                try {
                    Venue venue = venueList.get(markerId);
                    if(venue.getCan_checkin().equalsIgnoreCase("true")) {
                        Fragment fragment = VenueFragment.newInstance(venue);
                        if(fragment != null)
                            changeFragmentLister.OnReplaceFragment(fragment);
                        else
                            Log.e(TAG, "Error! venue shouldn't be null");
                    }
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(IndexOutOfBoundsException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        });
    }
于 2013-06-01T09:32:36.053 回答
36

如果您想清除“地图上的所有标记、叠加层和折线”,clear()请在您的 GoogleMap 上使用。

于 2015-07-29T15:32:52.840 回答
10

用于map.clear()从 Google 地图中删除所有标记

于 2017-05-12T07:25:35.947 回答
0

假设有ArrayList2 个位置。现在,您根据该数组在地图上显示标记。会有两个标记。当您单击第一个标记时,它会给您一个标记索引m0,第二个是m1

假设您刷新了位置数组,现在您得到了一个包含 3 个位置的数组。你有3个标记。但是当您单击第一个时,它会为您提供标记索引m2(好像它从第一个位置箭头继续计数)第二个是m3,第三个是m4。你真正想要的是把它变成m0, m1, m2.

现在,当您构建您的位置数组时,您可能会调用location.add("you location")......当您重建它(刷新它)时,您location.clear()首先调用然后再次构建它。

解决方案:

首先,制作另一个类似于位置数组的虚拟数组for,并将其与真实位置数组一起循环构建:locaionDummy.add(i)但你永远不要刷新它 - 这样它会不断构建,你会知道你曾经从一开始。

mIndex其次,使用asint变量做这样的事情(设置图像的示例) :

void locatePins() {  

mIndex = locationDummy.size()-location.size();

for (int i = 0; i < userID.size(); i++) {

    LatLng pgLocation = new LatLng(Double.parseDouble(latArr.get(i)), Double.parseDouble(lngArr.get(i)));

    myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {    
        @Override
        public View getInfoWindow(Marker marker) {

        View view = getLayoutInflater().inflate(R.layout.map_marker_info, null);

        RelativeLayout markerInfo= view.findViewById(R.id.markerInfo);
        TextView name = view.findViewById(R.id.userName);
        TextView details = view.findViewById(R.id.userInfo);
        ImageView img = view.findViewById(R.id.userImg);

        name.setText(marker.getTitle());
        details.setText(marker.getSnippet());

        img.setImageBitmap (bmImg.get(Integer.parseInt(marker.getId().replaceAll("[^\\d.]", ""))-mIndex));

        return view;
    }

    @Override
    public View getInfoContents(Marker marker) {

         return null;
    }   

    // ... the rest of the code 
}
}

关键是location.size()从 a中减去实locationDummy.size()数以得到一个int mIndex稍后将减去的数字marker.getId()

于 2019-11-02T01:25:05.087 回答
0

如果您只需要删除标记,并将其他东西(例如地面覆盖物等)留在那里,请使用:

 marker.remove();

或者如果你有很多:

 if(markers!=null&&mMap!=null){                          
      for(int i=0;i<markers.size();i++){                
             markers.get(i).remove();
      }
 }

在哪里

List<Marker> markers = new ArrayList<>();
于 2020-06-24T18:21:16.437 回答