You are on page 1of 28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

DROID MOBILE
NOW
FOOD
TRENDING:
ORDERING APP FOR RESTAURANT STUDENTS PROJECT IDEA

ANDROID

IOS (SWIFT)

STUDENT HOMEWORK HELP

TIPS

ANDROID EVENTBUS LIBRARY EXAMPLE

ANDROID STUDENT PROJECT IDEAS

APPS FROM $1

FORUM

Search the site

Home Android
Android How to draw path between 2 points on Google Map

ANDROID HOW TO DRAW


PATH BETWEEN 2 POINTS
ON GOOGLE MAP
Henry

September 25, 2016

Android

No Comments

In this
tutorial, we
are going to
learn to how
to draw path
between 2
points on

EMAIL SUBSCRIPTION
Enter your email address:

Google Map
API V2.
Drawing a
route on
android
Google Map

Subscribe
Delivered by FeedBurner

API v2 can be
challenging but in this tutorial we will see what is need to draw a
path from a user current location to a point in the map that as serves
as the user destination.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

LIKE US ON
FACEBOOK
1/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

If you have not used Android Location API before to obtain user
current location, I will suggest you read my tutorial on Android
Location Service API using Google Play Services.

Inducesmile
Megustaestapgina

Selprimerodetusamigosenindicarquele
gustaesto.

WHAT WE ARE GOING TO ACHIEVE


1. Get current user location
2. Get user destination location
3. Draw a path overlay on the map between this locations
Before we start it is important that that we understand what we are
planning to achieve in this tutorial. I have add some screen-shot
from this tutorial

APP SCREEN-SHOT

RECENT POSTS
Android Mobile Food Ordering
App For Restaurant Students
Project Idea
Exception raised during
rendering: Unable to locate
mode 0
Android EventBus Library
Example
Day 3 of the 100 Days Android
App Development Challenge
for Beginners
Day 2 of 100 Days Android
App Development Challenge
for Beginners
Day 1 of 100 Days Android
App Development Challenge
for Beginners
Welcome to 100 Days Android
App Development Challenge
for Beginners
Android Record and Upload
Video to Server Using Retrofit
2
How to Program with your
Android Phone Using Aide IDE
Environment
Android Upload Image to
Server using Retrofit 2

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

2/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

CREATE NEW ANDROID PROJECT


Lets start to soil our hands in code. Start up your IDE. For this
tutorial, I am using the following tools and environment, feel free to
use what works for you.
Windows 10
Android Studio
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

3/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

Sony Xperia
ZL
Min SDK 14
Target SDK 23
To create a
new android
application
project, follow
the steps as
stipulated
below.
Go to File menu
Click on New menu
Click on Android Application
Enter Project name: AndroidMapDrawRoute
Package: com.inducesmile.androidmapdrawroute
Select Map Activity
Name your activity: MapsActivity
Keep other default selections
Continue to click on next button until Finish button is active, then
click on Finish Button.
Since we selected the default android Map Activity template, Android
Studio will add an xml file name google_maps_api.xml. This file is
stored in the values folder inside the res folder of your android
project.
When you open the file, it contains instruction on how to obtain a
Google Map Key. Every request your application send to Google Map
Server requires a unique key that will be used to identify your
application.
Also, there is a limit to the number of request you can send in a day
if your are using the free service. Your google map kep also helps

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

4/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

Google to keep track of the number of request coming from your


app.
Copy the text for creating a Google Map Key and paste it in a web
browser and hit enter. You will see a page like this.

You can create a new project or use an existing project. Click the
continue button to proceed.
Click the Create AOI Key button that will appear in the next page to
move over to Google API Manager page.
In the Google API Manager page, click on credentials and the key link
to open the page.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

5/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

Add a name for your key.


Select Android apps to restrict all the request from android apps
Add the your application package name
You can generate a SHA-1 certificate fingerprint. You will find the
process on the page.
Click the Save button when you are done.
Finally, copy your application Google map key to the generated

google_maps_api.xml as shown.

1.
2.

<resources>
<!--

3.

TODO: Before you run your application, you need


a Google Maps API key.

4.

To get one, follow this link, follow the


directions and press "Create" at the end:

5.

https://console.developers.google.com/flows/enablea
pi?
apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDR
OID&r=57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:%3B
com.inducesmile.androidmapdrawroute
6.

You can also add your credentials to an


existing key, using this line:

7.

57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C::46;com.i
nducesmile.androidmapdrawroute
8.

Alternatively, follow the directions here:

