1. 程式人生 > >Arcgis for android 離線查詢

Arcgis for android 離線查詢

package com.esri.arcgis.android.samples.offlineroutingandgeocoding;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Future;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.android.map.FeatureLayer;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.GraphicsLayer.RenderingMode;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.TiledLayer;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.core.geodatabase.Geodatabase;
import com.esri.core.geodatabase.GeodatabaseFeature;
import com.esri.core.geodatabase.GeodatabaseFeatureTable;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.CallbackListener;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.map.FeatureSet;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorReverseGeocodeResult;
import com.esri.core.tasks.na.NAFeaturesAsFeature;
import com.esri.core.tasks.na.Route;
import com.esri.core.tasks.na.RouteDirection;
import com.esri.core.tasks.na.RouteParameters;
import com.esri.core.tasks.na.RouteResult;
import com.esri.core.tasks.na.RouteTask;
import com.esri.core.tasks.na.StopGraphic;
import com.esri.core.tasks.query.QueryParameters;

public class RoutingAndGeocoding extends Activity {

  // Define ArcGIS Elements
  MapView mMapView;
  final String extern = Environment.getExternalStorageDirectory().getPath();
//  final String tpkPath = "/ArcGIS/samples/OfflineRouting/SanDiego.tpk";
final String tpkPath = "/Arcgis/hello.tpk";
    public static final String GEO_FILENAME="/Arcgis/hello/data/z01.geodatabase";
  TiledLayer mTileLayer = new ArcGISLocalTiledLayer(extern + tpkPath);
  GraphicsLayer mGraphicsLayer = new GraphicsLayer();
    String filename=extern+GEO_FILENAME;
  RouteTask mRouteTask = null;
  NAFeaturesAsFeature mStops = new NAFeaturesAsFeature();

  Locator mLocator = null;
  View mCallout = null;
  Spinner dSpinner;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_routing_and_geocoding);
    
    // Find the directions spinner
    dSpinner = (Spinner) findViewById(R.id.directionsSpinner);
    dSpinner.setEnabled(false);

    // Retrieve the map and initial extent from XML layout
    mMapView = (MapView) findViewById(R.id.map);

    // Set the tiled map service layer and add a graphics layer
    mMapView.addLayer(mTileLayer);
    mMapView.addLayer(mGraphicsLayer);

    // Initialize the RouteTask and Locator with the local data
    initializeRoutingAndGeocoding();
    mMapView.setOnTouchListener(new TouchListener(RoutingAndGeocoding.this, mMapView));
  //    Point mapPoint = null;

