tyczj tyczj - 9 months ago 68
Android Question

Getting a map marker by its ID in Google Maps v2

basically when adding a marker to the map it returns the new marker and you can gets the marker id from it like so

Marker m = map.addMarker(new MarkerOptions()
.position(new LatLng(lat,lon)));
String id = m.getId();

is there a way to get a marker by its id if there are many markers and you just want to delete one?

Answer Source

The problem is that the marker id is generated automaticlly and cannot be used for tracking the markers individually. A number of strategies have been proposed work around this. One would be to use a hash map to track markers and then use a key you choose to find a speific marker and remove it. Another idea is to overload one of the marker fields, like snippet, and then add a key yourself. For example, if you were making a new marker (using the google example code) you could put your own key string into the snippet field

mMap.addMarker(new MarkerOptions()                           
.snippet(KEY + "Population: 4,137,400"));

Later you could retrive that key using

String s = marker.getSnippet()
String key = s.substring(start, end)

and then use a conditional to remove a specific marker if it is a match. Depending on whatyou need to do one approach my be easier and more efficient than another.