9.

https://developers.google.com/maps/documentation/an
droid/start#get-key
10.
11.
12.
13.

14.

Once you have your key (it starts with "AIza"),


replace the "google_maps_key"
string in this file.
-->
<string name="google_maps_key"
templateMergeStrategy="preserve"
translatable="false">YOUR GOOGLE MAP API KEY
HERE</string>
</resources>

BUILD.GRADLE
In android, since we are going to make use of user location in
drawing path between two points in Google Map API, we are going to
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

6/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

use Google Play Services. Android Location Service API is part of


Google Play Services.
Since the library is too big and to avoid going beyond 64000 methods
which will force use to multiDexEnabled true in the defaultConfig, we
will use Location and Map libraries alone.
Inaddition to these libraries, we are going to make use of Volley
network library and Gson library.
Open your application build.gradle and add the code below.
1.

apply plugin: 'com.android.application'

2.

android {

3.

compileSdkVersion 24

4.

buildToolsVersion "24.0.1"

5.
6.

defaultConfig {
applicationId
"com.inducesmile.androidmapdrawroute"

7.

minSdkVersion 14

8.

targetSdkVersion 24

9.

versionCode 1
versionName "1.0"

10.
11.

12.

buildTypes {
release {

13.

minifyEnabled false

14.
15.

proguardFiles
getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}

16.

17.
18.
19.
20.

}
dependencies {
compile fileTree(dir: 'libs', include:
['*.jar'])
testCompile 'junit:junit:4.12'

21.
22.

compile 'com.android.support:appcompatv7:24.2.1'

23.

compile 'com.google.android.gms:play-servicesmaps:9.4.0'

24.

compile 'com.google.android.gms:play-serviceslocation:9.4.0'
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.mcxiaoke.volley:library:1.0.19'

25.
26.
27.

ANDROIDMANIFEST.XML
We are going to update our application androidmanifest.xml. Using
Android Location requires that our application must request for user
permission before it can access their location. Starting from android
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

7/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

6, location request are run time permission which the user will grant
or deny while using the app.
Open your AndroidManifest.xml file and add the code below.
1.

<?xml version="1.0" encoding="utf-8"?>

2.

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid"

3.

package="com.inducesmile.androidmapdrawroute">
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATI
ON" />

4.

5.

6.

<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCA
TION" />
<uses-permission
android:name="android.permission.INTERNET" />
<application

7.
8.

android:name=".network.CustomApplication"

9.
10.

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"

11.

android:label="@string/app_name"

12.

android:supportsRtl="true"

13.

android:theme="@style/AppTheme">

14.

<meta-data

15.

android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"

16.

/>
<activity

17.

android:name=".MapsActivity"

18.
19.

android:label="@string/title_activity_maps">
<intent-filter>

20.
21.

<action
android:name="android.intent.action.MAIN" />

22.

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

23.

</activity>

24.

</application>

25.
26.

</manifest>

The meta-data retrieves the Google Map Key that we obtained


before.

STRINGS.XML
We are going to update our project strings.xml file located in the
values folder inside the res folder. Open the file and add the code
below to it.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

8/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

1.

<resources>

2.

<string
name="app_name">AndroidMapDrawRoute</string>
<string name="title_activity_maps">Map</string>

3.
4.

<string name="permission_refused">Permission
was not granted</string>

5.

<string name="permission_request_title">Special
Permission Request</string>
<string name="app_permission_notice">This
permission request is very important to your app
functionality. If it is not granted your app might
not work the way it is intended</string>

6.

7.
8.
9.

<string name="failed_draw">Empty line path


return</string>
<string name="server_error">Server error.
Something when wrong with the server</string>
</resources

COLORS.XML
Open the colors.xml file in the same location as the strings.xml file
and add the code below to the file.
1.

<?xml version="1.0" encoding="utf-8"?>

2.

<resources>

3.

<color name="colorPrimary">#3F51B5</color>

4.

<color name="colorPrimaryDark">#303F9F</color>

5.
6.

<color name="colorAccent">#FF4081</color>
</resources>

ANDROID GOOGLE DIRECTION API


This android tutorial on how to draw path between two points on
Google Map API v2 is going to make use of android google direction
api.
Android Google direction API is a service that calculates directions
between locations using an HTTP request.
So we are going to get the user current location as the origin and we
will implement onMapClickListener which will mark the user
destination.
Thereafter, we will use the Android Google Direction API to calculate
the direction between the two locations. The Android Polyline is used
to draw an overlay line between the two directions.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

9/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

Lets move on to create a layout interface file

ACTIVITY_MAPS.XML
The Map Activity uses Fragment with
android:name=com.google.android.gms.maps.SupportMapFragment.
The complete code for the layout file is as shown.
1.

<fragment
xmlns:android="http://schemas.android.com/apk/res/a
ndroid"

2.

xmlns:map="http://schemas.android.com/apk/resauto"

3.

xmlns:tools="http://schemas.android.com/tools"

4.

android:id="@+id/map"

5.

android:name="com.google.android.gms.maps.SupportMa
pFragment"
6.

android:layout_width="match_parent"

7.

android:layout_height="match_parent"

8.

tools:context="com.inducesmile.androidmapdrawroute.
MapsActivity" />

MAPSACTIVITY CLASS
In the MapsActivity class, the Android Google Map is setup my
Android Studio. We need to add some interfaces that the class will
implement.
GoogleMap.OnMapClickListener it listens to Map event click
GoogleApiClient.ConnectionCallbacks Connection callback for
GoogleApiClient
In the onConnected() callback method, we will get the user current
location and save it in a List object.
When a user click on a destination location on the Map, it will get the
location and store it on a List object.
We check if there is more that one location object then we will clear
the list and add the present destination location in it.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

10/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

When the two locations are obtained, we will use Volley to make a
request to Google Direction API.
The complete code for the MapsActivity class is as shown.
1.

import android.Manifest;

2.

import android.content.DialogInterface;

3.
4.

import android.content.pm.PackageManager;
import android.graphics.Color;

5.

import android.location.Location;

6.

import android.os.Bundle;

7.

import android.support.annotation.NonNull;

8.

import android.support.annotation.Nullable;

9.
10.

import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

11.

import android.support.v7.app.AlertDialog;

12.

import android.util.Log;

13.

import android.widget.Toast;

14.
15.

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;

16.

import com.android.volley.Response;

17.

import com.android.volley.VolleyError;

18.

import
com.google.android.gms.common.api.GoogleApiClient;
import
com.google.android.gms.common.api.PendingResult;

19.
20.

import
com.google.android.gms.common.api.ResultCallback;

21.

import com.google.android.gms.common.api.Status;
import
com.google.android.gms.location.LocationRequest;

22.
23.
24.

25.

26.

27.
28.
29.
30.
31.
32.
33.
34.
35.

import
com.google.android.gms.location.LocationServices;
import
com.google.android.gms.location.LocationSettingsReq
uest;
import
com.google.android.gms.location.LocationSettingsRes
ult;
import
com.google.android.gms.location.LocationSettingsSta
tusCodes;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import
com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import
com.google.android.gms.maps.model.PolylineOptions;

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

11/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

36.

37.

import
com.inducesmile.androidmapdrawroute.entityObjects.D
irectionObject;
import
com.inducesmile.androidmapdrawroute.entityObjects.L
egsObject;

38.
import
Contactmeforcodeservices

com.inducesmile.androidmapdrawroute.entityObjects.P
olylineObject;
39.

40.

41.

42.

43.
44.

import
com.inducesmile.androidmapdrawroute.entityObjects.R
outeObject;
import
com.inducesmile.androidmapdrawroute.entityObjects.S
tepsObject;
import
com.inducesmile.androidmapdrawroute.network.GsonReq
uest;
import
com.inducesmile.androidmapdrawroute.network.VolleyS
ingleton;
import java.util.ArrayList;
import java.util.List;

45.

public class MapsActivity extends FragmentActivity


implements OnMapReadyCallback,
GoogleMap.OnMapClickListener,
GoogleApiClient.ConnectionCallbacks {

46.

private static final String TAG =


MapsActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;

47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.

private LocationRequest mLocationRequest;


private double latitudeValue = 0.0;
private double longitudeValue = 0.0;
private GoogleMap mMap;
private static final int
PERMISSION_LOCATION_REQUEST_CODE = 100;
private List<LatLng> latLngList;
private MarkerOptions yourLocationMarker;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
latLngList = new ArrayList<LatLng>();
if (mGoogleApiClient == null) {
mGoogleApiClient = new
GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();

64.
65.
66.
67.
68.

69.
70.
71.

}
mLocationRequest = createLocationRequest();
SupportMapFragment mapFragment =
(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.m
ap);
mapFragment.getMapAsync(this);
}
@Override

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

12/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

72.
73.

public void onMapReady(GoogleMap googleMap) {


mMap = googleMap;
mMap.setOnMapClickListener(this);

74.
75.

@Override
public void onMapClick(LatLng latLng) {
Contactmeforcodeservices
78.
if(latLngList.size() > 0){
76.
77.
79.
80.
81.
82.
83.
84.
85.

refreshMap(mMap);
latLngList.clear();
}
latLngList.add(latLng);
Log.d(TAG, "Marker number " +
latLngList.size());
mMap.addMarker(yourLocationMarker);
mMap.addMarker(new
MarkerOptions().position(latLng));

86.

LatLng defaultLocation =
yourLocationMarker.getPosition();

87.

LatLng destinationLocation = latLng;


//use Google Direction API to get the route
between these Locations

88.
89.

String directionApiPath =
Helper.getUrl(String.valueOf(defaultLocation.latitu
de), String.valueOf(defaultLocation.longitude),

90.

91.

String.valueOf(destinationLocation.latitude),
String.valueOf(destinationLocation.longitude));
Log.d(TAG, "Path " + directionApiPath);

92.

getDirectionFromDirectionApiServer(directionApiPath
);
93.
94.
95.
96.

97.

98.
99.
100.
101.
102.
103.
104.

}
@Override
public void onConnected(@Nullable Bundle
bundle) {
LocationSettingsRequest.Builder builder =
new
LocationSettingsRequest.Builder().addLocationReques
t(mLocationRequest);
PendingResult<LocationSettingsResult>
result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient, builder.build());
result.setResultCallback(new
ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull
LocationSettingsResult result) {
final Status status =
result.getStatus();
switch (status.getStatusCode()) {
case
LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection
method has been called");

105.

if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED

106.

&&
ActivityCompat.checkSelfPermission(getApplicationCo

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

13/28

9/12/2016

107.

AndroidHowtodrawpathbetween2pointsonGoogleMap

ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);

108.
Contactmeforcodeservices

assignLocationValues(mLastLocation);

109.

110.

setDefaultMarkerOption(new
LatLng(mLastLocation.getLatitude(),
mLastLocation.getLongitude()));
}else{

111.

ActivityCompat.requestPermissions(MapsActivity.this
, new String[]
{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_LOCATION_REQUEST_CODE);
112.
113.
114.

}
break;
case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAIL
ABLE:
break;

115.

116.

117.

});

118.
119.

120.

@Override
public void onConnectionSuspended(int i) {
}

121.
122.
123.
124.

125.

@Override
public void onRequestPermissionsResult(int
requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_LOCATION_REQUEST_CODE:

126.

{
127.

// If request is cancelled, the


result arrays are empty.

128.

if (grantResults[0] ==
PackageManager.PERMISSION_DENIED) {

129.

// permission was denied, show


alert to explain permission
showPermissionAlert();

130.
131.
132.
133.

134.

135.

}else{
//permission is granted now
start a background service
if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getApplicationCo
ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

14/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

136.
137.

138.

assignLocationValues(mLastLocation);
setDefaultMarkerOption(new
LatLng(mLastLocation.getLatitude(),
mLastLocation.getLongitude()));
}

Contactmeforcodeservices
139.
}
141.
142.
143.
144.
145.

140.

}
}
private void assignLocationValues(Location
currentLocation){
if (currentLocation != null) {
latitudeValue =
currentLocation.getLatitude();

146.

longitudeValue =
currentLocation.getLongitude();

147.

Log.d(TAG, "Latitude: " + latitudeValue


+ " Longitude: " + longitudeValue);
markStartingLocationOnMap(mMap, new
LatLng(latitudeValue, longitudeValue));
addCameraToMap(new
LatLng(latitudeValue, longitudeValue));

148.
149.

150.
151.
152.
153.
154.
155.
156.

}
private void addCameraToMap(LatLng latLng){
CameraPosition cameraPosition = new
CameraPosition.Builder()
.target(latLng)
.zoom(16)
.build();

157.

mMap.animateCamera(CameraUpdateFactory.newCameraPos
ition(cameraPosition));
158.
159.
160.

}
private void showPermissionAlert(){
AlertDialog.Builder builder = new
AlertDialog.Builder(this);

161.

builder.setTitle(R.string.permission_request_title)
;
162.
163.
164.
165.
166.
167.

168.

builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface
dialog, int which) {
if
(ActivityCompat.checkSelfPermission(MapsActivity.th
is, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(MapsActivity.thi
s, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

169.

ActivityCompat.requestPermissions(MapsActivity.this
, new String[]
{Manifest.permission.ACCESS_COARSE_LOCATION,
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

15/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

170.

Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_LOCATION_REQUEST_CODE);
}
}

171.

});

172.
173.

builder.setNegativeButton("Cancel", new
{
@Override
public void onClick(DialogInterface
dialog, int which) {

Contactmeforcodeservices
DialogInterface.OnClickListener()

174.
175.
176.

177.
178.

Toast.makeText(MapsActivity.this,
R.string.permission_refused,
Toast.LENGTH_LONG).show();
}
});
builder.show();

179.
180.

181.

private void
markStartingLocationOnMap(GoogleMap mapObject,
LatLng location){

182.

mapObject.addMarker(new
MarkerOptions().position(location).title("Current
location"));

183.

184.
185.
186.
187.
188.
189.

mapObject.moveCamera(CameraUpdateFactory.newLatLng(
location));
}
private void refreshMap(GoogleMap mapInstance){
mapInstance.clear();
}
protected LocationRequest
createLocationRequest() {
LocationRequest mLocationRequest = new
LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);

190.
191.
192.

mLocationRequest.setPriority(LocationRequest.PRIORI
TY_HIGH_ACCURACY);
193.
194.
195.
196.
197.
198.

return mLocationRequest;
}
private void setDefaultMarkerOption(LatLng
location){
if(yourLocationMarker == null){
yourLocationMarker = new
MarkerOptions();
}
yourLocationMarker.position(location);

199.
200.

201.

@Override
protected void onStart() {
mGoogleApiClient.connect();

202.
203.

super.onStart();

204.
205.

206.

@Override
protected void onStop() {
mGoogleApiClient.disconnect();

207.
208.

super.onStop();

209.
210.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

16/28

9/12/2016

211.
212.
213.

AndroidHowtodrawpathbetween2pointsonGoogleMap

private void
getDirectionFromDirectionApiServer(String url){
GsonRequest<DirectionObject> serverRequest
= new GsonRequest<DirectionObject>(
Request.Method.GET,
url,

214.

Contactmeforcodeservices

215.
DirectionObject.class,
216.
217.
218.

createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new
DefaultRetryPolicy(
Helper.MY_SOCKET_TIMEOUT_MS,

219.
220.

DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
221.

DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
222.

223.
224.
225.
226.

VolleySingleton.getInstance(getApplicationContext()
).addToRequestQueue(serverRequest);
}
private Response.Listener<DirectionObject>
createRequestSuccessListener() {
return new
Response.Listener<DirectionObject>() {
@Override
public void onResponse(DirectionObject

227.

response) {
228.
229.

try {
Log.d("JSON Response",
response.toString());

230.

if(response.getStatus().equals("OK")){
231.
232.

List<LatLng> mDirections =
getDirectionPolylines(response.getRoutes());
drawRouteOnMap(mMap,
mDirections);
}else{

233.
234.

235.

Toast.makeText(MapsActivity.this,
R.string.server_error, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}

236.
237.
238.

};

239.
240.
241.
242.
243.
244.
245.
246.

};
}
private List<LatLng>
getDirectionPolylines(List<RouteObject> routes){
List<LatLng> directionList = new
ArrayList<LatLng>();
for(RouteObject route : routes){
List<LegsObject> legs =
route.getLegs();
for(LegsObject leg : legs){
List<StepsObject> steps =

247.

leg.getSteps();
248.
249.

for(StepsObject step : steps){


PolylineObject polyline =
step.getPolyline();

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

17/28

9/12/2016

250.
251.
252.

AndroidHowtodrawpathbetween2pointsonGoogleMap

String points =
polyline.getPoints();
List<LatLng> singlePolyline =
decodePoly(points);
for (LatLng direction :
singlePolyline){

Contactmeforcodeservices
253.
254.
255.

directionList.add(direction);
}
}
}

256.
257.

258.

return directionList;

259.
260.

}
private Response.ErrorListener
createRequestErrorListener() {
return new Response.ErrorListener() {
@Override

261.
262.

public void onErrorResponse(VolleyError

263.

error) {
error.printStackTrace();

264.

265.

};

266.

267.
268.

private void drawRouteOnMap(GoogleMap map,


List<LatLng> positions){

269.

PolylineOptions options = new


PolylineOptions().width(5).color(Color.BLUE).geodes
ic(true);
options.addAll(positions);
Polyline polyline =
map.addPolyline(options);

270.
271.
272.
273.

274.

CameraPosition cameraPosition = new


CameraPosition.Builder()
.target(new
LatLng(positions.get(1).latitude,
positions.get(1).longitude))
.zoom(17)
.build();

275.
276.

277.

map.animateCamera(CameraUpdateFactory.newCameraPosi
tion(cameraPosition));
}
/**
* Method to decode polyline points

278.
279.
280.

* Courtesy :
http://jeffreysambells.com/2010/05/27/decodingpolylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded)

281.
282.

{
283.
284.
285.
286.
287.
288.

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


int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {

290.

b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;

291.

shift += 5;

289.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

18/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

292.
293.
294.

} while (b >= 0x20);


int dlat = ((result & 1) != 0 ? ~
(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;

295.
296.

Contactmeforcodeservices

do {

297.

b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;

298.
299.

shift += 5;
} while (b >= 0x20);

300.
301.
302.
303.
304.

int dlng = ((result & 1) != 0 ? ~


(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat /
1E5)),
(((double) lng / 1E5)));
poly.add(p);

305.
306.

}
return poly;

307.
308.

309.
310.

RETURNED JSON RESPONSE OBJECT


FROM GOOGLE DIRECTION API
The returned response object is a Json object and the direction path
is stored in the Polyline class. This is the class structure of the Json
response object. We are going to use the Gson library to convert it to
plain Java object class.
1.
2.
3.

{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",

4.
5.
6.
7.
8.

"place_id" :
"ChIJZymwbofzU0YRvgugqrVwH8Q",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",

9.
10.

"place_id" :
"EiJOeWdhdGFuIDMyLCAyNDIgMzEgSMO2cmJ5LCBTdmVyaWdl",
"types" : [ "street_address" ]

11.
12.
13.
14.
15.
16.
17.

}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 55.8541564,
"lng" : 13.661235

18.
19.
20.

},

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

19/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

23.

"southwest" : {
"lat" : 55.85187149999999,
"lng" : 13.660381

24.

21.
22.

25.

},

26.

"copyrights" : "Map data 2016 Google",

Contactmeforcodeservices

27.
"legs" : [
28.
29.
30.

{
"distance" : {
"text" : "0.3 km",
"value" : 260

31.
32.

},

33.

"duration" : {
"text" : "1 min",
"value" : 84

34.
35.
36.
37.
38.

},
"end_address" : "Nygatan 32, 242 31
Hrby, Sweden",
"end_location" : {
"lat" : 55.85187149999999,
"lng" : 13.660381

39.
40.
41.
42.
43.

},
"start_address" : "Nygatan 12B, 242
31 Hrby, Sweden",
"start_location" : {
"lat" : 55.8541564,
"lng" : 13.661235

44.
45.
46.
47.
48.

},
"steps" : [
{
"distance" : {
"text" : "0.3 km",

49.
50.

"value" : 260

51.

},
"duration" : {

52.
53.

"text" : "1 min",


"value" : 84

54.
55.

},
"end_location" : {
"lat" : 55.85187149999999,

56.
57.
58.

"lng" : 13.660381

59.

},

60.
61.

"html_instructions" : "Head
\u003cb\u003esouth\u003c/b\u003e on
\u003cb\u003eNygatan\u003c/b\u003e toward
\u003cb\u003eKvarngatan\u003c/b\u003e\u003cdiv
style=\"font-size:0.9em\"\u003eDestination will be
on the left\u003c/div\u003e",

62.

"polyline" : {
"points" :
"o_|sIwekrAVHxBj@|Bh@nBr@d@Hb@L"
},

63.
64.

"start_location" : {
"lat" : 55.8541564,

65.
66.

"lng" : 13.661235
},
"travel_mode" : "DRIVING"

67.
68.
69.

70.
71.

],

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

20/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

"traffic_speed_entry" : [],
"via_waypoint" : []

72.
73.

74.

],
"overview_polyline" : {

75.
76.

"points" : "o_|sIwekrApCt@|Bh@nBr@hAV"

77.

Contactmeforcodeservices
78.
},
79.

"summary" : "Nygatan",

80.

"warnings" : [],
"waypoint_order" : []

81.

}
],
"status" : "OK"

82.
83.
84.
85.

ENTITYOBJECT CLASSES
We will create the following classes to mimic the structure of the Json
response object. The classes are

DIRECTIONOBJECT.JAVA
1.
2.
3.
4.
5.

import java.util.List;
public class DirectionObject {
private List<RouteObject> routes;
private String status;
public DirectionObject(List<RouteObject>
routes, String status) {
this.routes = routes;
this.status = status;

6.
7.
8.

9.

public List<RouteObject> getRoutes() {


return routes;

10.

}
public String getStatus() {
return status;

11.
12.
13.

14.
15.

LEGSOBJECT.JAVA
1.
2.

import java.util.List;
public class LegsObject {

3.

private List<StepsObject> steps;

4.
5.

public LegsObject(List<StepsObject> steps) {


this.steps = steps;

6.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

21/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

public List<StepsObject> getSteps() {


return steps;

7.
8.

9.
10.

Contactmeforcodeservices

POLYLINEOBJECT.JAVA
1.

public class PolylineObject {

2.

private String points;

3.

public PolylineObject(String points) {


this.points = points;

4.
5.

6.

public String getPoints() {


return points;

7.

8.
9.

ROUTEOBJECT.JAVA
1.
2.

import java.util.List;
public class RouteObject {

3.

private List<LegsObject> legs;

4.
5.

public RouteObject(List<LegsObject> legs) {


this.legs = legs;

6.

7.
8.

public List<LegsObject> getLegs() {


return legs;

9.

10.

STEPSOBJECTS.JAVA
1.

public class StepsObject {

2.

private PolylineObject polyline;

3.
4.

public StepsObject(PolylineObject polyline) {


this.polyline = polyline;

5.

6.

public PolylineObject getPolyline() {


return polyline;

7.

8.
9.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

22/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

USING ANDROID VOLLEY FOR


NETWORK CALL
We are going to extends the Application class. Create a java class and

Contactmeforcodeservices
name
it CustomApplication.java.

We will create an instance of our Volley object in the class. By using a


custom application class, we can access the Volley object anywhere
in our application.
Add the following code to the class
1.

import android.app.Application;

2.

import com.android.volley.RequestQueue;
public class CustomApplication extends Application{

3.
4.

private RequestQueue requestQueue;

5.

@Override
public void onCreate() {

6.

super.onCreate();

7.
8.

9.

requestQueue =
VolleySingleton.getInstance(getApplicationContext()
).getRequestQueue();
}
public RequestQueue getVolleyRequestQueue(){

10.

return requestQueue;

11.

12.
13.

GSONREQUEST.JAVA
Create a java file and name it GsonRequest.java. Open the file and
add the code below to it.
1.

import com.android.volley.AuthFailureError;

2.

import com.android.volley.NetworkResponse;

3.
4.

import com.android.volley.ParseError;
import com.android.volley.Request;

5.

import com.android.volley.Response;

6.

import com.android.volley.toolbox.HttpHeaderParser;

7.
8.

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

9.

import java.io.UnsupportedEncodingException;

10.
11.

import java.util.Map;
public class GsonRequest<T> extends Request<T> {

12.

// create variables

13.
14.

private Gson mGson = new Gson();


private Class<T> tClass;

15.

private Map<String, String> headers;

16.

private Map<String, String> params;

17.

private Response.Listener<T> listener;

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

23/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

18.

19.

public GsonRequest(int method, String url,


Class<T> tClass, Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);

20.

this.tClass = tClass;

21.

this.listener = listener;

Contactmeforcodeservices

22.
mGson = new Gson();
}

23.
24.

25.

public GsonRequest(int method, String url,


Class<T> tClass, Map<String, String> params,
Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);

26.

this.tClass = tClass;

27.

this.params = params;

28.

this.listener = listener;
this.headers = null;

29.

mGson = new Gson();

30.

}
@Override

31.
32.
33.

public Map<String, String> getHeaders() throws


AuthFailureError {

34.

return headers != null ? headers :


super.getHeaders();
}

35.

@Override

36.
37.
38.

protected Map<String, String> getParams()


throws AuthFailureError {
return params;

39.

40.

protected void deliverResponse(T response) {


listener.onResponse(response);

41.
42.

43.

@Override

44.
45.

protected Response<T>
parseNetworkResponse(NetworkResponse response) {
try {

46.

String json = new String(response.data,


HttpHeaderParser.parseCharset(response.headers));

47.

return
Response.success(mGson.fromJson(json, tClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {

48.
49.

return Response.error(new
ParseError(e));

50.

} catch (JsonSyntaxException e) {
return Response.error(new
ParseError(e));

51.

52.

53.
54.

VOLLEYSINGLETON.JAVA
Create a new Java class and name it VolleySingleton.java. Open the
file and add the code below to it.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

24/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

1.

import android.content.Context;

2.

import android.graphics.Bitmap;

3.

import android.util.LruCache;

4.

import com.android.volley.Request;

5.
import com.android.volley.RequestQueue;
Contactmeforcodeservices

6.

import com.android.volley.toolbox.ImageLoader;

7.

import com.android.volley.toolbox.Volley;
public class VolleySingleton {

8.

private static VolleySingleton mInstance;

9.
10.

private RequestQueue mRequestQueue;

11.
12.

private ImageLoader mImageLoader;


private static Context mCtx;

13.

private VolleySingleton(Context context) {

14.

mCtx = context;
mRequestQueue = getRequestQueue();

15.
16.

mImageLoader = new
ImageLoader(mRequestQueue, new
ImageLoader.ImageCache() {

17.

private final LruCache<String, Bitmap>


cache = new LruCache<String, Bitmap>(20);
@Override

18.

public Bitmap getBitmap(String url) {

19.

return cache.get(url);

20.
21.

22.

@Override

23.
24.

public void putBitmap(String url,


Bitmap bitmap) {
cache.put(url, bitmap);
}

25.

});

26.
27.
28.

}
public static synchronized VolleySingleton
getInstance(Context context) {
if (mInstance == null) {

29.
30.
31.

mInstance = new
VolleySingleton(context);
}
return mInstance;

32.

}
public RequestQueue getRequestQueue() {

33.
34.

if (mRequestQueue == null) {

35.
36.

37.

mRequestQueue =
Volley.newRequestQueue(mCtx.getApplicationContext()
);
}
return mRequestQueue;

38.

39.
40.
41.

public <T> void addToRequestQueue(Request<T>


req) {
getRequestQueue().add(req);

42.

43.
44.

public ImageLoader getImageLoader() {


return mImageLoader;

45.

46.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

25/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

HELPER.JAVA
We will create a new Java file and we will name it Helper.java. Open
the file and add the code below.

Contactmeforcodeservices
2.

import android.content.Context;
import android.net.ConnectivityManager;

3.

import android.net.NetworkInfo;

4.

public class Helper {

5.

private static final String DIRECTION_API =


"https://maps.googleapis.com/maps/api/directions/js
on?origin=";

6.

public static final String API_KEY =


"AIzaSyCuZCfoPPUV1upJT10kJbCbV71LUqwhFCM";

7.

public static final int MY_SOCKET_TIMEOUT_MS =


5000;
public static String getUrl(String originLat,
String originLon, String destinationLat, String
destinationLon){

1.

8.

9.

10.
11.

return Helper.DIRECTION_API +
originLat+","+originLon+"&destination="+destination
Lat+","+destinationLon+"&key="+API_KEY;
}
public static boolean
isNetworkAvailable(Context context) {

12.

ConnectivityManager connectivityManager =
(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVI
CE);

13.

NetworkInfo activeNetworkInfo =
connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null &&
activeNetworkInfo.isConnected();

14.

15.
16.

This brings us to the end of this tutorial. I hope that you have learn
something. Run your app and see for yourself.
You can download the code for this tutorial below. If you are having
hard time downloading the tutorial, kindly contact me.
Remember to subscribe with your email address to be among the
first to receive my new android blog post once it is published.

OTHER INTERESTING POSTS:

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

26/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

Android Fake Call


Application Tutorial

Android GridView Vs
GridLayout Example
Tutorial

Contactmeforcodeservices

How to combine Android


Navigation Drawer and
Master Detail flow in
Android

Android Age Calculator


Application Example

Android Firebase Cloud


Messaging (Push
Notification) with Server
Admin in Php and MYSQL
database

Android Food Recipe App


with Php and Mysql
Backend

Tags: Android - How to draw path between 2 points on Google Map,


Draw Route on Map in Android, Google Maps Draw Route between
two points using Google, How to draw road directions between two
geocodes in android google

ABOUT THE AUTHOR


Henry
I like Java. I breath Android and iOS. I love Yii
and Javascript

ADD A COMMENT
You must be logged in to post a comment.

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

27/28

9/12/2016

AndroidHowtodrawpathbetween2pointsonGoogleMap

INDUCESMILE ANDROID TUTORIAL, ANDROID APPS, ANDROID STUDIO, ANDROID SDK, ANDROID
DEVELOPMENT COPYRIGHT 2016.
ANDROID STUDENT ASSIGNMENT HELP

ANDROID TUTORIALS

BUY APPS FROM $1

ASK QUESTIONS
CONTACT US
Contactmeforcodeservices

https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/

28/28

You might also like