6

右鍵指定路線行駛,所以我目前使用的谷歌地圖API在我的應用程序來檢索兩個位置之間的路線。突出顯示在谷歌地圖V2的Android

當我發送路線指示的請求時,我會檢索JSON中有關路線的許多詳細信息,包括路線中每條道路的名稱,其相應的起點和終點經緯座標及其折線值。

例如:如果我將請求發送道路http://maps.googleapis.com/maps/api/directions/json?origin=redfern+ave,+dublin&destination=limetree+ave,+dublin&sensor=false兩者之間,我得到(沿着路線一條路輸出)以下JSON響應。

{ 
        "distance" : { 
         "text" : "0.2 km", 
         "value" : 203 
        }, 
        "duration" : { 
         "text" : "1 min", 
         "value" : 18 
        }, 
        "end_location" : { 
         "lat" : 53.435250, 
         "lng" : -6.132140000000001 
        }, 
        "html_instructions" : "Head \u003cb\u003eeast\u003c/b\u003e on \u003cb\u003eRedfern Ave.\u003c/b\u003e toward \u003cb\u003eMartello Court\u003c/b\u003e", 
        **"polyline" : { 
         "points" : "[email protected]}DOkDQqF"** 
        }, 

到目前爲止,我的應用程序解析這個信息和簡單的羅列像這樣的列表視圖中的道路和方向:

enter image description here

我想這樣做,可突出顯示整個路線是什麼B中的地圖上,但是我發現沒有什麼用處就如何做到這一點在新的谷歌地圖API第2版在線。我看到折線的使用,而不是覆蓋借鑑谷歌地圖V2線,但是從我所知道的,他們只畫直線是沒用的我。有沒有反正突出使用我所掌握的信息路線(道路名稱,開始&結束經緯座標,折線點?任何幫助表示讚賞。

此外,我看到有一個'折線「在響應值可能是有用的,但我不知道如何解析或使用的信息,該位。有誰知道我怎樣才能使這個價值感繪製折線?

**"polyline" : { 
      "points" : "[email protected]}DOkDQqF"** 

編輯:我的解決方案的代碼在我的回答如下提供

回答

34

我終於設法得到了很多的試驗和錯誤後工作!現在它在地圖上完全突出顯示從A到B的指定路線(如下面的屏幕截圖所示)。我還將代碼放入了將來可能需要它的任何人。

enter image description here

public class PolyMap extends Activity { 
     ProgressDialog pDialog; 
     GoogleMap map; 
     List<LatLng> polyz; 
     JSONArray array; 
     static final LatLng DUBLIN = new LatLng(53.344103999999990000, 
       -6.267493699999932000); 

     @SuppressLint("NewApi") 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.map_layout); 
      map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) 
        .getMap(); 
      map.moveCamera(CameraUpdateFactory.newLatLngZoom(DUBLIN, 15)); 
      map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
      new GetDirection().execute(); 
     } 

     class GetDirection extends AsyncTask<String, String, String> { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog = new ProgressDialog(PolyMap.this); 
       pDialog.setMessage("Loading route. Please wait..."); 
       pDialog.setIndeterminate(false); 
       pDialog.setCancelable(false); 
       pDialog.show(); 
      } 

      protected String doInBackground(String... args) { 
       Intent i = getIntent(); 
       String startLocation = i.getStringExtra("startLoc"); 
       String endLocation = i.getStringExtra("endLoc"); 
          startLocation = startLocation.replace(" ", "+"); 
        endLocation = endLocation.replace(" ", "+");; 
       String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + startLocation + ",+dublin&destination=" + endLocation + ",+dublin&sensor=false"; 
       StringBuilder response = new StringBuilder(); 
       try { 
        URL url = new URL(stringUrl); 
        HttpURLConnection httpconn = (HttpURLConnection) url 
          .openConnection(); 
        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
         BufferedReader input = new BufferedReader(
           new InputStreamReader(httpconn.getInputStream()), 
           8192); 
         String strLine = null; 

         while ((strLine = input.readLine()) != null) { 
          response.append(strLine); 
         } 
         input.close(); 
        } 

        String jsonOutput = response.toString(); 

        JSONObject jsonObject = new JSONObject(jsonOutput); 

        // routesArray contains ALL routes 
        JSONArray routesArray = jsonObject.getJSONArray("routes"); 
        // Grab the first route 
        JSONObject route = routesArray.getJSONObject(0); 

        JSONObject poly = route.getJSONObject("overview_polyline"); 
        String polyline = poly.getString("points"); 
        polyz = decodePoly(polyline); 

       } catch (Exception e) { 

       } 

       return null; 

      } 

      protected void onPostExecute(String file_url) { 

       for (int i = 0; i < polyz.size() - 1; i++) { 
        LatLng src = polyz.get(i); 
        LatLng dest = polyz.get(i + 1); 
        Polyline line = map.addPolyline(new PolylineOptions() 
          .add(new LatLng(src.latitude, src.longitude), 
            new LatLng(dest.latitude,    dest.longitude)) 
          .width(2).color(Color.RED).geodesic(true)); 

       } 
       pDialog.dismiss(); 

      } 
     } 

     /* Method to decode polyline points */ 
     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; 
     } 
    } 
+1

這對我很有幫助。謝謝。如果要重複使用相同的地圖,則必須考慮將Polyline線保存在數組中,並且您可以從該地圖中刪除線。 –

+0

那麼有一個共同發生,我今天幾乎花了幾個小時試圖找出爲什麼line.remove()不工作。謝謝! –

+0

感謝您附上您的代碼:) –

2

隨着Android的地圖API 2確實需要使用。類在地圖上繪製路線(至少它是一個最簡單的方法:))。你需要做的是 - 提供你的路線上的積分列表。

至於突出活動路由 - 存在PolylinesetColor一個方便的界面,讓您可以設置要活動路由任何顏色(包括alpha通道)

Polyline line1 = map.addPolyline(new PolylineOptions() 
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0)) 
.width(5) 
.color(0xFFFF0000)); //non transparent red 

Polyline line2 = map.addPolyline(new PolylineOptions() 
.add(new LatLng(51.5, -0.1), new LatLng(40.8, -74.2)) 
.width(5) 
.color(0x7F0000FF)); //semi-transparent blue 

請注意,您是隨意改變你想要的顏色折線隨時(用戶點擊網絡連接,或某事)

至於從谷歌JSON響應 - 路線點進行編碼,所以你可以參考this question瞭解如何對其進行解碼

+0

好吧,如果你在路上有10個點,折線將吸引10(實際上是9)直接相互連接線..多少分你的路線和這些點的實際座標是什麼 - 這個信息被編碼成「點」字段 –

+0

得到它的工作:D謝謝! –

1

有一個簡單的解決方案

添加庫

編譯「com.google.maps.android:android-maps-utils:0。從 4+」

參考https://developers.google.com/maps/documentation/android-api/utility/setup

//Getting the points String from response of NavigationAPI call 
String polyz=routeSteps.get(0).getOverview_polyline().getPoints(); 
//Decoding the LatLng Points using PolyUtil Class used from above Library 
List<LatLng> points=PolyUtil.decode(polyz); 
polyline.addAll(points); 
googleMap.addPolyline(polyline);