//      mapPoint.setXY(0.1942*1928,(0.6842-1)*1928);
//      Log.i("zjx",""+mapPoint);
//      Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(Color.BLUE, 10, STYLE.DIAMOND));
//      mGraphicsLayer.addGraphic(graphic);
  }

  private void initializeRoutingAndGeocoding() {

    // We will spin off the initialization in a new thread
    new Thread(new Runnable() {

      @Override
      public void run() {
        // Get the external directory
//        String locatorPath = "/ArcGIS/samples/OfflineRouting/Geocoding/SanDiego_StreetAddress.loc";
//        String networkPath = "/ArcGIS/samples/OfflineRouting/Routing/RuntimeSanDiego.geodatabase";
            String locatorPath = "/Arcgis/hello/data/z01.loc";
            String networkPath = "/Arcgis/hello/data/z01.geodatabase";
            String networkName = "Streets_ND";

        // Attempt to load the local geocoding and routing data
        try {
          mLocator = Locator.createLocalLocator(extern + locatorPath);
          mRouteTask = RouteTask.createLocalRouteTask(extern + networkPath, networkName);
        } catch (Exception e) {
          popToast("Error while initializing :" + e.getMessage(), true);
          e.printStackTrace();
        }
      }
    }).start();
  }

  class TouchListener extends MapOnTouchListener {

    private int routeHandle = -1;

    @Override
    public void onLongPress(MotionEvent point) {
      // Our long press will clear the screen
      mStops.clearFeatures();
      mGraphicsLayer.removeAll();
      mMapView.getCallout().hide();
    }

    @Override
    public boolean onSingleTap(MotionEvent point) {
        Point mapPoint = mMapView.toMapPoint(point.getX(), point.getY());
        Log.i("zjx",""+mapPoint.getX()/1000+",,,"+(mapPoint.getY()/1000+1));
        Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(Color.BLUE, 10, STYLE.DIAMOND));
        mGraphicsLayer.addGraphic(graphic);
      if (mLocator == null) {
            popToast("Locator uninitialized", true);
            return super.onSingleTap(point);
        }

      String stopAddress = "";
      try {
        // Attempt to reverse geocode the point.
        // Our input and output spatial reference will
        // be the same as the map.
        SpatialReference mapRef = mMapView.getSpatialReference();
        LocatorReverseGeocodeResult result = mLocator.reverseGeocode(mapPoint, 50, mapRef, mapRef);

        // Construct a nicely formatted address from the results
        StringBuilder address = new StringBuilder();
        if (result != null && result.getAddressFields() != null) {
          Map<String, String> addressFields = result.getAddressFields();
          address.append(String.format("%s\n%s, %s %s", addressFields.get("Street"), addressFields.get("City"),
              addressFields.get("State"), addressFields.get("ZIP")));
        }

        // Show the results of the reverse geocoding in
        // the map's callout.
        stopAddress = address.toString();
        showCallout(stopAddress, mapPoint);

      } catch (Exception e) {
        Log.v("Reverse Geocode", e.getMessage());
      }

      // Add the touch event as a stop
      StopGraphic stop = new StopGraphic(graphic);
      stop.setName(stopAddress.toString());
      mStops.addFeature(stop);

      return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent point) {
        Log.i("zjx","double");

       // String filename=Environment.getExternalStorageDirectory().getAbsolutePath()+GEO_FILENAME;
        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);
        FeatureLayer  featureLayer = new FeatureLayer(mytable);
        QueryParameters qParameters = new QueryParameters();
        String whereClause = "name='z5'";
//        SpatialReference sr = SpatialReference.create(102100);
        qParameters.setGeometry(mMapView.getExtent());
//        qParameters.setOutSpatialReference(sr);
        qParameters.setReturnGeometry(true);
        qParameters.setWhere(whereClause);
        CallbackListener<FeatureResult> callback=new CallbackListener<FeatureResult>(){
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            public void onCallback(FeatureResult featureIterator) {
                //...
                Log.i("zjx","featureIterator.featureCount():"+featureIterator.featureCount());
                Log.i("zjx","featureIterator.getDisplayFieldName()"+featureIterator.getDisplayFieldName());
                Log.i("zjx","i m callback");
            }


        };
        Log.i("zjx","sb:"+featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback));
//        featureLayer.getU
        Future<FeatureResult> resultFuture=featureLayer.selectFeatures(qParameters, FeatureLayer.SelectionMode.NEW,callback);
        Log.i("zjx","resultFuture:"+ resultFuture);
        try{
            FeatureResult results = resultFuture.get();
            Log.i("zjx","feature.featureCount():"+results.featureCount());
            Log.i("zjx","feature.getDisplayFieldName():"+results.getDisplayFieldName());
            if (results != null) {
                Log.i("zjx","results no null");
                int size = (int) results.featureCount();
                int i = 0;
                for (Object element : results) {
                    Log.i("zjx","the element:"+element);
                    if (element instanceof Feature) {
                        Log.i("zjx","element");
                        Feature feature = (Feature) element;
                        Log.i("zjx","Feature feature = (Feature) element;:"+element);
                        // turn feature into graphic
                        Random r = new Random();
                        int color = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255));
                        SimpleFillSymbol sfs = new SimpleFillSymbol(color);
                        sfs.setAlpha(75);
                        Graphic graphic = new Graphic(feature.getGeometry(),
                               sfs);
                        // add graphic to layer
                        mGraphicsLayer.addGraphic(graphic);
                    }
                    i++;
                }
                // update message with results


            }


        }
       catch (Exception e){
           Log.i("zjx","e:"+e);
       }

