来源:http://blog.csdn.net/mwthe/article/details/49780161
主类中:
完成各种view初始化后,添加该代码
MyTouchListener myListener = new MyTouchListener(context, mapView,graphicsLayer);
mapView.setOnTouchListener(myListener);
1、当点击地图时,将点添加到图层上并且将其渲染;
2、当在屏幕上滑动时,将滑动生成的点逐步添加到poly变量中;
3、当滑动完离开屏幕时,判断是绘制的线还是面,当是面时,将第一个点追加到poly变量中,并将poly变量添加到图层中去。
监听类:
public class MyTouchListener extends MapOnTouchListener {
//此变量是用来保存线或者面的轨迹数据的
MultiPath poly;
//判断是执行的哪种绘图方式,它可以为这三种值:point,polgyline,polgyon
String type = "";
//绘画点时用于储存点的变量
Point startPoint = null;
//地图
public MapView mapView;
//图层
public GraphicsLayer graphicsLayer;
//构造方法
public MyTouchListener(Context context, MapView view) {
super(context, view);
}
//设置drawe的类型
public void setType(String geometryType) {
this.type = geometryType;
}
public String getType() {
return this.type;
}
//当我们绘制点时执行的处理函数
public boolean onSingleTap(MotionEvent e) {
if (type.length() > 1 && type.equalsIgnoreCase("POINT")) {
graphicsLayer.removeAll();//绘制点时首先清除图层要素
//生成点图形,并设置相应的样式
Graphic graphic = new Graphic(mapView.toMapPoint(new Point(e.getX(), e
.getY())),new SimpleMarkerSymbol(Color.RED,25,SimpleMarkerSymbol.STYLE.CIRCLE));
//将点要素添加到图层上
graphicsLayer.addGraphic(graphic);
//设置按钮可用
clearButton.setEnabled(true);
return true;
}
return false;
}
//当绘制线或者面时调用的函数
public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
if (type.length() > 1
&& (type.equalsIgnoreCase("POLYLINE") || type.equalsIgnoreCase("POLYGON"))) {
//得到移动后的点
Point mapPt = mapView.toMapPoint(to.getX(), to.getY());
//判断startPoint是否为空,如果为空,给startPoint赋值
if (startPoint == null) {
graphicsLayer.removeAll();
poly = type.equalsIgnoreCase("POLYLINE") ?new Polyline()
: new Polygon();
startPoint = mapView.toMapPoint(from.getX(), from.getY());
//将第一个点存入poly中
poly.startPath((float) startPoint.getX(),(float) startPoint.getY());
Graphic graphic = new Graphic(startPoint,new SimpleLineSymbol(Color.RED,5));
graphicsLayer.addGraphic(graphic);
}
//将移动的点放入poly中
poly.lineTo((float) mapPt.getX(), (float) mapPt.getY());
return true;
}
return super.onDragPointerMove(from, to);
}
//当绘制完线或面,离开屏幕时调用的函数
@Override
public boolean onDragPointerUp(MotionEvent from, MotionEvent to) {
if (type.length() > 1
&& (type.equalsIgnoreCase("POLYLINE") || type
.equalsIgnoreCase("POLYGON"))) {
//判断当绘制的是面时,将起始点填入到poly中形成闭合
if (type.equalsIgnoreCase("POLYGON")) {
poly.lineTo((float) startPoint.getX(),
(float) startPoint.getY());
graphicsLayer.removeAll();
graphicsLayer.addGraphic(new Graphic(poly,new SimpleFillSymbol(Color.RED)));
}
//最后将poly图形添加到图层中去
graphicsLayer.addGraphic(new Graphic(poly,new SimpleLineSymbol(Color.BLUE,5)));
startPoint = null;
clearButton.setEnabled(true);
return true;
}
return super.onDragPointerUp(from, to);
}
}