Google Maps Directions API

Peter-John Welcome
AndroidPub
Published in
4 min readJun 5, 2017

--

https://tinyurl.com/ycktd9ko

In my previous post, I spoke about how we can clean up our Google Map by clustering our markers together for a better user experience. Continuing with the Google Maps APIs, in this post I’ll be showing how to get direction information and draw a route between two end points on a map by using the Google Maps Directions API.

Getting Started

The Google Maps Directions API is a web service that Google provides us to get information about a route. A route is getting from an initial location to a specific destination. This web service provides us with information for different transport modes, waypoints and traveling times.

Since I’ll be demonstrating this API within an Android app, we can use the Java client library that is provided for us. There are also client libraries for Python, Go and Node.js available.

Note: This is assuming you have already set up a Google Map in your Android app. If not, then visit Google Maps API to get started.

To get this library into our app, we need to add the following to our build.gradle file.

compile 'com.google.maps:google-maps-services:0.1.20'

Before we start looking at some code, we also need to get a Google Directions API Key. This API is enabled in the Google Developer Console and the API key can also be retrieved from there.

Getting Directions

Now that we have all the configuration out the way, we can start implementing this API in our Android app.

Firstly, we will need to create a GeoApiContext object. This object is where we will set our API key and some restrictions:

  1. ConnectTimeout: The default connect timeout for new connections.
  2. QueryRate: The maximum number of queries that will be executed during a 1 second intervals.
  3. ReadTimeout: The default read timeout for new connections.
  4. WriteTimeout: The default write timeout for new connections.
private GeoApiContext getGeoContext() {      
GeoApiContext geoApiContext = new GeoApiContext();
return geoApiContext.setQueryRateLimit(3) .setApiKey(getString(R.string.directionsApiKey)) .setConnectTimeout(1, TimeUnit.SECONDS) .setReadTimeout(1, TimeUnit.SECONDS) .setWriteTimeout(1, TimeUnit.SECONDS);
}

Once we have our GeoApiContext, we can now use the DirectionsAPI class (which has a static method called newRequest) to request direction information. This newRequest method takes a GeoApiContext as an argument, which then returns us a DirectionsApiRequest.

On the DirectionsApiRequest object we have some methods that we need to set before we make this request. First we need to set our TravelMode, which can be Driving, Bicycling, Walking or Transit.

We then need to set our origin and our destination points. To accomplish this, there are two separate methods that return a DirectionsApiRequest that take either a LatLng or a String as an argument. What’s awesome about the methods which take in a String, is that the Latitude and Longitude will be automatically calculated based on the String address that you provide.

Lastly, we can call the departureTime method, so that we know the travel times that are returned are based on the departure time we provided. This method takes a simple DateTime object.

Now we can call the await method on the DirectionsApiRequest. This will make a synchronous call to the web service and return us a DirectionsResult object.

DateTime now = new DateTime();DirectionsResult result = DirectionsApi.newRequest(getGeoContext())                    .mode(TravelMode.DRIVING).origin(origin)                    .destination(destination).departureTime(now)                    .await();

What can we do with DirectionsResult?

Firstly, this returns LatLng objects for our origin and destination points so that we can place markers on our Google Map.

private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) {       
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].startLocation.lat,results.routes[0].legs[0].startLocation.lng)).title(results.routes[0].legs[0].startAddress));
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].endLocation.lat,results.routes[0].legs[0].endLocation.lng)).title(results.routes[0].legs[0].startAddress).snippet(getEndLocationTitle(results)));
}

We also get information like what the distance from the origin to destination is, based on the TravelMode we provided in the request. The API will return the amount of Time and Distance to get from the origin to the destination.

private String getEndLocationTitle(DirectionsResult results){        return  "Time :"+ results.routes[0].legs[0].duration.humanReadable + " Distance :" + results.routes[0].legs[0].distance.humanReadable;    }

Another field that is returned to us, is a overviewPolyline. This a path that we can use to represent these direction results on a Google Map.

private void addPolyline(DirectionsResult results, GoogleMap mMap) {        List<LatLng> decodedPath = PolyUtil.decode(results.routes[0].overviewPolyline.getEncodedPath());        
mMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}

The end up with a result as shown below:

This is a really awesome API, that solves many problems that many developers end up trying to solve themselves. This API has a lot more features, so I encourage you guys to look at the documentation.

If you would like me to cover more on this topic, let me know.

Go and try it yourself and let me know in the comments.

For a more complete example of the above code, you can visit my Github page:

Get in Touch!

Peter John Welcome — Google+

Thanks to Ashton Welcome and Joshua Leibstein for reviewing this post.

--

--

Peter-John Welcome
AndroidPub

Freelance Senior Mobile Engineer, Google Developer Expert for Firebase, Photographer