Android Example : Draw route between two location using Google Direction

Andrea
2 min readSep 22, 2019

--

This tutorial will explain how to drawing route between two location using Google Direction API and display it on screen. To follow on this tutorial, basic understanding of Java/Kotlin and Android Studio is necessary.

  1. Prepare data

As main input we need latitude and longitude for two location which we want to connect.

Barcelona : 41.3949 , 2.0086

Tarragona : 41.1258 ,1.2035

2. Project setup

Create new project on Android Studio, choose Google Map Activity as first activity. Android Studio will display google_maps_api.xml in its window. Follow the link inside the google_maps_api.xml, create new project -> create new API Key. Copy the API Key that just been created, paste it to replace YOUR_API_KEY_HERE on google_maps_api.xml

3. Styling UI

Now, I’d like the display of the screen not only display Map, but also textview and include some margin to make it looks better. So, we need to edit the layout on activity_maps.xml

4. Display two location pin on the map

The next step we can display pin for origin and destination location. Edit the code on the MapsActivity.java and display location from OnMapReady method.

5. Request data from Google Direction API and parse it

Google Directions API is a service that calculates directions between locations. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.

To be able to request data from Google Direction API, we need request url. Copy this method and paste it inside MapsActivity.

Once we have the requested url ready, we can request Json data from Google Direction API. Copy and paste this method to MapsActivity.

However requestDirection method should be called from AsyncTask :

And on the post execute we can parse the Json data that we get from Google Direction API. The Json data parsing task should be execute in another AsyncTask.

For the final step, we need to execute the TaskDirectionRequest AsyncTask from onMapReady method.

Run it on our emulator, and voila it appears!

Complete code can be found on my github.

Further studies : https://developers.google.com/maps/documentation/directions/start

--

--