Search code examples
androidgoogle-mapsgoogle-maps-markersgoogle-polyline

How to clear Google map v2 except few markers?


Suppose i have 100 markers on the map what i want is when i apply GoogleMap.clear(); to clear the map it clear all the other markers on the map except 2 markers and 1 polyline between them a path.

say

 marker1 = GoogleMap .addMarker(new MarkerOptions().position(latLng1).title(A));

 marker2 = GoogleMap .addMarker(new MarkerOptions().position(latLng2).title(B));

 line = GoogleMap.addPolyline(options1);

I don't want to clear these three. I want this so user don't have to experience a blink.


Solution

  • There is no way to clear everything except some things. However, you can keep a reference to any markers that you want to clear and loop over them.

    ArrayList<Marker> markersToClear = new ArrayList<Marker>();
    
    marker1 = GoogleMap.addMarker(new MarkerOptions().position(latLng1).title(A));
    marker2 = GoogleMap.addMarker(new MarkerOptions().position(latLng2).title(B));
    marker3 = GoogleMap.addMarker(new MarkerOptions().position(latLng3).title(C));
    
    markersToClear.add(marker2);
    markersToClear.add(marker3);
    
    for (Marker marker : markersToClear) {
        marker.remove();
    }
    
    markersToClear.clear();
    
    // marker1 left on map