Android,如何从Google Map V2中删除所有标记?

时间:2013-05-31 08:37:57

标签: android google-maps google-maps-markers android-mapview

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

实际上,几周前应用程序工作正常,突然发生了。我的代码是这样的:

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

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

上次它工作正常(在I / O 2013中由Android团队宣布新的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 个答案:

答案 0 :(得分:40)

好吧我终于找到了解决问题的替代方法。有趣的问题是当你为地图指定一个标记时,它的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();
                }
            }
        });
    }

答案 1 :(得分:20)

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

答案 2 :(得分:0)

假设有一个ArrayList 2个位置。现在,您将基于该数组在地图上显示标记。将有两个标记。单击第一个标记时,它会为您提供标记索引m0,第二个标记是m1

假设您刷新位置数组,现在得到一个包含3个位置的数组。您有3个标记。但是,当您单击第一个时,它会为您提供标记索引m2(就像它从第一个位置开始继续计数一样),第二个是m3,第三个是m4。您真正想要的是将其设置为m0m1m2

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

解决方案:

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

第二,使用mIndex作为int变量,执行以下操作(设置图像的示例):

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()中减去实数locationDummy.size()来得到一个数字int mIndex,稍后再从marker.getId()中减去

答案 3 :(得分: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<>();