This is actually very simple, all you need to do is check if the point that the user clicks on is further than your required distance before removing the previous Marker and adding the new one.
You can use the Location.distanceBetween()
method to do the distance check.
First, create your Marker reference as an instance variable of the Activity:
Marker marker;
Then, in your OnMapClickListener, add the logic to only move the Marker that the user chooses as the current location if the distance is greater than your defined minimum distance, 20 meters in this example:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
if (marker != null) {
LatLng markerPoint = marker.getPosition();
float[] distance = new float[2];
Location.distanceBetween(point.latitude, point.longitude,
markerPoint.latitude, markerPoint.longitude, distance);
//check if new position is at least 20 meters away from previous selection
if( distance[0] > 20 ){
//remove previous Marker
marker.remove();
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
else{
//Alert the user to select a location further away from the one already selected
Toast.makeText(MainActivity.this, "Please select a different location.", Toast.LENGTH_SHORT).show();
}
}
else {
//No previous selection, place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
}
});