//        Log.i("zjx","featureLayer2:"+featureLayer);
//        mMapView.addLayer(featureLayer);
//        QueryParameters query = new QueryParameters();
////        query.setWhere("*");
//
//        query.setOutFields(new String[]{"*"});
//        Log.i("zjx","query:"+query.toString());
//

//        Future resultFuture = mytable.queryFeatures(query, callback);
//        try{
//            Log.i("zjx","resultFuture:"+resultFuture.get().toString());
//             Object result = resultFuture.get();
//                Feature feature = (Feature) result;
//                Map attrs = feature.getAttributes();
//                Log.i("zjx","feature:"+feature);
//            Log.i("zjx","attrs:"+attrs);
//        }
//        catch(Exception e){
//
//            Log.i("zjx","error:"+e);
//        }

//        Future resultFuture = gdbFeatureTable.queryFeatures(query, new CallbackListener() {
//
//            public void onError(Throwable e) {
//                e.printStackTrace();
//            }
//
//            public void onCallback(FeatureResult featureIterator) {
//             //   ...
//            }
//        });
//
//        for (Object result : resultFuture.get()) {
//            Feature feature = (Feature) result;
//            // Map attrs = feature.getAttributes();
//        }
      // Return default behavior if we did not initialize properly.
//      if (mRouteTask == null) {
//        popToast("RouteTask uninitialized.", true);
//        return super.onDoubleTap(point);
//      }
//
//      try {
//
//        // Set the correct input spatial reference on the stops and the
//        // desired output spatial reference on the RouteParameters object.
//        SpatialReference mapRef = mMapView.getSpatialReference();
//        RouteParameters params = mRouteTask.retrieveDefaultRouteTaskParameters();
//        params.setOutSpatialReference(mapRef);
//        mStops.setSpatialReference(mapRef);
//
//        // Set the stops and since we want driving directions,
//        // returnDirections==true
//        params.setStops(mStops);
//        params.setReturnDirections(true);
//
//        // Perform the solve
//        RouteResult results = mRouteTask.solve(params);
//
//        // Grab the results; for offline routing, there will only be one
//        // result returned on the output.
//        Route result = results.getRoutes().get(0);
//
//        // Remove any previous route Graphics
//        if (routeHandle != -1)
//          mGraphicsLayer.removeGraphic(routeHandle);
//
//        // Add the route shape to the graphics layer
//        Geometry geom = result.getRouteGraphic().getGeometry();
//        routeHandle = mGraphicsLayer.addGraphic(new Graphic(geom, new SimpleLineSymbol(0x99990055, 5)));
//        mMapView.getCallout().hide();
//
//        // Get the list of directions from the result
//        List<RouteDirection> directions = result.getRoutingDirections();
//
//        // enable spinner to receive directions
//        dSpinner.setEnabled(true);
//
//        // Iterate through all of the individual directions items and
//        // create a nicely formatted string for each.
//        List<String> formattedDirections = new ArrayList<String>();
//        for (int i = 0; i < directions.size(); i++) {
//          RouteDirection direction = directions.get(i);
//          formattedDirections.add(String.format("%s\nGo %.2f %s For %.2f Minutes", direction.getText(),
//              direction.getLength(), params.getDirectionsLengthUnit().name(), direction.getMinutes()));
//        }
//
//        // Add a summary String
//        formattedDirections.add(0, String.format("Total time: %.2f Mintues", result.getTotalMinutes()));
//
//        // Create a simple array adapter to visualize the directions in
//        // the Spinner
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
//            android.R.layout.simple_spinner_item, formattedDirections);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        dSpinner.setAdapter(adapter);
//
//        // Add a custom OnItemSelectedListener to the spinner to allow
//        // panning to each directions item.
//        dSpinner.setOnItemSelectedListener(new DirectionsItemListener(directions));
//
//      } catch (Exception e) {
//        popToast("Solve Failed: " + e.getMessage(), true);
//        e.printStackTrace();
//      }
      return true;
    }

    public TouchListener(Context context, MapView view) {
      super(context, view);
    }
  }

  class DirectionsItemListener implements OnItemSelectedListener {

    private List<RouteDirection> mDirections;

    public DirectionsItemListener(List<RouteDirection> directions) {
      mDirections = directions;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
      // We have to account for the added summary String
      if (mDirections != null && pos > 0 && pos <= mDirections.size())
        mMapView.setExtent(mDirections.get(pos - 1).getGeometry());
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }
  }

  private void showCallout(String text, Point location) {

    // If the callout has never been created, inflate it
    if (mCallout == null) {
      LayoutInflater inflater = (LayoutInflater) getApplication().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      mCallout = inflater.inflate(R.layout.callout, null);
    }

    // Show the callout with the given text at the given location
    ((TextView) mCallout.findViewById(R.id.calloutText)).setText(text);
    mMapView.getCallout().show(location, mCallout);
    mMapView.getCallout().setMaxWidth(700);
  }

  private void popToast(final String message, final boolean show) {
    // Simple helper method for showing toast on the main thread
    if (!show)
      return;

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(RoutingAndGeocoding.this, message, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.routing_and_geocoding, menu);
    return true;
  }

}


