touchingtwist touchingtwist - 29 days ago 13
Android Question

How to remove specific marker on Android GoogleMap

CODE:

private Marker mCurrentMarker;
private ArrayList<Marker> mMarkerArrayList;

@Override
public void onMapReady(final GoogleMap googleMap) {
mGoogleMap = googleMap;

mMarkerArrayList = new ArrayList<>();
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {

MarkerOptions marker_onclick = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title(getString(R.string.now_your_location));
if (mMarkerArrayList.size() > 0){
Marker marker_to_remove = mMarkerArrayList.get(0);
marker_to_remove.remove();
}

mCurrentMarker = mGoogleMap.addMarker(marker_onclick);

mGoogleMap.addMarker(marker_onclick);
mMarkerArrayList.add(mCurrentMarker);

}
});
}


I want that when i click on map, there will be an marker related in showing clicked location. And marker which has been before is removed. So, there are only one marker related in showing clicked location.

I already know
mGoogleMap.clean();
can clean map, also markers on map.

But i want remove specific marker. (Because, On my application, there are many kind of markers. For example, home marker is showing where user's home is, and busstop marker is showing where busstop is.)

So i made arraylist and tried to use it.

But it didn't work.

I think when i click on map,
addmarker();
is working well but
.remove();
seems to be not working.

Where is the error?

How can i remove specific marker only?

I read : How to remove the marker in Google map v2?

Answer

When you add a marker on Map, you can store it into HashMap like this:

 HashMap<YourUniqueKey,Marker> hashMapMarker = new HashMap<>();
 Marker marker = googleMap.addMarker(markerOptions);
 hashMapMarker.put(YourUniqueKey,marker);

At the time you want to delete particular marker just get your Maker by YourUniqueKey for that marker like this:

Marker marker = hashMapMarker.get(YourUniqueKey);
marker.remove();
hashMapMarker.remove(YourUniqueKey);
Comments