Arcgis for android 离线查询

时间:2022-10-22 16:34:59

参考.. 官方API demo 。。。 各种资料

以及。。

  1. ArcGIS for Android示例解析之高亮要素-----HighlightFeatures
  2. ttp://blog.csdn.net/wozaifeiyang0/article/details/7323606
  1. arcgis android 中 Geodatabase geodata = new Geodatabase(filepath);得到geodata为空
  2. http://zhidao.baidu.com/link?url=iH5IDhbjIKOrZE3WffmhHwJ2ZqFF8AzU8tir8qvSl_BP5AUIHiGSc3aKbqZ7MWVHS1_8Umey4tgNcm9fEm3eVX0pN5DMnhe2_Z7FoGa2ppe&qq-pf-to=pcqq.group
  1. ArcGIS for Android示例解析之FeatureLayer服务-----SelectFeatures
  2. http://bbs.hiapk.com/thread-3940420-1-1.html

过程:

通过FeatureLayer我们可以很快的查询出所选的要素,并进行渲染。下面我们梳理一下选择查询的步骤:

1、              FeatureLayer图层对象所需的参数的设置,如:自身的url设置,Options对象设置,以及选择的要素渲染的样式设置等。
2、              定义一个Query对象,并且给其设置所需的值,如:设置查询条件、是否返回几何对象、输入的空间参考、空间要素以及查询的空间关系。
3、              执行FeatureLayer对象的selectFeatures()方法。

 4 、Graphic graphic = new Graphic(feature.getGeometry(),
                               sfs);
                        // add graphic to layer
                        mGraphicsLayer.addGraphic(graphic);
 
详细:先
1.GraphicsLayer mGraphicsLayer = new GraphicsLayer();  //类似于画布
final String tpkPath = "/Arcgis/hello.tpk";
    public static final String GEO_FILENAME="/Arcgis/hello/data/z01.geodatabase";//数据存放地址
2. onCreate里面加 mMapView.addLayer(mGraphicsLayer); 
3.class TouchListener extends MapOnTouchListener {
长按清除所有画布的要素
  1. public void onLongPress(MotionEvent point) {
  2. // Our long press will clear the screen
  3. mStops.clearFeatures();
  4. mGraphicsLayer.removeAll();
  5. mMapView.getCallout().hide();
  6. }
  1. public boolean onSingleTap(MotionEvent point) {
  2. Point mapPoint = mMapView.toMapPoint(point.getX(), point.getY());
  3. Log.i("zjx",""+mapPoint.getX()/1000+",,,"+(mapPoint.getY()/1000+1));
  4. Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(Color.BLUE, 10, STYLE.DIAMOND));
  5. mGraphicsLayer.addGraphic(graphic);}

单击得到相对地图的位置

