Can I restrict the dragging of marker in maps to a particular country? I don't want user to drag the marker outside India because of some features of my application.
-
1The difficult part may depend on how precise you need to model the border. Ultimately you'll have to perform a test on the position against some boundary using LatLngBounds/Builder as @Mauker suggests. – Mar 06 '18 at 15:14
1 Answers
Yes, you can restrict where the marker may be placed.
Take a look at the GoogleMap.OnMarkerDragListener. You'll see that this interface has three methods.
onMarkerDrag(Marker marker)
onMarkerDragEnd(Marker marker)
onMarkerDragStart(Marker marker)
First, you'll have to listen for the onMarkerDrag
events. Do that by setting the listener to your map instance, like:
mMap.setOnMarkerDragListener(new OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
// ...
}
@Override
public void onMarkerDragEnd(Marker marker) {
// Use this method to detect when the user stopped dragging the marker.
}
@Override
public void onMarkerDrag(Marker marker) {
// Listen to this method to check the marker position.
}
});
That method will be called every time you try to drag the marker somewhere.
Once you detect that event, you may continuously check the marker position by calling myMarker.getPosition()
, and compare it to some boundary. See the LatLngBounds class, and its Builder for more info on that.
If the marker ever crosses that boundary, make it "undraggable" by calling the marker setDraggable method, like below:
myMarker.setDraggable(false)
And then, on the onMarkerDragEnd
method, make it draggable once again, otherwise the user won't be able to drag the marker after he crosses the boundary:
myMarker.setDraggable(true)

- 11,237
- 7
- 58
- 76