解决方法
我必须为我的一个项目实现可拖动标记.我找到的唯一解决方案是扩展现有的Marker类,同时检查拖动事件并相应地更新标记位置.
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 = p.x - event.getX(); mDy = p.y - 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; } }
稍后您需要在MapView上的触摸事件上添加侦听器,并检查您的标记(或标记集合中的许多标记之一)是否受事件影响.
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); } });