双击。。这里我订死了查询条件,显示要素
Geodatabase geodatabase =null;
        try {
            geodatabase =new Geodatabase(filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<GeodatabaseFeatureTable> table = geodatabase
      .getGeodatabaseTables();
        Log.i("zjx","list:"+table);
        GeodatabaseFeatureTable mytable=geodatabase.getGeodatabaseFeatureTableByLayerId(0);
得到数据库 以及第一个数据表
  1. FeatureLayer  featureLayer = new FeatureLayer(mytable);
  2. QueryParameters qParameters = new QueryParameters();
  3. String whereClause = "name='z5'";
  4. //        SpatialReference sr = SpatialReference.create(102100);
  5. qParameters.setGeometry(mMapView.getExtent());
  6. //        qParameters.setOutSpatialReference(sr);
  7. qParameters.setReturnGeometry(true);
  8. qParameters.setWhere(whereClause);
  9. CallbackListener<FeatureResult> callback=new CallbackListener<FeatureResult>(){
  10. public void onError(Throwable e) {
  11. e.printStackTrace();
  12. }
  13. public void onCallback(FeatureResult featureIterator) {
  14. //...
  15. Log.i("zjx","featureIterator.featureCount():"+featureIterator.featureCount());
  16. Log.i("zjx","featureIterator.getDisplayFieldName()"+featureIterator.getDisplayFieldName());
  17. Log.i("zjx","i m callback");
  18. }
  19. };
  20. Log.i("zjx","sb:"+featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback));
  21. //        featureLayer.getU
  22. Future<FeatureResult> resultFuture=featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback);
  23. Log.i("zjx","resultFuture:"+ resultFuture);
  24. try{
  25. FeatureResult results = resultFuture.get();//最关键  得到结果
  26. Log.i("zjx","feature.featureCount():"+results.featureCount());//得到结果的数量
  27. Log.i("zjx","feature.getDisplayFieldName():"+results.getDisplayFieldName());
  28. if (results != null) {
  29. Log.i("zjx","results no null");
  30. int size = (int) results.featureCount();
  31. int i = 0;
  32. for (Object element : results) {//得到每个要素
  33. Log.i("zjx","the element:"+element);
  34. if (element instanceof Feature) {
  35. Log.i("zjx","element");
  36. Feature feature = (Feature) element;
  37. Log.i("zjx","Feature feature = (Feature) element;:"+element);
  38. // turn feature into graphic
  39. Random r = new Random();
  40. int color = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255));
  41. SimpleFillSymbol sfs = new SimpleFillSymbol(color);
  42. sfs.setAlpha(75);
  43. Graphic graphic = new Graphic(feature.getGeometry(),
  44. sfs);
  45. // add graphic to layer
  46. mGraphicsLayer.addGraphic(graphic);//显示要素
  47. }
  48. i++;
  49. }
  50. // update message with results
  51. }

设置查询条件 高亮样式

 
 
