2016-11-12 106 views
0

我想繪製兩點之間的路徑並計算從A點移動到B點需要多少時間。我認爲這對於Google Maps API來說是微不足道的任務。Android谷歌地圖在兩點之間繪製一條路徑

我發現的一切都是關於PolyUtil的小片段,其中documentation並沒有說明如何使用它。

我做了什麼?

裏面onMapReady方法我試圖創建一個編碼的路徑MapsActivity

List<LatLng> latLngList = new ArrayList<>(); 
latLngList.add(new LatLng(56.952503, 24.083719)); 
latLngList.add(new LatLng(55.877526, 26.533898)); 

String encodedPath = PolyUtil.encode(latLngList); 

但是,什麼是下一個?如何在地圖上繪製此路徑?如何計算這些點之間的車/步行距離?

+0

@回答這些問題 - 答案是從2010-2013。這是真的嗎? – VLeonovs

+0

請看https://android-arsenal.com/details/1/4157 – Saveen

+0

https:// android-arsenal。com/details/1/1106看看 – Saveen

回答

12

路徑是點的序列。其中一個解決方案是向谷歌地圖API發出HTTP請求,指定您的兩個位置作爲參數,並取回描述在兩點之間建立路徑所需的點的JSON。需要的代碼做如下:

  1. 獲取路線URL需要調用谷歌地圖API
