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?
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()
.position(MELBOURNE)
.title("Melbourne")
.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.
I have done this way:
Initialize variables:
private GoogleMap mMap;
private HashMap<Marker, Integer> mHashMap = new HashMap<Marker, Integer>();
private ArrayList<MyCustomModelClass> myList = new ArrayList<MyCustomModelClass>();
Add marker on google map using your arraylist:
for (int i = 0; i < myList.size(); i++) {
double latitude = myList.getLatitude();
double longitude = myList.getLongitude();
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude))).title(myList.getTitle())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon));
mHashMap.put(marker, i);
}
On marker click listener:
@Override
public boolean onMarkerClick(Marker marker) {
int pos = mHashMap.get(marker);
Log.i("Position of arraylist", pos+"");
}
Hope this will help you.
Use WeakHashMap<Integer,Marker>
to store markers because in this way, we wouldn't keep a reference to a Marker in memory, and wouldn't have to worry about garbage collected markers.
secondly recommended way to do this is to have a WeakHashMap with ID and your custom data. The documentation says that marker object may change, so don't use the marker as the key. if the activity is killed and restored but the ID will remain the same. sometime it may return null also if marker objects changed.
WeakHashMap<Integer,Marker> obj = new WeakHashMap <Integer,Marker>();
Hope it will help future viewers...
The best way to do this is using a Map <int, Mark> dictionaryMark;
.
Just add the mark into your dictionary each time you draw it.
I know, its very late. But now, we can directly add a unique TAG to a marker.
Marker marker = mMap.addMarker(markerOptions);
marker.setTag("");
Google Developers link about map marker TAG