как использовать ответ Google direction api для отображения drive road на карте

#android #google-maps #google-maps-android-api-2

#Android #google-карты #google-maps-android-api-2

Вопрос:

после получения следующего ответа от Google direction api, как я могу отобразить дорогу на карте, как показано на рисунке ниже? и как я могу переключиться на просмотр улиц? .

https://ddewaele.github.io/GoogleMapsV2WithActionBarSherlock/part5 вот мой код :

  RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://maps.googleapis.com/maps/api/directions/json?origin=Disneylandamp;destination=Universal Studios Hollywood4amp;key=AIzaSyBX40zJvRu0PBVs5iA0xG_cmdpVAUKYmmQ";
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        Log.e("Response is: ", response.toString());
                        ////////////////json response //////////
                        try {
                            String responseString;
                            JSONObject responseObject = (JSONObject) new JSONTokener(response.toString()).nextValue();
                            responseString = responseObject.getString("status");
                            JSONArray routesArray = responseObject.getJSONArray("routes");
                            JSONObject route = routesArray.getJSONObject(0);
                            JSONArray legs;
                            JSONObject leg;
                            JSONArray steps;
                            JSONObject dist;
                            Integer distance;
                            if (route.has("legs")) {
                                legs = route.getJSONArray("legs");
                                leg = legs.getJSONObject(0);
                                steps = leg.getJSONArray("steps");
                                int nsteps = steps.length();
                                for (int i = 0; i < nsteps; i  ) {
                                    JSONObject step = steps.getJSONObject(i);
                                    if (step.has("distance")) {
                                        dist = (JSONObject) step.get("distance");
                                        if (dist.has("value"))
                                            distance = (Integer) dist.get("value");
                                    }
                                }
                            } else
                                responseString = "not found";
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ////////////////////////////

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Response is: ", "error");

            }
        });
  

вот ответ :

 {
   "geocoded_waypoints":[
      {
         "geocoder_status":"OK",
         "place_id":"ChIJRVY_etDX3IARGYLVpoq7f68",
         "types":[
            "bus_station",
            "establishment",
            "point_of_interest",
            "transit_station"
         ]
      },
      {
         "geocoder_status":"OK",
         "partial_match":true,
         "place_id":"ChIJE0RfH0m-woAROpQUDVXcp1A",
         "types":[
            "route"
         ]
      }
   ],
   "routes":[
      {
         "bounds":{
            "northeast":{
               "lat":34.1380726,
               "lng":-117.9143879
            },
            "southwest":{
               "lat":33.8068768,
               "lng":-118.3545268
            }
         },
         "copyrights":"Map data ©2016 Google",
         "legs":[
            {
               "distance":{
                  "text":"36.5 mi",
                  "value":58724
               },
               "duration":{
                  "text":"53 mins",
                  "value":3192
               },
               "end_address":"Studio way, North Hollywood, CA 91602, USA",
               "end_location":{
                  "lat":34.1378505,
                  "lng":-118.3545268
               },
               "start_address":"Disneyland (Harbor Blvd.), S Harbor Blvd, Anaheim, CA 92802, USA",
               "start_location":{
                  "lat":33.8098177,
                  "lng":-117.9154353
               },
               "steps":[
                  {
                     "distance":{
                        "text":"0.2 mi",
                        "value":310
                     },
                     "duration":{
                        "text":"1 min",
                        "value":79
                     },
                     "end_location":{
                        "lat":33.8070347,
                        "lng":-117.9154133
                     },
                     "html_instructions":"Head u003cbu003esouthu003c/bu003e on u003cbu003eS Harbor Blvdu003c/bu003e",
                     "polyline":{
                        "points":"knjmEnjunUNAb@@Z?RALA`@B~D?n@ChDA"
                     },
                     "start_location":{
                        "lat":33.8098177,
                        "lng":-117.9154353
                     },
                     "travel_mode":"DRIVING"
                  },
                  {
                     "distance":{
                        "text":"0.6 mi",
                        "value":1039
                     },
                     "duration":{
                        "text":"3 mins",
                        "value":195
                     },
                     "end_location":{
                        "lat":33.8159247,
                        "lng":-117.9152992
                     },
                     "html_instructions":"Make a u003cbu003eU-turnu003c/bu003e at u003cbu003eDisney Wayu003c/bu003e",
                     "maneuver":"uturn-left",
                     "polyline":{
                        "points":"}|imEhjunU\??_@]@cIBgC?Q@sD?wDEi@A{@?s@AqB?M@M?aB?oDB_@?y@?M?O?IAE?I?O?]?C?s@?{@@K?m@D"
                     },
                     "start_location":{
                        "lat":33.8070347,
                        "lng":-117.9154133
                     },
                     "travel_mode":"DRIVING"
                  },
                  {
                     "distance":{
                        "text":"22.9 mi",
                        "value":36928
                     },
                     "duration":{
                        "text":"27 mins",
                        "value":1593
                     },
                     "end_location":{
                        "lat":34.0255711,
                        "lng":-118.2060101
                     },
                     "html_instructions":"                     Take the ramp onto u003cbu003eI-5 Nu003c/bu0
  

Ответ №1:

Вы можете проанализировать ответ JSON и извлечь свойство overview_polyline из JSON. Добавьте утилиты Android map в свой файл gradle:

 compile 'com.google.maps.android:android-maps-utils:0.4'
  

С утилями Android map у вас будет com.google.maps.android.Класс PolyUtil, который может декодировать закодированную ломаную линию из свойства overview_polyline и получать список LatLng.

Фрагмент кода может быть чем-то вроде:

 MapFragment mapFrag = (MapFragment)
            getFragmentManager().findFragmentById(R.id.route_map);
    if(mapFrag!=null amp;amp; jsonRoute != null){
        mapFrag.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                try {
                    if (jsonRoute.has("status") amp;amp; jsonRoute.getString("status").equals("OK")) {
                        if (jsonRoute.has("routes")) {
                            JSONArray rts = jsonRoute.getJSONArray("routes");
                            if (rts != null amp;amp; rts.length() > 0 amp;amp; !rts.isNull(0)) {
                                JSONObject r = rts.getJSONObject(0);
                                if (r.has("overview_polyline") amp;amp; !r.isNull("overview_polyline")) {
                                    JSONObject m_poly = r.getJSONObject("overview_polyline");
                                    if (m_poly.has("points") amp;amp; !m_poly.isNull("points")) {
                                        String enc_points = m_poly.getString("points");
                                        List<LatLng> m_path = PolyUtil.decode(enc_points);
                                        PolylineOptions polyOptions = new PolylineOptions().addAll(m_path);
                                        googleMap.addPolyline(polyOptions);

                                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                        for(LatLng coord : m_path){
                                            builder.include(coord);
                                        }
                                        LatLngBounds m_bounds = builder.build();
                                        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(m_bounds, 10));
                                    }
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Cannot process directions JSON results", e);
                }
            }
        });
    }
  

Надеюсь, это поможет!