private String getMapsApiDirectionsUrl(LatLng origin,LatLng dest) { 
    // Origin of route 
String str_origin = "origin="+origin.latitude+","+origin.longitude; 

// Destination of route 
String str_dest = "destination="+dest.latitude+","+dest.longitude;   


// Sensor enabled 
String sensor = "sensor=false";    

// Building the parameters to the web service 
String parameters = str_origin+"&"+str_dest+"&"+sensor; 

// Output format 
String output = "json"; 

// Building the url to the web service 
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters; 


return url; 

} 
  • 執行URL在後臺致電

    private class ReadTask extends AsyncTask<String, Void , String> { 
    
    @Override 
    protected String doInBackground(String... url) { 
        // TODO Auto-generated method stub 
        String data = ""; 
        try { 
         MapHttpConnection http = new MapHttpConnection(); 
         data = http.readUr(url[0]); 
    
    
        } catch (Exception e) { 
         // TODO: handle exception 
         Log.d("Background Task", e.toString()); 
        } 
        return data; 
    } 
    
    @Override 
    protected void onPostExecute(String result) { 
        super.onPostExecute(result); 
        new ParserTask().execute(result); 
    } 
    
    } 
    
  • public class MapHttpConnection { 
        public String readUr(String mapsApiDirectionsUrl) throws IOException{ 
         String data = ""; 
         InputStream istream = null; 
         HttpURLConnection urlConnection = null; 
         try { 
          URL url = new URL(mapsApiDirectionsUrl); 
          urlConnection = (HttpURLConnection) url.openConnection(); 
          urlConnection.connect(); 
          istream = urlConnection.getInputStream(); 
          BufferedReader br = new BufferedReader(new InputStreamReader(istream)); 
          StringBuffer sb = new StringBuffer(); 
          String line =""; 
          while ((line = br.readLine()) != null) { 
           sb.append(line); 
          } 
          data = sb.toString(); 
          br.close(); 
    
    
         } 
         catch (Exception e) { 
          Log.d("Exception while reading url", e.toString()); 
         } finally { 
          istream.close(); 
          urlConnection.disconnect(); 
         } 
         return data; 
    
        } 
    } 
    
  • 創建解析器類從JSON解析數據列出pointes的

    public class PathJSONParser { 
    
    public List<List<HashMap<String, String>>> parse(JSONObject jObject) { 
        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>(); 
        JSONArray jRoutes = null; 
        JSONArray jLegs = null; 
        JSONArray jSteps = null; 
        try { 
         jRoutes = jObject.getJSONArray("routes"); 
         for (int i=0 ; i < jRoutes.length() ; i ++) { 
          jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs"); 
          List<HashMap<String, String>> path = new ArrayList<HashMap<String,String>>(); 
          for(int j = 0 ; j < jLegs.length() ; j++) { 
           jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps"); 
           for(int k = 0 ; k < jSteps.length() ; k ++) { 
            String polyline = ""; 
            polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points"); 
            List<LatLng> list = decodePoly(polyline); 
            for(int l = 0 ; l < list.size() ; l ++){ 
             HashMap<String, String> hm = new HashMap<String, String>(); 
             hm.put("lat", 
               Double.toString(((LatLng) list.get(l)).latitude)); 
             hm.put("lng", 
               Double.toString(((LatLng) list.get(l)).longitude)); 
             path.add(hm); 
            } 
           } 
           routes.add(path); 
          } 
    
         } 
    
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
        return routes; 
    
    } 
    
    private List<LatLng> decodePoly(String encoded) { 
        List<LatLng> poly = new ArrayList<LatLng>(); 
        int index = 0, len = encoded.length(); 
        int lat = 0, lng = 0; 
    
        while (index < len) { 
         int b, shift = 0, result = 0; 
         do { 
          b = encoded.charAt(index++) - 63; 
          result |= (b & 0x1f) << shift; 
          shift += 5; 
         } while (b >= 0x20); 
         int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
         lat += dlat; 
    
         shift = 0; 
         result = 0; 
         do { 
          b = encoded.charAt(index++) - 63; 
          result |= (b & 0x1f) << shift; 
          shift += 5; 
         } while (b >= 0x20); 
         int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
         lng += dlng; 
    
         LatLng p = new LatLng((((double) lat/1E5)), 
           (((double) lng/1E5))); 
         poly.add(p); 
        } 
        return poly; 
    }} 
    
  • 的使用另一線程執行解析擴大性能

  • private class ParserTask extends AsyncTask<String,Integer, List<List<HashMap<String , String >>>> { 
        @Override 
        protected List<List<HashMap<String, String>>> doInBackground(
          String... jsonData) { 
         // TODO Auto-generated method stub 
         JSONObject jObject; 
         List<List<HashMap<String, String>>> routes = null; 
         try { 
          jObject = new JSONObject(jsonData[0]); 
          PathJSONParser parser = new PathJSONParser(); 
          routes = parser.parse(jObject); 
    
    
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
         return routes; 
        } 
    
        @Override 
        protected void onPostExecute(List<List<HashMap<String, String>>> routes) { 
         ArrayList<LatLng> points = null; 
         PolylineOptions polyLineOptions = null; 
    
         // traversing through routes 
         for (int i = 0; i < routes.size(); i++) { 
          points = new ArrayList<LatLng>(); 
          polyLineOptions = new PolylineOptions(); 
          List<HashMap<String, String>> path = routes.get(i); 
    
          for (int j = 0; j < path.size(); j++) { 
           HashMap<String, String> point = path.get(j); 
    
           double lat = Double.parseDouble(point.get("lat")); 
           double lng = Double.parseDouble(point.get("lng")); 
           LatLng position = new LatLng(lat, lng); 
    
           points.add(position); 
          } 
    
          polyLineOptions.addAll(points); 
          polyLineOptions.width(4); 
          polyLineOptions.color(Color.BLUE); 
         } 
    
         googleMap.addPolyline(polyLineOptions); 
    
        }} 
    
  • 當要得到兩個點的路徑
  • String url = getMapsApiDirectionsUrl(latlngOne, latlngTwo);      
        ReadTask downloadTask = new ReadTask();  
        // Start downloading json data from Google Directions API 
        downloadTask.execute(url); 
    

    爲了計算點之間的距離

    float[] results = new float[1]; 
    Location.distanceBetween(latLongA.latitude, latLongB.longitude, 
             latLongB.latitude, latLongB.longitude, 
             results); 
    

    結果將在m eters

    +0

    什麼是ReadTask中的MapHttpConnection? – VLeonovs

    +0

    這是另一個類我用來舉行連接,我會更新答案 –

    +0

    謝謝。這個對我有用。 – ashishdhiman2007

    相關問題