Search code examples
androidandroid-mapviewitemizedoverlay

How to delete all markers from the mapview with one click in Android?


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?


Solution

  • .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();