Как узнать кратчайший маршрут из Google Maps с указанием альтернатив = true? - PullRequest
0 голосов
/ 23 мая 2018

Google Directions Api: https://maps.googleapis.com/maps/api/directions/json?origin=1.29068,103.851743&destination=1.324298,103.9032129&sensor=false&mode-driving&alternatives=true

В ссылке 3 маршрута, но мне нужно отредактировать код для обработки и отображения всех 3 маршрутов.Я пытаюсь найти кратчайший маршрут, маршрут, позволяющий избежать платы за проезд, и самый быстрый маршрут (который, по моему мнению, является маршрутом по умолчанию, предоставленным Google)

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
        JSONObject jsonObject;
        List<List<HashMap<String, String>>> routes = null;
        try {
            jsonObject = new JSONObject(strings[0]);
            DirectionsJSONParser directionsJSONParser = new DirectionsJSONParser();
            routes = directionsJSONParser.parse(jsonObject);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
        //Get list route and display

        ArrayList points = null;
        PolylineOptions polylineOptions = null;
        String distance = "";
        String duration = "";
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();

        for (int i = 0; i < lists.size(); i++) {
            points = new ArrayList();
            polylineOptions = new PolylineOptions();

            List<HashMap<String, String>> path = lists.get(i);

            for (int j = 0; j < path.size(); j++) {

                HashMap<String, String> point = path.get(j);

                if(j==0){ // Get distance from the list
                    distance = point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
                boundsBuilder.include(position);


            }

            polylineOptions.addAll(points);
            polylineOptions.width(12);
            polylineOptions.color(Color.RED);
            polylineOptions.geodesic(true);

        }



        if (polylineOptions != null) {
            mMap.addPolyline(polylineOptions);
            LatLngBounds routeBounds = boundsBuilder.build();
            mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(routeBounds, 12));
            mDisTextView.setText(distance);
            mDuraTextView.setText(duration);
        } else {
            Toast.makeText(MapActivity.this, "Directions not found!", Toast.LENGTH_SHORT).show();
        }
    }

Вот мой класс JSONParser

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;
    JSONObject jDistance = null;
    JSONObject jDuration = null;

    try {

        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<HashMap<String, String>>();

            /** Traversing all legs */
            for(int j=0;j<jLegs.length();j++){
                /** Getting distance from the json data */
                jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                HashMap<String, String> hmDistance = new HashMap<String, String>();
                hmDistance.put("distance", jDistance.getString("text"));

            /** Getting duration from the json data */
                jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                HashMap<String, String> hmDuration = new HashMap<String, String>();
                hmDuration.put("duration", jDuration.getString("text"));

            /** Adding distance object to the path */
                path.add(hmDistance);

            /** Adding duration object to the path */
                path.add(hmDuration);

                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 list = decodePoly(polyline);

                    /** Traversing all points */
                    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 (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }

    return routes;
}

/**
 * Method to decode polyline points
 * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
 * */
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;
}

}

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Я предполагаю, что если вы установите в качестве альтернативы значение true, API вернет несколько объектов маршрута.Учитывая, что вам просто нужно перебрать массив объектов маршрута и отсортировать их по их общей длине (расстоянию).

0 голосов
/ 23 мая 2018

-По умолчанию Google предоставит вам кратчайший путь, если вы установите для этого ключа значение false, Google даст вам кратчайший путь альтернативы = ложь

, и если вы хотите альтернативы, вам нужно установить нижеключ к направлению API:

- к сожалению, в настоящее время нет способа заставить API вернуть абсолютный кратчайший маршрут во всех ситуациях.

, но с использованием избежать введите API направления, вы можете найти кратчайший маршрут, как показано ниже:

Google Directions Api: 
https://maps.googleapis.com/maps/api/directions/json?origin=1.29068,103.851743&destination=1.324298,103.9032129&avoid=highways&sensor=false&mode-driving&alternatives=true
...