How does one implement drag and drop for Android marker?
Implement Google Maps Android API v2, refer this: https://developers.google.com/maps/documentation/android/ and set on GoogleMap object setOnMarkerDragListener. For Ex:
map.setOnMarkerDragListener(new OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker arg0) { // TODO Auto-generated method stub Log.d("System out", "onMarkerDragStart..."+arg0.getPosition().latitude+"..."+arg0.getPosition().longitude); } @SuppressWarnings("unchecked") @Override public void onMarkerDragEnd(Marker arg0) { // TODO Auto-generated method stub Log.d("System out", "onMarkerDragEnd..."+arg0.getPosition().latitude+"..."+arg0.getPosition().longitude); map.animateCamera(CameraUpdateFactory.newLatLng(arg0.getPosition())); } @Override public void onMarkerDrag(Marker arg0) { // TODO Auto-generated method stub Log.i("System out", "onMarkerDrag..."); } });//Don't forget to Set draggable(true) to marker, if this not set marker does not drag.map.addMarker(new MarkerOptions() .position(crntLocationLatLng) .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_my_location)) .draggable(true));
Here is a sample project from one of my books showing drag-and-drop movement of markers on a Google Map in Android.
In a nutshell, it uses onTouchEvent()
to detect when the user touches and holds their finger near a marker. It then removes the marker from the overlay, but puts the same image over top of the map using RelativeLayout
. Then, on "move" touch events, the image is moved (faster than forcing the whole overlay to redraw). When the finger is lifted, the image is removed, but the marker is put back in the overlay at the new spot.
For MapsV2. Use the google map events. Don't write your own.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { mVisitingMarker.setPosition(latLng); mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } }); mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker arg0) { } @SuppressWarnings("unchecked") @Override public void onMarkerDragEnd(Marker arg0) { Log.d("System out", "onMarkerDragEnd..."); mMap.animateCamera(CameraUpdateFactory.newLatLng(arg0.getPosition())); } @Override public void onMarkerDrag(Marker arg0) { } });