In the new Google Maps API for Android, we can add a marker, but there is no way to (easily) remove one.
My solution is to keep the markers in a map and redraw the map when I want to remove a marker, but it is not very efficient.
private final Map<String, MarkerOptions> mMarkers = new ConcurrentHashMap<String, MarkerOptions>();
private void add(String name, LatLng ll) {
final MarkerOptions marker = new MarkerOptions().position(ll).title(name);
mMarkers.put(name, marker);
runOnUiThread(new Runnable() {
@Override
public void run() {
mMap.addMarker(marker);
}
});
}
private void remove(String name) {
mMarkers.remove(name);
runOnUiThread(new Runnable() {
@Override
public void run() {
mMap.clear();
for (MarkerOptions item : mMarkers.values()) {
mMap.addMarker(item);
}
}
});
}
Does anyone have a better idea?
Best Answer
The method signature for
addMarker
is:So when you add a marker to a
GoogleMap
by specifying the options for the marker, you should save theMarker
object that is returned (instead of theMarkerOptions
object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can callMarker.remove()
to remove it from the map.As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling
Marker.setVisible(boolean)
.