相關推薦

Arcgis for android 離線查詢

package com.esri.arcgis.android.samples.offlineroutingandgeocoding; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Lis

arcgis for android 離線切片載入與geodatabase查詢

載入geodatabase資料private FeatureLayer valueFL; //離線資料圖 @Override public void getLocalMapServerDiFangData(){ try {

arcgis for android空間查詢 點選某點,選中該點所在區域,高亮顯示

修改mail.xml <com.esri.android.map.MapView android:id="@+id/map" android:layout_width="fill_parent" an

ArcGIS for Android 離線資料圖例載入

  圖例是地圖展示裡常用的輔助展示工具。曾經我採用過將圖例截成圖片轉為2進位制儲存到資料庫裡,然後在載入圖層時候調取對應圖片作為圖例展示。但是後來知道geodatabase資料其實就是個空間資料庫,如果是通過geodatabase資料載入圖層,圖斑都是geodatabase

Arcgis for android離線數據庫小記

pan eat 下載失敗 roi 一模一樣 數據 ID 找到 code 最近在使用arcgis for android,要實現本地數據的編輯,esri的解決方案搞的太復雜,遇到了不少問題,特此記錄 1.Desktop生成的runtime geodatabase無法在本地進

Arcgis For Android 查詢功能

Arcgis For Android 有三種常用的查詢方式:IdentifyTask 、FindTask 和 QueryTask。 1、QueryTask QueryTask是一個進行空間和屬性查詢的功能類,它可以在某個地圖服務的某個子圖層內進行查詢,QueryTask進行查詢的地圖服務並不必須載入到Map中

Arcgis For Android離線地圖實現的幾種方式

ArcGIS for Android離線資料編輯實現原理 實現ArcGIS for Android上的離線資料編輯,具體實現環境及其步驟如下: 一、      環境準備 1.        軟體環境 1)        ArcGIS Server10用於釋出地圖服務 2)        ArcGIS Des

Arcgis for Android開發檔案一(離線地圖解決方案)

ArcGIS Runtime for Android開發解決方案資料 目錄 前言 一、ArcGIS Runtime for Android 開發環境的搭建 二、ArcGIS Runtime for Android 離線地圖包的製作 三、ArcGIS Runtime for

arcgis for android 短路徑分析 查詢最短路徑

