如上圖,點擊某塊,然后高亮顯示選中的這塊區域(本例中是紅色的那個塊)。
---------------------------
編碼過程:
1.注冊 mapView的單擊事件
mMapView.setOnSingleTapListener(mOnSingleTapListener);
2.實現單擊的時間的監聽器
OnSingleTapListener mOnSingleTapListener = new OnSingleTapListener() { @Override public void onSingleTap(float x, float y) { new AsyncQueryTask().execute(x, y); } };
我們具體在一個AsyncQueryTask里異步執行查詢和顯示。
在上面的onSingleTap方法里有有兩個參數 (float x, float y) ,這個是一個坐標點,表示里你點擊的位置,是個屏幕坐標,在查詢時,我們需要將其轉成 地圖坐標點,使用方法
mMapView.toMapPoint(x,y)
class AsyncQueryTask extends AsyncTask<Float, Void, FeatureSet> { String errMsg = null; @Override protected FeatureSet doInBackground(Float... params) { float x = params[0]; float y = params[1]; if (mMapView.isLoaded()) { // AlertMsg("單擊,屏幕像素坐標點: x=%s,y=%s", x, y); // Point mapPoint = mMapView.toMapPoint(new Point(x, y)); Point pt = mMapView.toMapPoint(x, y); Query query = new Query(); query.setGeometry(pt); query.setReturnGeometry(true); //query.setOutFields(new String[] {"*"}); query.setOutFields(new String[] { "縣名稱_1", "鄉名稱_1", "村名稱_1", "地塊名稱", "統一編號" }); QueryTask queryTask = new QueryTask(mMapServiceUrl + "/4");//這里參數是地圖的服務地址,后面的4,標識了是其中某一個圖層。 try { FeatureSet fs = queryTask.execute(query); return fs; } catch (Exception e) { e.printStackTrace(); errMsg = e.getMessage(); } } return null; }
我們構建一個 query 和 queryTask 進行查詢,
查詢條件: query.setGeometry(pt);
返回的字段內容:query.setOutFields(new String[] { "縣名稱_1", "鄉名稱_1", "村名稱_1", "地塊名稱", "統一編號" });
返回的結果是 FeatureSet 就是想要獲得區域。
3.從返回的結果中拿到 grphics 並繪制在一個 自定義的圖層上 ,並指定繪制方式。
@Override protected void onPostExecute(FeatureSet fs) { if (fs == null) { if (errMsg != null) { Toast.makeText(CT_Area_ViewActivity.this, errMsg, 0).show(); } Toast.makeText(CT_Area_ViewActivity.this, "查詢的結果為空", 0).show(); return; } try { Toast.makeText(CT_Area_ViewActivity.this, "查詢到" + fs.getGraphics().length + "個結果", 0).show(); SimpleFillSymbol symbol = new SimpleFillSymbol(Color.RED); CT_Area_ViewActivity.this.gLayer .setRenderer(new SimpleRenderer(symbol)); CT_Area_ViewActivity.this.gLayer.removeAll(); CT_Area_ViewActivity.this.gLayer.addGraphics(fs.getGraphics()); if (fs.getGraphics().length > 0) { Graphic graphic = fs.getGraphics()[0]; // String[] names = graphic.getAttributeNames(); String xian = getValue(graphic, "縣名稱_1", ""); String xiang = getValue(graphic, "鄉名稱_1", ""); String cun = getValue(graphic, "村名稱_1", ""); String dikuai = getValue(graphic, "地塊名稱", ""); String id = getValue(graphic, "統一編號", ""); ShowDialog_Detail(xian + xiang + cun + "\n" + dikuai, id); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(CT_Area_ViewActivity.this, e.getMessage(), 0) .show(); } } String getValue(Graphic graphic, String key, String defaultVal) { Object obj = graphic.getAttributeValue(key); if (obj == null) return defaultVal; else return obj.toString(); } }
別忘了聲明一些 類變量:
com.esri.android.map.MapView mMapView;
ArcGISDynamicMapServiceLayer agmServiceLayer;
GraphicsLayer gLayer;