Draw path between two points using Google Maps Android API v2

前端 未结 4 1209
日久生厌
日久生厌 2020-11-22 11:46

Google changed its map API for Android and introduced API V2. The previous codes for drawing path are not working with API V2.

I have managed to draw a path with API

4条回答
  •  情深已故
    2020-11-22 12:21

    in below code midpointsList is an ArrayList of waypoints

    private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList midpointsList) {
        String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;
    
        String midpoints = "";
        for (int mid = 0; mid < midpointsList.size(); mid++) {
            midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
        }
    
        String waypoints = "waypoints=optimize:true" + midpoints + "|";
    
        String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
        String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";
    
        String sensor = "sensor=false";
        String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
    
    
        Log.e("url", url);
        parseDirectionApidata(url, googleMap);
        return url;
    }
    

    Then copy and paste this url in your browser to check And the below code is to parse the url

        private void parseDirectionApidata(String url, final GoogleMap googleMap) {
    
        final JSONObject jsonObject = new JSONObject();
    
        try {
    
            AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
                @Override
                public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {
    
                    if (jsonResult != null) {
    
                        Log.e("jsonRes", jsonResult.toString());
    
                        String status = jsonResult.optString("status");
    
                        if (status.equalsIgnoreCase("ok")) {
                            drawPath(jsonResult, googleMap);
                        }
    
                    } else {
    
                        Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
                    }
    
                }
            }, url, jsonObject);
    
        } catch (Exception e) {
            e.printStackTrace();
    
        }
    }
    

    And then pass the result to the drawPath method

        public void drawPath(JSONObject jObject, GoogleMap googleMap) {
    
        List>> routes = new ArrayList>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        List list = null;
        try {
    
            Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
            jRoutes = jObject.getJSONArray("routes");
    
            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList>();
    
                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
    
                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        list = decodePoly(polyline);
                    }
                    Log.e("list", list.toString());
                    routes.add(path);
                    Log.e("routes", routes.toString());
                    if (list != null) {
                        Polyline line = googleMap.addPolyline(new PolylineOptions()
                                .addAll(list)
                                .width(12)
                                .color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
                                .geodesic(true)
                        );
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
    }
    
      private List decodePoly(String encoded) {
    
        List poly = new ArrayList();
        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;
    }
    

    decode poly function is to decode the points(lat and long) provided by Directions API in encoded form

提交回复
热议问题