【移动GIS】如何监听地图操作事件?


在android地图开发过程中,我们常常会有这样一种需求:当点击或长按地图时,然后做一些事。比如:当我长按地图某一处时,为该处添加给图标

说下思路,首先创建一个图层,该图层继承overlay,然后在该图层中实现onLongPress接口,然后再把该图层添加到mapview中。

好了废话到此为止了,先来个效果图吧。当长按地图时添加一个marker:

 

现在说说代码吧,创建一个层叫MapEventsOverlay:

private class MapEventsOverlay extends Overlay{
		@Override
		public boolean onLongPress(MotionEvent e,MapView mv){
			Projection proj = mapView.getProjection();//获得投影对象		
	                GeoPoint  gp = (GeoPoint) proj.fromPixels(e.getX(), e.getY());//坐标转换
                        /**********自己写你要做的事咯,自己YY吧***********/

			mapView.invalidate();//重绘地图			
                       return true;
		}
		@Override
		protected void draw(Canvas c, MapView osmv, boolean shadow) {
		}
		public MapEventsOverlay(Context ctx) {
			super(ctx);
		}
	}

然后再把该层添加到mapview中:

MapEventsOverlay mo = new MapEventsOverlay(context);
  mapView.getOverlayManager().add(mo);

好了,这就完事了

-----------------------------------------------------------------------------华丽分割线---------------------------------------------------------------------------------------------------

当然你也可以将此类独立出来,然后再另外创建一个接口类,这样其它地方也可以用了,干脆我把独立后的代码一并贴出来吧:

MapEventsOverlay:

 

public class MapEventsOverlay extends Overlay {

	private MapEventsReceiver mReceiver;
	
	/**
	 * @param ctx the context
	 * @param receiver the object that will receive/handle the events. 
	 * 必须实现 MapEventsReceiver 接口. 
	 */
	public MapEventsOverlay(Context ctx, MapEventsReceiver receiver) {
        super(ctx);
		mReceiver = receiver;
    }

	@Override protected void draw(Canvas c, MapView osmv, boolean shadow) {
		//Nothing to draw
	}
	
	@Override public boolean onSingleTapUp(MotionEvent e, MapView mapView){
		Projection proj = mapView.getProjection();
		IGeoPoint p = proj.fromPixels(e.getX(), e.getY());
		return mReceiver.singleTapUpHelper(p);
	}
	
	@Override public boolean onLongPress(MotionEvent e, MapView mapView) {
		Projection proj = mapView.getProjection();
		IGeoPoint p = proj.fromPixels(e.getX(), e.getY());
		//throw event to the receiver:
		return mReceiver.longPressHelper(p);
    }

}


接口类:MapEventsReceiver

public interface MapEventsReceiver {

	
	boolean singleTapUpHelper(IGeoPoint p);
	
	
	boolean longPressHelper(IGeoPoint p);	
}


 

再来个使用例子吧:

 

public class MapEventsDemo extends Activity implements MapEventsReceiver {
	private MapView mapView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/************一些你自己的设置*****************/

		MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(
				getApplicationContext(), this);

		mapView.getOverlays().add(mapEventsOverlay);
	}


	//长按地图时触发
	@Override
	public boolean longPressHelper(IGeoPoint igeo) {
		/**添加你的代码吧**/
		mapView.invalidate();
		return true;
	}

	@Override
	public boolean singleTapUpHelper(IGeoPoint arg0) {
		return false;
	}

}


 

好了,到此完工,你会了么?

你可能感兴趣的:(【移动GIS】如何监听地图操作事件?)