<p>In this article, we will discuss how to draw route between two locations in GoogleMap using <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://developers.google.com/maps/documentation/directions/intro">Directions API</a></strong></span>.</p>
<h3><span style="color: #000080;"><strong>Directions API</strong></span></h3>
<p>The Directions API is a service that calculates directions between locations using an HTTP request.</p>
<p>With the Directions API, you can:</p>
<ul>
<li>Search for directions for several modes of transportation, including transit, driving, walking or cycling.</li>
<li>Return multi-part directions using a series of waypoints.</li>
<li>Specify origins, destinations, and waypoints as text strings (e.g. &#8220;Chicago, IL&#8221; or &#8220;Darwin, NT, Australia&#8221;), or as latitude/longitude coordinates, or as place IDs.</li>
</ul>
<p><strong><span style="color: #008000;">GET GITHUB CODE FROM</span></strong> <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://github.com/arunk7839/MapDirectionDemo">HERE</a>.</strong></span></p>
<h3><span style="color: #000080;"><strong>Creating New Project</strong></span></h3>
<p><strong>1</strong>. Create a new project in <span style="color: #008000;"><strong>Android Studio</strong></span> from <span style="color: #008000;"><strong>File ⇒ New Project</strong></span> and fill the project details.</p>
<p><strong>2</strong>. In the <span style="color: #008000;"><strong>Choose your project</strong> </span>dialog, select the tab that corresponds to the platform you intended to develop for. Select <span style="color: #008000;"><strong>Phone and Tablet</strong></span>.</p>
<p><strong>3</strong>. Select <span style="color: #008000;"><strong>Google Maps Activity</strong></span>, then click <span style="color: #008000;"><strong>Next</strong></span>.</p>
<p><img class="alignnone size-full wp-image-1283" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-14-18.05.53.png" alt="Screenshot 2019-11-14 18.05.53" width="1806" height="1100" /></p>
<p><strong>4</strong>.Enter your app name, package name, and project location, programming language (Java or Kotlin), and the minimum Android API level supported by your app, then click <span style="color: #008000;"><strong>Finish</strong></span>.</p>
<p><img class="alignnone size-full wp-image-1309" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-19-19.03.32.png" alt="Screenshot 2019-11-19 19.03.32" width="1798" height="1268" /></p>
<h4><span style="color: #000080;"><strong>Getting the API key</strong></span></h4>
<p><strong>5</strong>.Copy the URL from <span style="color: #0000ff;"><strong>google_map_api.xml</strong></span> file to generate Google map API key.</p>
<p><strong>6</strong>.Paste the copied URL at the browser. It will open the following page. Here I have selected my project <strong>GoogleMapExample</strong>.</p>
<p><img class="alignnone size-full wp-image-1286" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-14-18.24.38-2702355708-1574321829820.png" alt="Screenshot 2019-11-14 18.24.38" width="908" height="435" /></p>
<p><strong>7</strong>.Click on <span style="color: #008000;"><strong>Create API key</strong></span> to generate API key.</p>
<p><img class="alignnone size-full wp-image-1288" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-14-18.28.46-1128114308-1574321904187.png" alt="Screenshot 2019-11-14 18.28.46" width="752" height="369" /></p>
<p><strong>8</strong>.After clicking on <span style="color: #008000;"><strong>Create API key</strong></span>, it will generate an API key displaying the following screen.</p>
<p><img class="alignnone size-full wp-image-1290" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-14-18.31.40.png" alt="Screenshot 2019-11-14 18.31.40" width="1592" height="796" /></p>
<p><strong>9</strong>.Copy this generated API key and click on the <span style="color: #008000;"><strong>CLOSE</strong></span> button. Now paste it in your <span style="color: #008000;"><strong>google_map_api.xml</strong></span> file.</p>
<p><img class="alignnone size-full wp-image-1291" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-14-18.34.28-2238297101-1573829461234.png" alt="Screenshot 2019-11-14 18.34.28" width="1974" height="310" /></p>
<p><strong>10</strong>.Select <span style="color: #0000ff;"><strong>Library</strong></span> from<span style="color: #0000ff;"><span style="color: #000000;"> the left side and then</span></span> search for <span style="color: #008000;"><strong>Direction API</strong></span> and enable it.</p>
<p><img class="alignnone size-full wp-image-1310" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-19-19.26.57.png" alt="Screenshot 2019-11-19 19.26.57" width="1386" height="592" /></p>
<p><strong>11</strong>.Go to <span style="color: #0000ff;"><strong>Credentials.</strong></span> Click on the currently created API key and the following screen appears:</p>
<p><img class="alignnone size-full wp-image-1312" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-19-19.17.21.png" alt="Screenshot 2019-11-19 19.17.21" width="1516" height="924" /></p>
<p><strong>12</strong> .Under <span style="color: #0000ff;"><strong>Application restrictions </strong></span>select <strong><span style="color: #008000;">None</span> </strong>and under <span style="color: #0000ff;"><strong>API restrictions</strong> </span>select <span style="color: #008000;"><strong>Restrict Key </strong></span>and then select the two APIs<span style="color: #008000;"><strong> Direction API </strong></span>and<strong><span style="color: #008000;"> Maps SDK for Android</span>. </strong>Finally, don&#8217;t forget to click on <span style="color: #008000;"><strong>SAVE</strong></span>.</p>
<p><img class="alignnone size-full wp-image-1311" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot-2019-11-19-19.17.56.png" alt="Screenshot 2019-11-19 19.17.56" width="1520" height="1170" /></p>
<p class="p1"><strong>13</strong>.After creating an API key you must enable <strong><span style="color: #008000;">Billing</span></strong> on the Google Cloud Project at <strong><span style="color: #0000ff;">https://console.cloud.google.com/project/_/billing/enable</span></strong>. Learn more at <strong><span style="color: #0000ff;">https://developers.google.com/maps/gmp-get-started</span></strong>.</p>
<p><strong>14</strong>.Open <strong><span style="color: #008000;">build.gradle</span>.</strong>Here you can see a new library to integrate google Maps gets added.</p>
<p><span style="color: #0000ff;"><strong>build.gradle</strong></span></p>
<pre>dependencies {
 implementation fileTree(dir: 'libs', include: ['*.jar'])
 implementation 'androidx.appcompat:appcompat:1.0.2'

 <strong><span style="color: #008000;">//Google Maps</span></strong>
 implementation 'com.google.android.gms:play-services-maps:16.1.0'
 testImplementation 'junit:junit:4.12'
 androidTestImplementation 'androidx.test:runner:1.1.1'
 androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}</pre>
<p><strong>15</strong>.Open <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> file and add the below user-permissions as shown below.</p>
<p><span style="color: #0000ff;"><strong>INTERNET</strong></span> – To communicate with API .<br />
<span style="color: #0000ff;"><strong>ACCESS_COARSE_LOCATION</strong> </span>– To determine user’s location using WiFi and mobile cell data. It will give you an approximate location.<br />
<span style="color: #0000ff;"><strong>ACCESS_FINE_LOCATION</strong></span> – To determine user’s location using GPS. It will give you precise location.</p>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.mapdirectiondemo">;

 <span style="color: #008000;"><strong><;uses-permission android:name="android.permission.INTERNET"/>;</strong></span>
<span style="color: #008000;"><strong> <;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>;</strong></span>
<span style="color: #008000;"><strong> <;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>;</strong></span>

 <;application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:roundIcon="@mipmap/ic_launcher_round"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">;

 <;activity
 android:name=".MapsActivity"
 android:label="@string/title_activity_maps">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

 <;category android:name="android.intent.category.LAUNCHER" />;
 <;/intent-filter>;
 <;/activity>;

 <strong><span style="color: #008000;"><;meta-data
 android:name="com.google.android.geo.API_KEY"
 android:value="@string/google_maps_key" />;</span></strong>
 <;/application>;
<;/manifest>;</pre>
<p><strong>16</strong>.Google maps are implemented using <span style="color: #008000;"><strong>Support</strong><strong>MapFragment</strong></span> which is a subclass of <span style="color: #008000;"><strong>Fragment</strong></span> class. By default, the XML file that defines the app’s layout is at <span style="color: #008000;"><strong>res/layout/activity_maps.xml</strong></span>. It contains the following code:</p>
<p class="h3"><span style="color: #0000ff;"><strong>activity_maps.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;fragment xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:map="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/map"
 android:name="com.google.android.gms.maps.SupportMapFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MapsActivity" />;</pre>
<p><strong>17</strong>.Let&#8217;s understand the methods and AsyncTask used in <span style="color: #008000;"><strong>MainActivity.Java</strong></span>.</p>
<p><strong><span style="color: #0000ff;">getDirectionsUrl(): </span></strong>Getting URL to the Google Directions API based on output, parameters, and the API key.</p>
<pre>private String getDirectionsUrl(LatLng origin, LatLng dest) {

 <strong><span style="color: #008000;">// Origin of route</span></strong>
 String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

 <strong><span style="color: #008000;">// Destination of route</span></strong>
 String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
<strong><span style="color: #008000;"> 
 // Setting mode</span></strong>
 String mode = "mode=driving";

 <strong><span style="color: #008000;">// Building the parameters to the web service</span></strong>
 String parameters = str_origin + "&;" + str_dest + "&;" + mode;

 <strong><span style="color: #008000;">// Output format</span></strong>
 String output = "json";

 <span style="color: #008000;"><strong>// Building the url to the web service</strong></span>
 String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&;key=" + "AIzaSyD_L8g3AcwXBKnEjhvLJwBXwI3L51LjQUU";

 return url;
}</pre>
<p>A Directions API request takes the following form:</p>
<pre>String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" 
+ parameters + "&;key=" + "API KEY";</pre>
<p class="p1">The output may be either of the following values <span style="color: #0000ff;"><strong>json</strong></span> or <span style="color: #0000ff;"><strong>xml</strong></span>. In my case, it holds a <span style="color: #008000;"><strong>“json”</strong></span> string and the parameter string is created as:</p>
<p class="p1"><span style="color: #008000;"><b>String parameters = str_origin + &#8220;&;&#8221; + str_dest + &#8220;&;&#8221; + mode;</b></span></p>
<p> <span style="color: #0000ff;"><strong>str_origin and str_dest</strong> </span>: The address, textual latitude/longitude value, or place ID from which you wish to calculate directions.</p>
<p class="p1">We have set the <span style="color: #008000;"><b>mode=driving</b></span> in the current application.<br />
The other modes of transport are:</p>
<ul class="ul1">
<li class="li1">driving (default)</li>
<li class="li1">walking</li>
<li class="li1">bicycling</li>
<li class="li1">transit</li>
</ul>
<p><strong><span style="color: #0000ff;">downloadUrl(): </span></strong>A method to download JSON data <span style="color: #0000ff;"><span style="color: #000000;">using </span></span><span style="color: #0000ff;"><span style="color: #000000;"><strong><span style="color: #008000;">HttpURLConnection</span></strong> </span></span>from the URL returned by <strong><span style="color: #008000;">getDirectionsUrl()</span><span style="color: #0000ff;"><span style="color: #000000;">.</span></span></strong></p>
<pre>private String downloadUrl(String strUrl) throws IOException {
 String data = "";
 InputStream iStream = null;
 HttpURLConnection urlConnection = null;
 try {
 URL url = new URL(strUrl);

 urlConnection = (HttpURLConnection) url.openConnection();

 urlConnection.connect();

 iStream = urlConnection.getInputStream();

 BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

 StringBuffer sb = new StringBuffer();

 String line = "";
 while ((line = br.readLine()) != null) {
 sb.append(line);
 }

 data = sb.toString();

 br.close();

 } catch (Exception e) {
 Log.d("Exception", e.toString());
 } finally {
 iStream.close();
 urlConnection.disconnect();
 }
 return data;
}</pre>
<p><strong><span style="color: #0000ff;">ParserTask</span></strong> : <span style="color: #008000;"><strong>ParserTask</strong></span> is a class that extends <span style="color: #008000;"><strong>AsyncTask</strong></span>. Here we will parse the JSON data returned by <strong class="gc go"><span style="color: #008000;">downloadUrl</span> </strong>method.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<pre>private class ParserTask extends AsyncTask<;String, Integer, List<;List<;HashMap<;String, String>;>;>;>; {

 <span style="color: #008000;"><strong>// Parsing the data in non-ui thread</strong></span>
 @Override
 protected List<;List<;HashMap<;String, String>;>;>; doInBackground(String... jsonData) {

 JSONObject jObject;
 List<;List<;HashMap<;String, String>;>;>; routes = null;

 try {
 jObject = new JSONObject(jsonData[0]);
 DataParser parser = new DataParser();

 routes = parser.parse(jObject);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return routes;
 }

 @Override
 protected void onPostExecute(List<;List<;HashMap<;String, String>;>;>; result) {
 ArrayList points = new ArrayList();
 PolylineOptions lineOptions = new PolylineOptions();

 for (int i = 0; i <; result.size(); i++) {

 List<;HashMap<;String, String>;>; path = result.get(i);

 for (int j = 0; j <; path.size(); j++) {
 HashMap<;String, String>; point = path.get(j);

 double lat = Double.parseDouble(point.get("lat"));
 double lng = Double.parseDouble(point.get("lng"));
 LatLng position = new LatLng(lat, lng);

 points.add(position);
 }

 lineOptions.addAll(points);
 lineOptions.width(12);
 lineOptions.color(Color.RED);
 lineOptions.geodesic(true);

 }

 <strong><span style="color: #008000;">// Drawing polyline in the Google Map </span></strong>

 if (points.size() != 0)
 mMap.addPolyline(lineOptions);
 }
 }</pre>
<p>In the <span style="color: #0000ff;"><strong class="gc go">doInBackround </strong><span style="color: #000000;">method, </span></span>we will parse the JSON data. So we are parsing the data using another class i.e <strong class="gc go"><span style="color: #008000;">DataParser</span>.</strong><br />
In the <strong class="gc go"><span style="color: #0000ff;">onPostExecute</span> </strong>method, we will add polyline to draw a route on Google Map.</p>
<p><strong><span style="color: #0000ff;">DataParser</span>: </strong>Right-click on root project directory under Java folder and create a new Java Class <span style="color: #008000;"><strong>DataParser</strong><strong>.Java </strong></span>and write the below code:</p>
<p><span style="color: #0000ff;"><strong>DataParser.Java</strong></span></p>
<pre>package com.example.mapdirectiondemo;

import com.google.android.gms.maps.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DataParser {

 <span style="color: #008000;"><strong>/**
 * Receives a JSONObject and returns a list of lists containing latitude and longitude
 */</strong></span>
 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;

 try {

 jRoutes = jObject.getJSONArray("routes");

 <strong><span style="color: #008000;">/** Traversing all routes */</span></strong>
 for (int i = 0; i <; jRoutes.length(); i++) {
 jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
 List path = new ArrayList<;HashMap<;String, String>;>;();

 <strong><span style="color: #008000;">/** Traversing all legs */</span></strong>
 for (int j = 0; j <; jLegs.length(); j++) {
 jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

 <strong><span style="color: #008000;">/** Traversing all steps */</span></strong>
 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);

 <strong><span style="color: #008000;">/** Traversing all points */</span></strong>
 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;
 }

 <strong><span style="color: #008000;">/**
 * Method to decode polyline points
 */</span></strong>
 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;
 }
}</pre>
<p class="p1"><span style="color: #0000ff;"><strong>parse()</strong></span> method will receive a <strong><span style="color: #008000;">JSONObject</span></strong> and returns a list of lists containing latitude and longitude.</p>
<p class="p1">Here we will split JSONArray by using <strong class="gc go"><span style="color: #008000;">getJSONArray</span><br />
</strong>And we will traverse all routes, legs, steps, points, etc. And then we will add all the traversing points to the list.<br />
<span style="color: #0000ff;"><strong class="gc go">routes.add(path);</strong></span></p>
<p class="p1"><strong><span style="color: #0000ff;">decodepoly()</span></strong> : Method to decode polyline points.</p>
<h3><span style="color: #000080;"><strong>Complete Code:</strong></span></h3>
<p><strong>18</strong>.Open <span style="color: #008000;"><strong>MainActivity.Java</strong></span> and write the below code:</p>
<p><span style="color: #0000ff;"><strong>MainActivity.Java</strong></span></p>
<pre>package com.example.mapdirectiondemo;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.fragment.app.FragmentActivity;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

 private GoogleMap mMap;

 MarkerOptions origin, destination;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_maps);

 <strong><span style="color: #008000;">// Obtain the SupportMapFragment and get notified when the map is ready to be used.</span></strong>
 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
 .findFragmentById(R.id.map);
 mapFragment.getMapAsync(this);

 <strong><span style="color: #008000;">//Setting marker to draw route between these two points</span></strong>
 origin = new MarkerOptions().position(new LatLng(12.9121, 77.6446)).title("HSR Layout").snippet("origin");
 destination = new MarkerOptions().position(new LatLng(12.9304, 77.6784)).title("Bellandur").snippet("destination");

 <strong><span style="color: #008000;">// Getting URL to the Google Directions API</span></strong>
 String url = getDirectionsUrl(origin.getPosition(), destination.getPosition());

 DownloadTask downloadTask = new DownloadTask();

 <strong><span style="color: #008000;">// Start downloading json data from Google Directions API</span></strong>
 downloadTask.execute(url);

 }

 @Override
 public void onMapReady(GoogleMap googleMap) {
 mMap = googleMap;
 mMap.addMarker(origin);
 mMap.addMarker(destination);
 mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin.getPosition(), 10));
 }

 private class DownloadTask extends AsyncTask<;String, Void, String>; {

 @Override
 protected String doInBackground(String... url) {

 String data = "";

 try {
 data = downloadUrl(url[0]);
 } catch (Exception e) {
 Log.d("Background Task", e.toString());
 }
 return data;
 }

 @Override
 protected void onPostExecute(String result) {
 super.onPostExecute(result);
 ParserTask parserTask = new ParserTask();
 parserTask.execute(result);
 }
 }

 <strong><span style="color: #008000;">/**
 * A class to parse the JSON format
 */</span></strong>
 private class ParserTask extends AsyncTask<;String, Integer, List<;List<;HashMap<;String, String>;>;>;>; {

 <strong><span style="color: #008000;">// Parsing the data in non-ui thread</span></strong>
 @Override
 protected List<;List<;HashMap<;String, String>;>;>; doInBackground(String... jsonData) {

 JSONObject jObject;
 List<;List<;HashMap<;String, String>;>;>; routes = null;

 try {
 jObject = new JSONObject(jsonData[0]);
 DirectionsJSONParser parser = new DirectionsJSONParser();

 routes = parser.parse(jObject);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return routes;
 }

 @Override
 protected void onPostExecute(List<;List<;HashMap<;String, String>;>;>; result) {
 ArrayList points = new ArrayList();
 PolylineOptions lineOptions = new PolylineOptions();
 
 for (int i = 0; i <; result.size(); i++) {

 List<;HashMap<;String, String>;>; path = result.get(i);

 for (int j = 0; j <; path.size(); j++) {
 HashMap<;String, String>; point = path.get(j);

 double lat = Double.parseDouble(point.get("lat"));
 double lng = Double.parseDouble(point.get("lng"));
 LatLng position = new LatLng(lat, lng);

 points.add(position);
 }

 lineOptions.addAll(points);
 lineOptions.width(12);
 lineOptions.color(Color.RED);
 lineOptions.geodesic(true);

 }

 <strong><span style="color: #008000;">// Drawing polyline in the Google Map</span> </strong>
 if (points.size() != 0)
 mMap.addPolyline(lineOptions);
 }
 }

 private String getDirectionsUrl(LatLng origin, LatLng dest) {

 <strong><span style="color: #008000;">// Origin of route</span></strong>
 String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

 <strong><span style="color: #008000;">// Destination of route</span></strong>
 String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
 
 <strong><span style="color: #008000;">//setting transportation mode</span></strong>
 String mode = "mode=driving";
 <strong><span style="color: #008000;">// Building the parameters to the web service</span></strong>
 String parameters = str_origin + "&;" + str_dest + "&;" + sensor + "&;" + mode;

 <strong><span style="color: #008000;">// Output format</span></strong>
 String output = "json";

 <strong><span style="color: #008000;">// Building the url to the web service</span></strong>
 String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&;key=" + "AIzaSyD_L8g3AcwXBKnEjhvLJwBXwI3L51LjQUU";

 return url;
 }

 <strong><span style="color: #008000;">/**
 * A method to download json data from url
 */</span></strong>
 private String downloadUrl(String strUrl) throws IOException {
 String data = "";
 InputStream iStream = null;
 HttpURLConnection urlConnection = null;
 try {
 URL url = new URL(strUrl);

 urlConnection = (HttpURLConnection) url.openConnection();

 urlConnection.connect();

 iStream = urlConnection.getInputStream();

 BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

 StringBuffer sb = new StringBuffer();

 String line = "";
 while ((line = br.readLine()) != null) {
 sb.append(line);
 }

 data = sb.toString();

 br.close();

 } catch (Exception e) {
 Log.d("Exception", e.toString());
 } finally {
 iStream.close();
 urlConnection.disconnect();
 }
 return data;
 }

}</pre>
<p>When you run your application it will look like this:</p>
<p><img class="alignnone wp-image-1313" src="https://c1ctech.com/wp-content/uploads/2019/11/Screenshot_1574166034.png" alt="Screenshot_1574166034" width="534" height="949" /></p>
<p>I hope this article will help you in understanding how to draw a route between two locations using Directions API. Thank You.</p>
<p> ;</p>
<h4></h4>


