百度地图长按事件

地图版本: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);
	}


参考:http://www.kind-kristiansen.no/2011/android-handling-longpresslongclick-on-map-revisited/

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

说明:

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

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

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

转载于:https://my.oschina.net/xesam/blog/138350

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值