完整:
  1. package com.esri.arcgis.android.samples.offlineroutingandgeocoding;
  2. import java.io.FileNotFoundException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Random;
  7. import java.util.concurrent.Future;
  8. import android.app.Activity;
  9. import android.content.Context;
  10. import android.graphics.Color;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.util.Log;
  14. import android.view.LayoutInflater;
  15. import android.view.Menu;
  16. import android.view.MotionEvent;
  17. import android.view.View;
  18. import android.widget.AdapterView;
  19. import android.widget.AdapterView.OnItemSelectedListener;
  20. import android.widget.ArrayAdapter;
  21. import android.widget.Spinner;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24. import com.esri.android.map.FeatureLayer;
  25. import com.esri.android.map.GraphicsLayer;
  26. import com.esri.android.map.GraphicsLayer.RenderingMode;
  27. import com.esri.android.map.MapOnTouchListener;
  28. import com.esri.android.map.MapView;
  29. import com.esri.android.map.TiledLayer;
  30. import com.esri.android.map.ags.ArcGISLocalTiledLayer;
  31. import com.esri.core.geodatabase.Geodatabase;
  32. import com.esri.core.geodatabase.GeodatabaseFeature;
  33. import com.esri.core.geodatabase.GeodatabaseFeatureTable;
  34. import com.esri.core.geometry.Geometry;
  35. import com.esri.core.geometry.Point;
  36. import com.esri.core.geometry.SpatialReference;
  37. import com.esri.core.map.CallbackListener;
  38. import com.esri.core.map.Feature;
  39. import com.esri.core.map.FeatureResult;
  40. import com.esri.core.map.FeatureSet;
  41. import com.esri.core.map.Graphic;
  42. import com.esri.core.symbol.SimpleFillSymbol;
  43. import com.esri.core.symbol.SimpleLineSymbol;
  44. import com.esri.core.symbol.SimpleMarkerSymbol;
  45. import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;
  46. import com.esri.core.tasks.geocode.Locator;
  47. import com.esri.core.tasks.geocode.LocatorReverseGeocodeResult;
  48. import com.esri.core.tasks.na.NAFeaturesAsFeature;
  49. import com.esri.core.tasks.na.Route;
  50. import com.esri.core.tasks.na.RouteDirection;
  51. import com.esri.core.tasks.na.RouteParameters;
  52. import com.esri.core.tasks.na.RouteResult;
  53. import com.esri.core.tasks.na.RouteTask;
  54. import com.esri.core.tasks.na.StopGraphic;
  55. import com.esri.core.tasks.query.QueryParameters;
  56. public class RoutingAndGeocoding extends Activity {
  57. // Define ArcGIS Elements
  58. MapView mMapView;
  59. final String extern = Environment.getExternalStorageDirectory().getPath();
  60. //  final String tpkPath = "/ArcGIS/samples/OfflineRouting/SanDiego.tpk";
  61. final String tpkPath = "/Arcgis/hello.tpk";
  62. public static final String GEO_FILENAME="/Arcgis/hello/data/z01.geodatabase";
  63. TiledLayer mTileLayer = new ArcGISLocalTiledLayer(extern + tpkPath);
  64. GraphicsLayer mGraphicsLayer = new GraphicsLayer();
  65. String filename=extern+GEO_FILENAME;
  66. RouteTask mRouteTask = null;
  67. NAFeaturesAsFeature mStops = new NAFeaturesAsFeature();
  68. Locator mLocator = null;
  69. View mCallout = null;
  70. Spinner dSpinner;
  71. @Override
  72. protected void onCreate(Bundle savedInstanceState) {
  73. super.onCreate(savedInstanceState);
  74. setContentView(R.layout.activity_routing_and_geocoding);
  75. // Find the directions spinner
  76. dSpinner = (Spinner) findViewById(R.id.directionsSpinner);
  77. dSpinner.setEnabled(false);
  78. // Retrieve the map and initial extent from XML layout
  79. mMapView = (MapView) findViewById(R.id.map);
  80. // Set the tiled map service layer and add a graphics layer
  81. mMapView.addLayer(mTileLayer);
  82. mMapView.addLayer(mGraphicsLayer);
  83. // Initialize the RouteTask and Locator with the local data
  84. initializeRoutingAndGeocoding();
  85. mMapView.setOnTouchListener(new TouchListener(RoutingAndGeocoding.this, mMapView));
  86. //    Point mapPoint = null;
  87. //      mapPoint.setXY(0.1942*1928,(0.6842-1)*1928);
  88. //      Log.i("zjx",""+mapPoint);
  89. //      Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(Color.BLUE, 10, STYLE.DIAMOND));
  90. //      mGraphicsLayer.addGraphic(graphic);
  91. }
  92. private void initializeRoutingAndGeocoding() {
  93. // We will spin off the initialization in a new thread
  94. new Thread(new Runnable() {
  95. @Override
  96. public void run() {
  97. // Get the external directory
  98. //        String locatorPath = "/ArcGIS/samples/OfflineRouting/Geocoding/SanDiego_StreetAddress.loc";
  99. //        String networkPath = "/ArcGIS/samples/OfflineRouting/Routing/RuntimeSanDiego.geodatabase";
  100. String locatorPath = "/Arcgis/hello/data/z01.loc";
  101. String networkPath = "/Arcgis/hello/data/z01.geodatabase";
  102. String networkName = "Streets_ND";
  103. // Attempt to load the local geocoding and routing data
  104. try {
  105. mLocator = Locator.createLocalLocator(extern + locatorPath);
  106. mRouteTask = RouteTask.createLocalRouteTask(extern + networkPath, networkName);
  107. } catch (Exception e) {
  108. popToast("Error while initializing :" + e.getMessage(), true);
  109. e.printStackTrace();
  110. }
  111. }
  112. }).start();
  113. }
  114. class TouchListener extends MapOnTouchListener {
  115. private int routeHandle = -1;
  116. @Override
  117. public void onLongPress(MotionEvent point) {
  118. // Our long press will clear the screen
  119. mStops.clearFeatures();
  120. mGraphicsLayer.removeAll();
  121. mMapView.getCallout().hide();
  122. }
  123. @Override
  124. public boolean onSingleTap(MotionEvent point) {
  125. Point mapPoint = mMapView.toMapPoint(point.getX(), point.getY());
  126. Log.i("zjx",""+mapPoint.getX()/1000+",,,"+(mapPoint.getY()/1000+1));
  127. Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(Color.BLUE, 10, STYLE.DIAMOND));
  128. mGraphicsLayer.addGraphic(graphic);
  129. if (mLocator == null) {
  130. popToast("Locator uninitialized", true);
  131. return super.onSingleTap(point);
  132. }
  133. String stopAddress = "";
  134. try {
  135. // Attempt to reverse geocode the point.
  136. // Our input and output spatial reference will
  137. // be the same as the map.
  138. SpatialReference mapRef = mMapView.getSpatialReference();
  139. LocatorReverseGeocodeResult result = mLocator.reverseGeocode(mapPoint, 50, mapRef, mapRef);
  140. // Construct a nicely formatted address from the results
  141. StringBuilder address = new StringBuilder();
  142. if (result != null && result.getAddressFields() != null) {
  143. Map<String, String> addressFields = result.getAddressFields();
  144. address.append(String.format("%s\n%s, %s %s", addressFields.get("Street"), addressFields.get("City"),
  145. addressFields.get("State"), addressFields.get("ZIP")));
  146. }
  147. // Show the results of the reverse geocoding in
  148. // the map's callout.
  149. stopAddress = address.toString();
  150. showCallout(stopAddress, mapPoint);
  151. } catch (Exception e) {
  152. Log.v("Reverse Geocode", e.getMessage());
  153. }
  154. // Add the touch event as a stop
  155. StopGraphic stop = new StopGraphic(graphic);
  156. stop.setName(stopAddress.toString());
  157. mStops.addFeature(stop);
  158. return true;
  159. }
  160. @Override
  161. public boolean onDoubleTap(MotionEvent point) {
  162. Log.i("zjx","double");
  163. // String filename=Environment.getExternalStorageDirectory().getAbsolutePath()+GEO_FILENAME;
  164. Geodatabase geodatabase =null;
  165. try {
  166. geodatabase =new Geodatabase(filename);
  167. } catch (FileNotFoundException e) {
  168. // TODO Auto-generated catch block
  169. e.printStackTrace();
  170. }
  171. List<GeodatabaseFeatureTable> table = geodatabase
  172. .getGeodatabaseTables();
  173. Log.i("zjx","list:"+table);
  174. GeodatabaseFeatureTable mytable=geodatabase.getGeodatabaseFeatureTableByLayerId(0);
  175. FeatureLayer  featureLayer = new FeatureLayer(mytable);
  176. QueryParameters qParameters = new QueryParameters();
  177. String whereClause = "name='z5'";
  178. //        SpatialReference sr = SpatialReference.create(102100);
  179. qParameters.setGeometry(mMapView.getExtent());
  180. //        qParameters.setOutSpatialReference(sr);
  181. qParameters.setReturnGeometry(true);
  182. qParameters.setWhere(whereClause);
  183. CallbackListener<FeatureResult> callback=new CallbackListener<FeatureResult>(){
  184. public void onError(Throwable e) {
  185. e.printStackTrace();
  186. }
  187. public void onCallback(FeatureResult featureIterator) {
  188. //...
  189. Log.i("zjx","featureIterator.featureCount():"+featureIterator.featureCount());
  190. Log.i("zjx","featureIterator.getDisplayFieldName()"+featureIterator.getDisplayFieldName());
  191. Log.i("zjx","i m callback");
  192. }
  193. };
  194. Log.i("zjx","sb:"+featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback));
  195. //        featureLayer.getU
  196. Future<FeatureResult> resultFuture=featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback);
  197. Log.i("zjx","resultFuture:"+ resultFuture);
  198. try{
  199. FeatureResult results = resultFuture.get();
  200. Log.i("zjx","feature.featureCount():"+results.featureCount());
  201. Log.i("zjx","feature.getDisplayFieldName():"+results.getDisplayFieldName());
  202. if (results != null) {
  203. Log.i("zjx","results no null");
  204. int size = (int) results.featureCount();
  205. int i = 0;
  206. for (Object element : results) {
  207. Log.i("zjx","the element:"+element);
  208. if (element instanceof Feature) {
  209. Log.i("zjx","element");
  210. Feature feature = (Feature) element;
  211. Log.i("zjx","Feature feature = (Feature) element;:"+element);
  212. // turn feature into graphic
  213. Random r = new Random();
  214. int color = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255));
  215. SimpleFillSymbol sfs = new SimpleFillSymbol(color);
  216. sfs.setAlpha(75);
  217. Graphic graphic = new Graphic(feature.getGeometry(),
  218. sfs);
  219. // add graphic to layer
  220. mGraphicsLayer.addGraphic(graphic);
  221. }
  222. i++;
  223. }
  224. // update message with results
  225. }
  226. }
  227. catch (Exception e){
  228. Log.i("zjx","e:"+e);
  229. }
  230. //        Log.i("zjx","featureLayer2:"+featureLayer);
  231. //        mMapView.addLayer(featureLayer);
  232. //        QueryParameters query = new QueryParameters();
  233. ////        query.setWhere("*");
  234. //
  235. //        query.setOutFields(new String[]{"*"});
  236. //        Log.i("zjx","query:"+query.toString());
  237. //
  238. //        Future resultFuture = mytable.queryFeatures(query, callback);
  239. //        try{
  240. //            Log.i("zjx","resultFuture:"+resultFuture.get().toString());
  241. //             Object result = resultFuture.get();
  242. //                Feature feature = (Feature) result;
  243. //                Map attrs = feature.getAttributes();
  244. //                Log.i("zjx","feature:"+feature);
  245. //            Log.i("zjx","attrs:"+attrs);
  246. //        }
  247. //        catch(Exception e){
  248. //
  249. //            Log.i("zjx","error:"+e);
  250. //        }
  251. //        Future resultFuture = gdbFeatureTable.queryFeatures(query, new CallbackListener() {
  252. //
  253. //            public void onError(Throwable e) {
  254. //                e.printStackTrace();
  255. //            }
  256. //
  257. //            public void onCallback(FeatureResult featureIterator) {
  258. //             //   ...
  259. //            }
  260. //        });
  261. //
  262. //        for (Object result : resultFuture.get()) {
  263. //            Feature feature = (Feature) result;
  264. //            // Map attrs = feature.getAttributes();
  265. //        }
  266. // Return default behavior if we did not initialize properly.
  267. //      if (mRouteTask == null) {
  268. //        popToast("RouteTask uninitialized.", true);
  269. //        return super.onDoubleTap(point);
  270. //      }
  271. //
  272. //      try {
  273. //
  274. //        // Set the correct input spatial reference on the stops and the
  275. //        // desired output spatial reference on the RouteParameters object.
  276. //        SpatialReference mapRef = mMapView.getSpatialReference();
  277. //        RouteParameters params = mRouteTask.retrieveDefaultRouteTaskParameters();
  278. //        params.setOutSpatialReference(mapRef);
  279. //        mStops.setSpatialReference(mapRef);
  280. //
  281. //        // Set the stops and since we want driving directions,
  282. //        // returnDirections==true
  283. //        params.setStops(mStops);
  284. //        params.setReturnDirections(true);
  285. //
  286. //        // Perform the solve
  287. //        RouteResult results = mRouteTask.solve(params);
  288. //
  289. //        // Grab the results; for offline routing, there will only be one
  290. //        // result returned on the output.
  291. //        Route result = results.getRoutes().get(0);
  292. //
  293. //        // Remove any previous route Graphics
  294. //        if (routeHandle != -1)
  295. //          mGraphicsLayer.removeGraphic(routeHandle);
  296. //
  297. //        // Add the route shape to the graphics layer
  298. //        Geometry geom = result.getRouteGraphic().getGeometry();
  299. //        routeHandle = mGraphicsLayer.addGraphic(new Graphic(geom, new SimpleLineSymbol(0x99990055, 5)));
  300. //        mMapView.getCallout().hide();
  301. //
  302. //        // Get the list of directions from the result
  303. //        List<RouteDirection> directions = result.getRoutingDirections();
  304. //
  305. //        // enable spinner to receive directions
  306. //        dSpinner.setEnabled(true);
  307. //
  308. //        // Iterate through all of the individual directions items and
  309. //        // create a nicely formatted string for each.
  310. //        List<String> formattedDirections = new ArrayList<String>();
  311. //        for (int i = 0; i < directions.size(); i++) {
  312. //          RouteDirection direction = directions.get(i);
  313. //          formattedDirections.add(String.format("%s\nGo %.2f %s For %.2f Minutes", direction.getText(),
  314. //              direction.getLength(), params.getDirectionsLengthUnit().name(), direction.getMinutes()));
  315. //        }
  316. //
  317. //        // Add a summary String
  318. //        formattedDirections.add(0, String.format("Total time: %.2f Mintues", result.getTotalMinutes()));
  319. //
  320. //        // Create a simple array adapter to visualize the directions in
  321. //        // the Spinner
  322. //        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
  323. //            android.R.layout.simple_spinner_item, formattedDirections);
  324. //        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  325. //        dSpinner.setAdapter(adapter);
  326. //
  327. //        // Add a custom OnItemSelectedListener to the spinner to allow
  328. //        // panning to each directions item.
  329. //        dSpinner.setOnItemSelectedListener(new DirectionsItemListener(directions));
  330. //
  331. //      } catch (Exception e) {
  332. //        popToast("Solve Failed: " + e.getMessage(), true);
  333. //        e.printStackTrace();
  334. //      }
  335. return true;
  336. }
  337. public TouchListener(Context context, MapView view) {
  338. super(context, view);
  339. }
  340. }
  341. class DirectionsItemListener implements OnItemSelectedListener {
  342. private List<RouteDirection> mDirections;
  343. public DirectionsItemListener(List<RouteDirection> directions) {
  344. mDirections = directions;
  345. }
  346. @Override
  347. public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
  348. // We have to account for the added summary String
  349. if (mDirections != null && pos > 0 && pos <= mDirections.size())
  350. mMapView.setExtent(mDirections.get(pos - 1).getGeometry());
  351. }
  352. @Override
  353. public void onNothingSelected(AdapterView<?> arg0) {
  354. }
  355. }
  356. private void showCallout(String text, Point location) {
  357. // If the callout has never been created, inflate it
  358. if (mCallout == null) {
  359. LayoutInflater inflater = (LayoutInflater) getApplication().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  360. mCallout = inflater.inflate(R.layout.callout, null);
  361. }
  362. // Show the callout with the given text at the given location
  363. ((TextView) mCallout.findViewById(R.id.calloutText)).setText(text);
  364. mMapView.getCallout().show(location, mCallout);
  365. mMapView.getCallout().setMaxWidth(700);
  366. }
  367. private void popToast(final String message, final boolean show) {
  368. // Simple helper method for showing toast on the main thread
  369. if (!show)
  370. return;
  371. runOnUiThread(new Runnable() {
  372. @Override
  373. public void run() {
  374. Toast.makeText(RoutingAndGeocoding.this, message, Toast.LENGTH_SHORT).show();
  375. }
  376. });
  377. }
  378. @Override
  379. public boolean onCreateOptionsMenu(Menu menu) {
  380. // Inflate the menu; this adds items to the action bar if it is present.
  381. getMenuInflater().inflate(R.menu.routing_and_geocoding, menu);
  382. return true;
  383. }
  384. }
来自:http://blog.csdn.net/u011644423/article/details/45482577