How can I drag and drop a marker in a limited area?

How can I drag and drop a marker in a limited area? For instance, a circle has 20 meters radius. User can only drag and drop inside the circle. Here is the code I’ve tried.

map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng latLng) {
        mymarker.setPosition(latLng);
        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
});

map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
    @Override
    public void onMarkerDragStart(Marker arg0) {
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onMarkerDragEnd(Marker arg0) {
        Log.d("System out", "onMarkerDragEnd...");
        map.animateCamera(CameraUpdateFactory.newLatLng(arg0.getPosition()));
    }

    @Override
    public void onMarkerDrag(Marker arg0) {
    }
});

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

When drag starts you can move map to bounds in which you want to limit dragging. And disable map gestures to prevent map moving. If you have zoom or my location controls they can be disabled here as well. After drag ends you enable them back. map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 15)); map.getUiSettings().setAllGesturesEnabled(false); } @Override public void onMarkerDrag(Marker marker) {} @Override public void onMarkerDragEnd(Marker marker) { map.getUiSettings().setAllGesturesEnabled(true); } }); To get LatLngBounds by center and radius you can use this answer.