0
votes

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

There are 3 routes in the link, but I have to edit my code to process and display through all 3 routes. I am trying to find the shortest route, route that avoid tolls, and the fastest route (which i believe is the default one provided by 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();
        }
    }

Here is my JSONParser class

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

2 Answers

1
votes

I am assuming that if you set alternatives to true, the API is going to return multiple route objects. Given that you simply need to loop through the array of route objects and sort them based on their total length (distance).

0
votes

-By Default Google provide you shortest path if you set this key to false google gives you the shortest path alternatives=false

and if you want alternatives then you have to set below key to direction API:

-Unfortunately, there is not currently a way to have the API return the absolute shortest route in all situations.

but using avoid key in the direction API you are able to find the shortest route like below options:

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