DixieFlatline
DixieFlatline

Reputation: 8035

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?

Upvotes: 2

Views: 6160

Answers (2)

Alexey Glukharev
Alexey Glukharev

Reputation: 101

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

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

Upvotes: 3

NickT
NickT

Reputation: 23873

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

Upvotes: 7

Related Questions