androidandroid-mapviewosmdroidmarkersoverlays

OSMDroid - getOverlays().remove only removes 1 Marker


I'm using OSMDroid and have a bunch of different markers and trying to toggle marker overlays on/off using a checkbox setup. I grab a json array and get my data to create my markers as well as their gps location. All that works great.

I can show the markers fine using:

mapView.getOverlays().add(overlay);

but when I try to reverse it using:

mapView.getOverlays().remove(overlay);

Sadly, it only removes the last placed marker and not all of them. Please tell me where my failure lies. Thanks!

EDIT Additional code:

List<OverlayItem> itemList = new ArrayList<OverlayItem>();
GeoPoint geoPoint = new GeoPoint(lat, lng);
overlayItem = new OverlayItem("Title", "Snippet", geoPoint);

overlayItem.setMarker(getResources().getDrawable(R.drawable.marker));

itemList.add(overlayItem);

overlay = new ItemizedOverlayWithFocus<OverlayItem>(getApplicationContext(), itemList, 
        new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {

            @Override
            public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
            // This will do something eventually
            return true;
            }

            @Override
            public boolean onItemLongPress(final int index, final OverlayItem item) {
            // This will do something eventually
            return false;
            }
        });

mapView.getOverlays().add(overlay);

SOLUTION (This worked for me)

ArrayList<Marker> myMarkers= new ArrayList<>();

Marker myMarker = new Marker(mapView);
                    myMarker.setPosition(new GeoPoint(lat, lng));
                    myMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
                    myMarker.setTitle(TITLE);
                    myMarker.setIcon(getResources().getDrawable(R.drawable.myMarker));
                    myMarker.setSnippet(SNIPPET);
                    mapView.getOverlays().add(myMarker);
                    myMarkers.add(myMarker);

Then I was able to toggle ALL markers off with:

for (Marker m : myMarkers) {
     mapView.getOverlays().remove(m);
     }

Solution

  • You haven't shown enough code to be sure, but I guess, your myMarker variable holds a reference to the last added marker and so you remove only the last one.

    You should keep references to all your markers (e.g. in List) and go through them when removing.

    Or you may use FolderOverlay for grouping and easy removal of all markers.