ArcGIS for Android(10.1.1)只支援線上的網路分析,執行路徑分析可以通過RoutingTask類的solve方法來進行,通過給slove方法傳遞RoutingParameters型別的引數,可以最短路徑的查詢。而要成功執行路徑分析,就必須釋出網路分析

Arcgis for Android 空間數據WKT與JSON描述

nbsp gis str ext 10.9 select exception json字符串 spatial 點線面數據標準格式 一、 點 WKT: POINT(-118.4 -45.2) JSON: { "x": -118.4, "y": -45.2, "

arcgis for android 呼叫公網天地圖註記重影問題

      最近在android專案開發中,使用arcgis for android 地圖api呼叫公網的天地圖。有一個問題,天地圖的註記層,在地圖縮放的時候重新整理滯後,導致註記層有重影,使用者體驗差。    &nb

ArcGIS for Android 100.3的學習與應用(三) 實現地圖新增自定義指北針

圖為高德地圖實現指北針的效果,那麼ArcGIS如何實現呢? 實現方式: 新增地圖的旋轉監聽: map.addMapRotationChangedListener(new MapRotationChangedListener() { @Override

ArcGIS for Android 100.3的學習與應用(二) 如何移除指定的點和線?

在地圖上新增點和線的時候,我們有時候會遇到要移除或者切換指定的點和線的操作。那麼如何移除指定的點和線呢? ArcGIS的api裡點和線都是由GraphicsOverlay類來進行建立新增的。通過Graphic物件將點或者線的圖形物件(SimpleMarkerSymbol,SimpleLine

ArcGIS for Android 100.3的學習與應用(一) 如何繪製點和線?

平時工作中,我們接觸到的地圖類開發平臺有很多,最常用的有高德,百度,騰訊地圖。而且它們都有自己的開發者平臺和文件供我們使用。基本能滿足我們的業務需求。 由於公司裡的專案會涉及一些地圖資料統計和展示方面的需求,同時也會發布一些地圖服務,所以選擇了使用在地圖方面比較牛逼的ArcGIS。 把平時遇

ArcGIS for Android載入WMS(1)——WMS基本介紹

今天開始寫ArcGIS for Android載入WMS系列的一些記錄,主要包括WMS的基本介紹,ArcGIS for Android載入WMS,用MapGuide和GeoServer釋出WMS並在ArcGIS for Android中載入以及其中存在的一些問題等。因為前兩天

ArcGIS for Android 的學習與應用(二) 如何移除指定的點和線?

在地圖上新增點和線的時候,我們有時候會遇到要移除或者切換指定的點和線的操作。那麼如何移除指定的點和線呢? ArcGIS的api裡點和線都是由GraphicsOverlay類來進行建立新增的。通過Graphic物件將點或者線的圖形物件(SimpleMarkerSy

Arcgis for Js QueryTask查詢結果集的定位

通常我們在對服務查詢到結果集後,需要把視域定位到結果集上,這時可以使用到 graphicsUtils來實現    var queryTask = new esri.tasks.QueryTask(             "http://localhost:6080/arc

ArcGIS for Android示例解析之地圖旋轉-----MapRotation

  MapRotation 新增地圖控制元件,並且為地圖容器中新增地圖服務上面已經介紹完了,下面我們來個複雜一點的,這個例子主要實現了地圖的旋轉功能,下面來看一下應用的佈局檔案main.xml,內容如下: <com.esri.android.map.MapView

ArcGIS for Android示例解析之高亮要素-----HighlightFeatures

  HighlightFeatures 要素高亮化功能,相信有其他gis開發經營的開發人員都有過相應的實現經驗,對於高亮要素,簡單說起來就是我們查詢的或識別出來的要素進行渲染,讓其突出顯示而已,這個例子中涉及後面要介紹的識別的內容,我們只簡單介紹相關的知識,主要介紹要素物件

arcgis for android 地圖上畫框劃線

來源:http://blog.csdn.net/mwthe/article/details/49780161 主類中: 完成各種view初始化後,新增該程式碼  MyTouchListener  myListener = new MyTouchListener(contex