I want to remove a current marker after long click on map anywhere and recreate a new marker at that point. I have cleared google map on long click on map and new marker is crea
For the people who have tried the first solution in this question and you get the error of Marker has not been intialized.
Because, we are comparing the marker and null. When we have not even intialized the marker in the first place.
Solution:
Int mMarkerCount = 0; //Global Variable
Marker mMarker; //Global Variable
if(mMarkerCount > 0){
if(mMarker != null){
mMarker.remove();
}
}
mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
mMarkerCount++;
The Solution for the question:
Int mMarkerCount = 0; //Global Variable
Marker mMarker;
mMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latlng) {
if(mMarkerCount > 0){
if(mMarker != null){
mMarker.remove();
}
}
mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
mMarkerCount++;
}
});
In the beginning, the count is going to be zero. So, the marker remove method will not be called. Once, the marker is intialized and the count is incremented. We can remove the previous marker by the help of the remove method and create a new marker as shown in the code.