Reputation: 113
I want to remove multiple specific markers from Google Maps but I can't do it. I already know about marker.remove();
and mMap.clear();
but they don't help me. Look at the code below how I create multiple marker.
private ArrayList<String> pup_latList01;
private ArrayList<String> pup_longList01;
private ArrayList<String> pup_nameList01;
for(int i = 0 ;i< pup_nameList01.size();i++)
{
LatLng puplatlang = new LatLng(Double.parseDouble(pup_latList01.get(i)),Double.parseDouble(pup_longList01.get(i)));
pupMarker = mMap.addMarker(new MarkerOptions().position(puplatlang).title(pup_nameList01.get(i)).draggable(true).icon(bitmapDescriptorFromVector(MapsActivity.this, R.drawable.bus_stop_small)));
}
I want to remove marker only from create from pupMarker
Marker object.
I also have other marker created from other objects. When I use pupMarker.remove();
it removes only last created marker from above code
and mMap.clear();
removes all markers from the map.
Upvotes: 1
Views: 1495
Reputation: 137
When you create a marker with googleMap.addMarker(...), you receive a Marker object, which represents it. That is, each marker object for each marker on the map.
So, for example, you would add markers you like in a specific list group.
Steps:
Upvotes: 2
Reputation: 972
In this code pupMarker is always the last marker on the list. So when you use pupMarker.remove();
it only removes the last created marker. You can make a List that will hold all these Markers and then get the one you want to remove.
Edit 1:
It's probably better to use HashMap instead of List for holding references to Markers. It will be easier later to find it with a key in the Map.
Edit 2:
Example of this as requested in the comment:
private HashMap<Integer, Marker> hashMapMarker = new HashMap<>();
for(int i = 0 ;i< pup_nameList01.size();i++)
{
LatLng puplatlang = new LatLng(Double.parseDouble(pup_latList01.get(i)),Double.parseDouble(pup_longList01.get(i)));
Marker pupMarker = mMap.addMarker(new MarkerOptions().position(puplatlang).title(pup_nameList01.get(i)).draggable(true).icon(bitmapDescriptorFromVector(MapsActivity.this, R.drawable.bus_stop_small)));
hashMapMarker.put(i, pupMarker);
}
Note that if using Integer for a key is probably better to use SparseArray instead of HashMap.
private void removeMarker(int position){
hashMapMarker.get(positon).remove();
hashMapMarker.remove(position);
}
Upvotes: 1