上一讲中我们学会了如何在MapView中添加Graphic要素,那么在百度或高德地图中,当我们点击要素时,会显示出相应的详细信息。在GraphicsLayer中也提供了这样的方法。下面我们来学习在GraphicsLayer中如何点击查找要素。 首先在MapView中添加两个Graphic要素。代码如下,注意这里用( geometry, symbol, Map<String, Object> attributes)来实例化Graphic,Map<String, Object> attributes是要素的属性值。详细见以下代码。TILED_WORLD_STREETS_URL为网络图层地址。
- private void initLayer() {
- mapView.addLayer(new ArcGISTiledMapServiceLayer(
- TILED_WORLD_STREETS_URL));
- graphicsLayer = new GraphicsLayer();
- mapView.addLayer(graphicsLayer);
- Polygon polygon = new Polygon();
- polygon.startPath(new Point(1.2575908509778766E7,2879410.9266042486));
- polygon.lineTo(new Point(1.284360696117901E7,3021972.232083669));
- polygon.lineTo(new Point(1.2826182801620414E7,2713089.403544925));
- Map<String, Object> attr1 = new HashMap<>();
- attr1.put("name", "广州");
- attr1.put("mark", "广州是南方的城市");
- Graphic graphic1 = new Graphic(polygon, new SimpleFillSymbol(Color.RED),attr1);
- graphicsLayer.addGraphic(graphic1);
- Polygon polygon2 = new Polygon();
- polygon2.startPath(new Point(1.3388507951011453E7,3611225.628065273));
- polygon2.lineTo(new Point(1.3607101952746565E7,3858331.890896268));
- polygon2.lineTo(new Point(1.3613438010767872E7,3449656.14852193));
- Map<String, Object> attr2 = new HashMap<>();
- attr2.put("name", "上海");
- attr2.put("mark", "上海是中部的城市");
- Graphic graphic2 = new Graphic(polygon2, new SimpleFillSymbol(Color.GREEN),attr2);
- graphicsLayer.addGraphic(graphic2);
- }
效果图如下:
准备工作完成后,设置MapView的点击事件,
- mapView.setOnSingleTapListener(new OnSingleTapListener() {
- @Override
- public void onSingleTap(float x, float y) {
- // TODO Auto-generated method stub
- handleSingleTap(x,y);
- }
- });
在handleSingleTap方法中来处理查询事件,GraphicsLayer查询要用到(float x, float y, int tolerance, int numberOfResults)或者(float x, float y, int tolerance)方法,前面两个参数是地图点击时的
x与y的值,tolerance是围绕x与y这个点所查询的范围,numberOfResults是要返回结果的大小。
- /**
- * GraphicsLayer的点击查询
- * @param x
- * @param y
- */
- protected void handleSingleTap(float x, float y) {
- int[] graphicIds = graphicsLayer.getGraphicIDs(x, y, 8);
- if (graphicIds!=null&&graphicIds.length>0) {
- for (int i = 0; i < graphicIds.length; i++) {
- Graphic graphic = graphicsLayer.getGraphic(graphicIds[i]);
- Map<String,Object> attr = graphic.getAttributes();
- Log.i(TAG, attr.get("name")+"===="+attr.get("mark"));
- }
- }
- }这样当我们点击要素时,会打出以下的信息。