In this tutorial, we’ll be creating an android application that draws a possible google map route between two points. We’ll be using Google Maps Directions API in our application.

Android Google Map – Drawing Route

Create a new Google Map API Key from the API console using the steps demonstrated in this tutorial.

Create a New Android Studio Project and select the template as Google Maps Activity. Add the API key inside the google_maps_api.xml file that resides inside debug->res->values folder

This is how the application should look if you’re using the latest Android Studio.

android-map-routing-output-1

Android Google Maps Drawing Path Project Structure

android-map-routing-output-1

The DirectionsJSONParser.java file is the one that parses the locations and returns the route. decodePoly() method is then invoked to get the polyline data that’s later drawn on the map.

Android Google Maps Drawing Route Code

The MainActivity.java code is given below.

We’ve called an onMapClickListener on the google map object. It’s used to set a marker on the clicked location and store that location in an ArrayList. The ArrayList is used to store the source and destination markers only.
The getDirectionsUrl() is called the Directions API URL with the output and parameters as shown below.

"https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

The output variable holds a “json” string and the parameter string is created as:
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

We’ve set the mode=driving in the current application.
The other modes of transport are:

  • driving (default)
  • walking
  • bicycling
  • transit

The output of the application is given below:

android google maps draw path

This brings an end to this tutorial. You can download the final project from the link below, add your own Google Map API key.

By admin

Leave a Reply

%d bloggers like this: