正文  第三方集成 > 百度地图集成 >

百度地图长按事件代码详解 android开发

百度地图长按事件代码详解地图版本:1.3.5import java.util.Timer;import java.util.TimerTask;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import......

百度地图长按事件代码详解

地图版本:1.3.5
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MapView;

public class MyMapView extends MapView {
	
	private MyMapView mThis = MyMapView.this;
	
	public interface MyLongPressListener {
		public void apply(MapView view, GeoPoint point);
	}
	
	private Timer longpressTimer = new Timer();
	static final int LONGPRESS_THRESHOLD = 1000;
	static final int MOVABLE_REGION = 200;
	
	private MyLongPressListener longPressListener ;
	
	public MyMapView(Context arg0) {
		super(arg0);
	}

	public MyMapView(Context arg0, AttributeSet arg1) {
		super(arg0, arg1);
	}

	public MyMapView(Context arg0, AttributeSet arg1, int arg2) {
		super(arg0, arg1, arg2);
	}
	
	public void setMyLongPressListener(MyLongPressListener listener){
		longPressListener = listener;
	}
	
	private float mLastMotionX;
	private float mLastMotionY;
	
	@Override
	public boolean onTouchEvent(MotionEvent event){
		handleLongpress(event);
		return super.onTouchEvent(event);
	}
	
	private void handleLongpress(final MotionEvent event) {

		final float y = event.getY();
		final float x = event.getX();
		
		if (event.getPointerCount() > 1) {
			longpressTimer.cancel();
			return;
		}

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			mLastMotionX = x;
			mLastMotionY = y;
			longpressTimer = new Timer();
			longpressTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					if(null != longPressListener){
						mThis.post(new Runnable() {
							
							@Override
							public void run() {
								longPressListener.apply(mThis, MapHelper.fromXYtoPoint(mThis, mLastMotionX, mLastMotionY));
							}
						});
					}
				}

			}, LONGPRESS_THRESHOLD);
		}

		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			final int deltaX = (int) (x - mLastMotionX);
			final int deltaY = (int) (y - mLastMotionY);
			if(deltaX * deltaX + deltaY * deltaY > MOVABLE_REGION){
				longpressTimer.cancel();
			}
		}

		if (event.getAction() == MotionEvent.ACTION_UP) {
			longpressTimer.cancel();
		}
	}
}

	public static GeoPoint fromXYtoPoint(MapView mMapView, float x, float y) {
		return mMapView.getProjection().fromPixels((int) x, (int) y);
	}

 

不过上面的那篇不能满足要求。

说明:

1,本来是想用Overlay的,但是百度地图的Overlay的 boolean onTouchEvent(MotionEvent arg0, MapView mapView)无法检测到多根手指,于是只好继承MapView。

2,无论如何都会触发move事件,所以设置了一个MOVABLE_REGION容许误差。

3,顺便吐嘈一下,百度的2.x版本真心不厚道。