I had to implement drag-and-drop handles for one of my projects. The only solution I found was to extend the existing Marker class with mehod checked for a drag event and update the marker position accordingly.
package com.example.map; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.mapbox.mapboxsdk.api.ILatLng; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.overlay.Marker; import com.mapbox.mapboxsdk.views.MapView; import com.mapbox.mapboxsdk.views.util.Projection; public class DraggableMarker extends Marker { private static final String TAG = "map.DraggableMarker"; private boolean mIsDragged; private static final RectF mTempRect = new RectF(); private static final PointF mTempPoint = new PointF(); private float mDx, mDy; public DraggableMarker(String title, String description, LatLng latLng) { super(title, description, latLng); mIsDragged = false; } public DraggableMarker(MapView mv, String aTitle, String aDescription, LatLng aLatLng) { super(mv, aTitle, aDescription, aLatLng); mIsDragged = false; } public boolean drag(View v, MotionEvent event) { final int action = event.getActionMasked(); if(action == MotionEvent.ACTION_DOWN) { Projection pj = ((MapView)v).getProjection(); RectF bound = getDrawingBounds(pj, mTempRect); if(bound.contains(event.getX(), event.getY())) { mIsDragged = true; PointF p = getPositionOnScreen(pj, mTempPoint); mDx = px - event.getX(); mDy = py - event.getY(); } } if(mIsDragged) { if((action == MotionEvent.ACTION_CANCEL) || (action == MotionEvent.ACTION_UP)) { mIsDragged = false; } else { Projection pj = ((MapView)v).getProjection(); ILatLng pos = pj.fromPixels(event.getX() + mDx, event.getY() + mDy); setPoint(new LatLng(pos.getLatitude(), pos.getLongitude())); } } return mIsDragged; } }
Later, you need to add a listener on touch events to MapView and check if your marker (or one of many in your marker collection) is affected.
mMarker = new DraggableMarker(mMapView, "", "", aCenter); mMarker.setIcon(new Icon(getActivity().getApplicationContext(), Icon.Size.SMALL, "marker-stroked", "FF0000")); mMapView.addMarker(mMarker); mMapView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mMarker.drag(v, event); } });
source share