2

I have 2 markers on the map and i want to delete them when the user clicks on a button. This is my method:

 public void deleteAllMarkers() {
    if(mapView.getOverlays().size() !=0) { 
        //Log.d("MAPA ",Integer.toString(mapView.getOverlays().size()));
        for (int i=0; i<mapView.getOverlays().size(); i++ ) {
            mapView.getOverlays().remove(i);
        }
        mapView.postInvalidate();
    }   
}

The problem is that i have to press my button twice to get rid of both markers, because after the first press only 1 marker disappears.

What am i doing wrong?

DixieFlatline
  • 7,895
  • 24
  • 95
  • 147

2 Answers2

7

.size() will get re-evaluated on each iteration, i.e. after you've removed element 0.

It would be easier to write:

mapView.getOverlays().clear();
NickT
  • 23,844
  • 11
  • 78
  • 121
  • I have successfully used this function several times (on menu, button, `onPause()` ...), but I wander why it does not take effect when I call it in this context: `onLocationChanged(Location location) { mapview.getOverlays().clear();}`. If anybody knows something about this issue, please tell me... – AlexAndro Jun 27 '12 at 13:03
  • Notice: You have to make an additional call, to also remove potential `InfoWindow`s, as they won't be removed along with the markers: `mapView.overlays.forEach { (it as Marker).infoWindow.close() }` (Kotlin) – msal Jul 03 '22 at 17:05
3

The more fair solution is removing only Markers without any other layouts (like Compas, Copyright, etc)

mapView.overlays
                .forEach { (it as? Marker)?.remove(mapView) }