AndroidDev AndroidDev - 2 months ago 24
Android Question

Find route with Androids Google Maps API

I want to be able to display the route between two user-defined geographical points using the Google Maps API for Android. I also want to be able to let the user choose what type of route to display, whether it be walking, cycling, car etc. Additionally, I want to be able to calculate the time and distance it would take to use this route. I've tried searching the web and looking at other stackoverflow questions, but to no avail. How would I go about this? How would I be able to code this.

//----EDIT----//

I would also like to get traffic information such as busy routes, congestion, etc.

Answer

Here's some code to help you.

String url= 
"http://maps.googleapis.com/maps/api/directions/json?origin=" 
+ origin.latitude + "," + origin.longitude +"&destination=" 
+ destination.latitude + "," + destination.longitude + "&sensor=false";

To fetch the data with androidhttpclient, do something like this:

HttpResponse response;
HttpGet request;
AndroidHttpClient client = AndroidHttpClient.newInstance("somename");

request = new HttpGet(url);
response = client.execute(request);

InputStream source = response.getEntity().getContent();
String returnValue = buildStringIOutils(source);

return returnValue;

where buildStringIOUtils is:

private String buildStringIOutils(InputStream is) {
    try {
        return IOUtils.toString(is, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

You can then extract the actual polyline from the JSON-response with something like this:

JSONObject result = new JSONObject(returnValue);
JSONArray routes = result.getJSONArray("routes");

                    long distanceForSegment = routes.getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getInt("value");

                    JSONArray steps = routes.getJSONObject(0).getJSONArray("legs")
                            .getJSONObject(0).getJSONArray("steps");

                    List<LatLng> lines = new ArrayList<LatLng>();

                    for(int i=0; i < steps.length(); i++) {
                        String polyline = steps.getJSONObject(i).getJSONObject("polyline").getString("points");

                        for(LatLng p : decodePolyline(polyline)) {
                            lines.add(p);
                        }
                    }

where the method decodePolyline is this:

    /** POLYLINE DECODER - http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java **/
    private List<LatLng> decodePolyline(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;
    }

You can then add the polyline to the map with this:

Polyline polylineToAdd = mMap.addPolyline(new PolylineOptions().addAll(lines).width(3).color(Color.RED));

To change mode, add this to the url (See https://developers.google.com/maps/documentation/directions/): &mode=YOUR_MODE

driving (default) indicates standard driving directions using the road network.

walking requests walking directions via pedestrian paths & sidewalks (where available).

bicycling requests bicycling directions via bicycle paths & preferred streets (where available).

transit requests directions via public transit routes (where available).

Edit: About the "I would also like to get traffic information such as busy routes, congestion, etc." I have not looked into this, but my code should get you started pretty good.

Edit2: Found this in the google directions api: "For Driving Directions: Maps for Business customers can specify the departure_time to receive trip duration considering current traffic conditions. The departure_time must be set to within a few minutes of the current time."

Comments