Você está na página 1de 28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

RANT STUDENTS
NOW TRENDING:
PROJECT IDEA

ANDROID

ANDROID EVENTBUS LIBRARY EXAMPLE

IOS (SWIFT)

STUDENT HOMEWORK HELP

TIPS

WELCOME TO 100 DAYS ANDROID APP DEVELOPMENT CHA

ANDROID STUDENT PROJECT IDEAS

APPS FROM $1

FORUM

Search the site

Home Android
Android find distance and duration between two points on Google
Map

ANDROID FIND DISTANCE


AND DURATION BETWEEN
TWO POINTS ON GOOGLE
MAP
Henry

September 25, 2016

Android

7 Comments

In this
tutorial, we
are going to
learn how to

EMAIL SUBSCRIPTION
Enter your email address:

find the
distance and
duration
between two
points on
Google Map

Subscribe
Delivered by FeedBurner

API v2. There


are situations
were you
might want

LIKE US ON
FACEBOOK

your app to measure the distance and duration between two points
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

1/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

on a Map, this can give an insight of how long the distance is and the
time it will take to accomplish the journey.

Inducesmile
Megustaestapgina

Major part of this android tutorial on finding distance and duration


between two points on a Map is adopted from my tutorial on How to
draw path between two points on a Map. If you have not read the

Selprimerodetusamigosenindicarquele
gustaesto.

tutorial, I will suggest you read it first.

WHAT WE ARE GOING TO ACHIEVE


1. We are going to implement a Map

RECENT POSTS
Android Mobile Food Ordering
App For Restaurant Students
Project Idea

duration

Exception raised during


rendering: Unable to locate
mode 0

3. We draw a path between the two points and calculate the distance

Android EventBus Library


Example

2. Select two points on the Map we want find their distance and

and duration between them


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 SCREENSHOT

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/androidfinddistanceanddurationbetweentwopointsonandroidmap/

2/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

Contactmeforcodeservices

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/androidfinddistanceanddurationbetweentwopointsonandroidmap/

3/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

Sony Xperia
ZL
Min SDK 14
Target
SDK 23
Contactmeforcodeservices

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: AndroidMapRouteDistance
Package: com.inducesmile.androidmaproutedistance
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/androidfinddistanceanddurationbetweentwopointsonandroidmap/

4/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

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


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

Contactmeforcodeservices

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/androidfinddistanceanddurationbetweentwopointsonandroidmap/

5/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

Add a name for your key.


Select Android apps to restrict all the request from android apps
Add the your application package name

Contactmeforcodeservices
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/androidfinddistanceanddurationbetweentwopointsonandroidmap/

6/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

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

Contactmeforcodeservices
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.We are
going to add some user permissions.Open your
AndroidManifest.xml file and add the code below.
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

7/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

1.

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

2.

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

3.

package="com.inducesmile.androidmaproutedistance">
Contactmeforcodeservices

4.
5.

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATI
ON" />

6.

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

7.

<application

8.

android:name=".network.CustomApplication"

9.
10.

android:allowBackup="true"

11.

android:icon="@mipmap/ic_launcher"

12.

android:label="@string/app_name"

13.

android:supportsRtl="true"
android:theme="@style/AppTheme">

14.
15.

<meta-data

16.
17.
18.

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

19.

<activity

20.

android:name=".MapsActivity"

21.
22.

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

23.
24.

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

25.
26.

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

27.

</activity>

28.

</application>

29.
30.
31.

</manifest>

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.
1.

<resources>

2.

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

3.

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

8/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

<string name="route_distance">Distance</string>

4.
5.

<string name="route_distance_value">40.2
Km</string>
<string name="route_duration">Duration</string>

6.

<string name="route_duration_value">48
mins</string>
8.
<string name="server_error">Server error.
Contactmeforcodeservices
the server</string>
Something when wrong with
7.

9.

</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.

<color name="colorAccent">#FF4081</color>
<color name="colorPrimaryText">#000000</color>

6.
7.

<color
name="colorSecondaryText">#737373</color>

8.

<color name="colorIcons">#FFFFFF</color>

9.

<color name="colorDivider">#737373</color>

10.
11.

<color name="colorMap">#FAE6D6</color>
</resources>

ANDROID GOOGLE DIRECTION API


This android tutorial on how tofind distance and duration 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.
Lets move on to create a layout interface file
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

9/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

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

<LinearLayout
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.
5.

android:layout_height="match_parent"
android:orientation="vertical"

6.

android:layout_width="match_parent">

7.
8.
9.

<LinearLayout
android:layout_width="match_parent"

11.

android:layout_height="0dp"
android:orientation="horizontal"

12.

android:background="@color/colorMap"

13.

android:layout_weight="2">

10.

14.
15.
16.

<LinearLayout
android:layout_width="match_parent"

17.

android:layout_height="match_parent"

18.

android:orientation="horizontal">

19.
20.
21.

<LinearLayout
android:layout_width="0dp"

22.

android:layout_height="match_parent"
23.

android:layout_weight="1"

24.

android:gravity="center"

25.

android:orientation="vertical">

26.
27.

<TextView

28.

android:layout_width="wrap_content"
29.

android:layout_height="wrap_content"
30.

android:textStyle="bold"

31.

android:textSize="24sp"

32.

android:textColor="@color/colorPrimaryText"
33.

android:text="@string/route_distance"/>
34.
35.

<TextView

36.

android:id="@+id/distance_value"
37.

android:layout_width="wrap_content"
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

10/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

38.

android:layout_height="wrap_content"
39.

android:textSize="16sp"

40.

android:layout_marginTop="4dp"

41.

android:textColor="@color/colorAccent"
42.

Contactmeforcodeservices

android:text="@string/route_distance_value"/>
43.
44.

</LinearLayout>

45.
46.
47.

<View
android:layout_width="1dp"

48.

android:layout_height="match_parent"
49.

android:background="@color/colorDivider"
50.

android:layout_margin="4dp"/>

51.
52.
53.

<LinearLayout
android:layout_width="0dp"

54.

android:layout_height="match_parent"
55.

android:layout_weight="1"

56.

android:gravity="center"

57.

android:orientation="vertical">

58.
59.

<TextView

60.

android:layout_width="wrap_content"
61.
62.

android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="24sp"

63.
64.

android:textColor="@color/colorPrimaryText"
65.

android:text="@string/route_duration"/>
66.
67.

<TextView

68.

android:id="@+id/duration_value"
69.

android:layout_width="wrap_content"
70.
71.

android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="4dp"

72.
73.

android:textColor="@color/colorAccent"
74.

android:text="@string/route_duration_value"/>
75.
76.

</LinearLayout>

77.
78.

</LinearLayout>

79.
80.

</LinearLayout>

81.
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

11/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

<LinearLayout
android:layout_width="match_parent"

82.
83.
85.

android:layout_height="0dp"
android:orientation="vertical"

86.

android:layout_weight="8">

84.

87.
88.
<fragment
Contactmeforcodeservices

android:id="@+id/map"

89.
90.

android:name="com.google.android.gms.maps.SupportMa
pFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"

91.
92.
93.

tools:context="com.inducesmile.androidmaproutedista
nce.MapsActivity" />
94.

</LinearLayout>

95.
96.
97.

</LinearLayout>

MAPSACTIVITY CLASS
In the MapsActivity class, the Android Google Map is setup my
Android Studio. We need to add an interface that the class will
implement.
GoogleMap.OnMapClickListener it listens to Map event click
When the Map is load, the click event listener is attached to the Map
View. Users can select a location of interest on the Map by clicking on
the location. Once clicked a marker will appear there to let you know
the location you have selected.
The selected location is added to a List Object, once a user has
selected two different location, we will draw a path to between the
two location points and calculate the distance and duration between
the location.
Open the MapsActivity class and add the code below to the class.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

12/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

11.
12.

import com.android.volley.VolleyError;
import
com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;
import
com.google.android.gms.maps.OnMapReadyCallback;
15.
import
Contactmeforcodeservices

com.google.android.gms.maps.SupportMapFragment;
13.
14.

16.

17.
18.
19.
20.
21.
22.

23.

24.

import
com.google.android.gms.maps.model.BitmapDescriptorF
actory;
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;
import
com.inducesmile.androidmaproutedistance.entityObjec
ts.DirectionObject;
import
com.inducesmile.androidmaproutedistance.entityObjec
ts.LegsObject;
import
com.inducesmile.androidmaproutedistance.entityObjec
ts.PolylineObject;

25.

import
com.inducesmile.androidmaproutedistance.entityObjec
ts.RouteObject;

26.

import
com.inducesmile.androidmaproutedistance.entityObjec
ts.StepsObject;
import
com.inducesmile.androidmaproutedistance.network.Gso
nRequest;
import
com.inducesmile.androidmaproutedistance.network.Vol
leySingleton;
import java.util.ArrayList;

27.

28.

29.
30.
31.

32.
33.
34.
35.
36.
37.
38.
39.
40.

import java.util.List;
public class MapsActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleMap.OnMapClickListener {
private static final String TAG =
MapsActivity.class.getSimpleName();
private GoogleMap mMap;
private List<LatLng> latLngList;
private TextView distanceValue;
private TextView durationValue;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

41.

42.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTA
TION_PORTRAIT);
distanceValue =
(TextView)findViewById(R.id.distance_value);

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

13/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

43.
44.
45.

durationValue =
(TextView)findViewById(R.id.duration_value);
latLngList = new ArrayList<LatLng>();
SupportMapFragment mapFragment =
(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.m
ap);

Contactmeforcodeservices

46.
mapFragment.getMapAsync(this);
47.

48.

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

49.
50.

mMap.setOnMapClickListener(this);

51.
52.

53.

@Override
public void onMapClick(LatLng latLng) {
if(latLngList.size() > 1){

54.
55.

refreshMap(mMap);
latLngList.clear();

56.
57.

distanceValue.setText("");
durationValue.setText("");

58.
59.
60.
61.
62.

}
latLngList.add(latLng);
Log.d(TAG, "Marker number " +
latLngList.size());
createMarker(latLng, latLngList.size());
if(latLngList.size() == 2){
LatLng origin = latLngList.get(0);

63.
64.
65.
66.
67.
68.

LatLng destination = latLngList.get(1);


//use Google Direction API to get the
route between these Locations
String directionApiPath =
Helper.getUrl(String.valueOf(origin.latitude),
String.valueOf(origin.longitude),

69.

70.

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

71.

getDirectionFromDirectionApiServer(directionApiPath
);
}

72.
73.
74.

}
private void refreshMap(GoogleMap mapInstance){
mapInstance.clear();

75.
76.
77.
78.
79.

}
private void createMarker(LatLng latLng, int
position){
MarkerOptions mOptions = new
MarkerOptions().position(latLng);
if(position == 1){

80.

81.

mOptions.icon(BitmapDescriptorFactory.defaultMarker
(BitmapDescriptorFactory.HUE_YELLOW));
}else{

82.

mOptions.icon(BitmapDescriptorFactory.defaultMarker
(BitmapDescriptorFactory.HUE_RED));
83.
84.

}
addCameraToMap(latLng);

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

14/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

mMap.addMarker(mOptions);

85.
86.
87.
88.
89.

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

90.
.zoom(8)
Contactmeforcodeservices

.build();

91.
92.

mMap.animateCamera(CameraUpdateFactory.newCameraPos
ition(cameraPosition));
93.
94.
95.
96.
97.

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

98.
99.
100.
101.
102.

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

103.

DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
104.

DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
105.

VolleySingleton.getInstance(getApplicationContext()
).addToRequestQueue(serverRequest);
106.
107.
108.

}
private Response.Listener<DirectionObject>
createRequestSuccessListener() {
return new
Response.Listener<DirectionObject>() {
@Override
public void onResponse(DirectionObject

109.
110.

response) {
try {

111.
112.

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

113.
114.

if(response.getStatus().equals("OK")){
List<LatLng> mDirections =
getDirectionPolylines(response.getRoutes());
drawRouteOnMap(mMap,

115.

mDirections);
}else{

116.
117.

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

118.
119.
120.

121.

};

122.

};

123.
124.

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

15/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

125.
126.
127.
128.
129.

private void setRouteDistanceAndDuration(String


distance, String duration){
distanceValue.setText(distance);
durationValue.setText(duration);
}
private List<LatLng>
getDirectionPolylines(List<RouteObject> routes){

Contactmeforcodeservices

List<LatLng> directionList

130.
131.
132.
133.
134.
135.

= new
ArrayList<LatLng>();
for(RouteObject route : routes){
List<LegsObject> legs =
route.getLegs();
for(LegsObject leg : legs){
String routeDistance =
leg.getDistance().getText();
String routeDuration =
leg.getDuration().getText();

136.

137.
138.

setRouteDistanceAndDuration(routeDistance,
routeDuration);
List<StepsObject> steps =
leg.getSteps();
for(StepsObject step : steps){
PolylineObject polyline =

139.

step.getPolyline();
140.
141.

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

142.

singlePolyline){
143.
144.

directionList.add(direction);
}
}

145.

146.

}
return directionList;

147.
148.
149.
150.
151.

}
private Response.ErrorListener
createRequestErrorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError

152.
153.

error) {
error.printStackTrace();

154.

155.

};

156.
157.
158.
159.

160.
161.
162.
163.
164.

}
private void drawRouteOnMap(GoogleMap map,
List<LatLng> positions){
PolylineOptions options = new
PolylineOptions().width(5).color(Color.RED).geodesi
c(true);
options.addAll(positions);
Polyline polyline =
map.addPolyline(options);
}
/**
* Method to decode polyline points

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

16/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

165.

166.
167.

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

168.

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


encoded.length();

170.

int lat = 0, lng = 0;


while (index < len) {
int b, shift = 0, result = 0;

Contactmeforcodeservices
=
169.
int index = 0, len
171.
172.

do {

173.

b = encoded.charAt(index++) - 63;

174.

result |= (b & 0x1f) << shift;


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

175.
176.
177.
178.
179.

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


(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {

180.
181.
182.

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

183.
184.
185.
186.
187.

shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~
(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat /

188.
189.

1E5)),
(((double) lng / 1E5)));

190.

poly.add(p);

191.

192.

return poly;

193.

194.
195.

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.
4.
5.
6.

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

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

17/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

7.
8.
9.
10.
11.
12.

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

Contactmeforcodeservices
13.
],
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.

"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 55.8541564,
"lng" : 13.661235
},
"southwest" : {
"lat" : 55.85187149999999,
"lng" : 13.660381
}
},
"copyrights" : "Map data 2016 Google",
"legs" : [
{
"distance" : {
"text" : "0.3 km",
"value" : 260
},
"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.
44.

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

45.
46.

},

47.

"steps" : [
{
"distance" : {

48.
49.

"text" : "0.3 km",


"value" : 260

50.
51.
52.
53.

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

54.
55.
56.

},

57.

"end_location" : {
"lat" : 55.85187149999999,

58.

"lng" : 13.660381

59.
60.

},

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

18/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

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" : {
:
"o_|sIwekrAVHxBj@|Bh@nBr@d@Hb@L"
},

Contactmeforcodeservices
63.
"points"

64.

"start_location" : {
"lat" : 55.8541564,

65.
66.

"lng" : 13.661235

67.

},
"travel_mode" : "DRIVING"

68.
69.

70.
71.

],

72.

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

73.

74.

],
"overview_polyline" : {

75.
76.

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

77.

},
"summary" : "Nygatan",

78.
79.

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

80.
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.
11.
12.

}
public String getStatus() {

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

19/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

return status;

13.

14.
15.

Contactmeforcodeservices

LEGSOBJECT.JAVA
1.

import java.util.List;

2.
3.

public class LegsObject {

4.
5.

private List<StepsObject> steps;

6.
7.

private DistanceObject distance;

8.
9.

private DurationObject duration;

10.
11.

public LegsObject(DurationObject duration,


DistanceObject distance, List<StepsObject> steps) {

14.

this.duration = duration;
this.distance = distance;
this.steps = steps;

15.

12.
13.

16.
17.
18.
19.

public List<StepsObject> getSteps() {


return steps;
}

20.
21.

public DistanceObject getDistance() {

22.

return distance;
}

23.
24.
25.
26.
27.
28.

public DurationObject getDuration() {


return duration;
}
}

POLYLINEOBJECT.JAVA
1.

public class PolylineObject {


private String points;
public PolylineObject(String points) {
this.points = points;

2.
3.
4.

}
public String getPoints() {

5.
6.

return points;

7.

8.
9.

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

20/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

ROUTEOBJECT.JAVA
1.
2.
3.

import java.util.List;
public class RouteObject {
private List<LegsObject> legs;

4.

public RouteObject(List<LegsObject> legs) {

6.

}
public List<LegsObject> getLegs() {
return legs;

Contactmeforcodeservices

5.
this.legs = legs;
7.
8.

9.
10.

STEPSOBJECTS.JAVA
1.

public class StepsObject {


private PolylineObject polyline;
public StepsObject(PolylineObject polyline) {
this.polyline = polyline;

2.
3.
4.

}
public PolylineObject getPolyline() {

5.
6.

return polyline;

7.

8.
9.

USING ANDROID VOLLEY FOR


NETWORK CALL
We are going to extends the Application class. Create a java class and
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.
2.
3.
4.
5.
6.
7.
8.

9.

import android.app.Application;
import com.android.volley.RequestQueue;
public class CustomApplication extends Application{
private RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate();
requestQueue =
VolleySingleton.getInstance(getApplicationContext()
).getRequestQueue();
}

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

21/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

public RequestQueue getVolleyRequestQueue(){

10.

return requestQueue;

11.

12.
13.

Contactmeforcodeservices

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.
18.

private Response.Listener<T> listener;


public GsonRequest(int method, String url,
Class<T> tClass, Response.Listener<T> listener,
Response.ErrorListener errorListener) {

19.

super(method, url, errorListener);

20.

this.tClass = tClass;
this.listener = listener;

21.

mGson = new Gson();

22.
23.
24.

}
public GsonRequest(int method, String url,
Class<T> tClass, Map<String, String> params,
Response.Listener<T> listener,
Response.ErrorListener errorListener) {

25.

super(method, url, errorListener);

26.
27.

this.tClass = tClass;
this.params = params;

28.

this.listener = listener;

29.

this.headers = null;
mGson = new Gson();

30.
31.

32.

@Override

33.
34.

public Map<String, String> getHeaders() throws


AuthFailureError {
return headers != null ? headers :
super.getHeaders();

35.

36.

@Override

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

22/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

37.

protected Map<String, String> getParams()


throws AuthFailureError {
return params;

38.

}
protected void deliverResponse(T response) {

39.
40.

listener.onResponse(response);

41.

}
Contactmeforcodeservices
43.
@Override
42.

44.

protected Response<T>
parseNetworkResponse(NetworkResponse response) {

45.

try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));

46.
47.

return
Response.success(mGson.fromJson(json, tClass),
HttpHeaderParser.parseCacheHeaders(response));

48.

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

49.

} catch (JsonSyntaxException e) {

50.
51.
52.

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

53.
54.

VOLLEYSINGLETON.JAVA
Create a new Java class and name it VolleySingleton.java. Open the
file and add the code below to it.
1.

import android.content.Context;

2.
3.

import android.graphics.Bitmap;
import android.util.LruCache;

4.

import com.android.volley.Request;

5.
6.

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;

7.

import com.android.volley.toolbox.Volley;

8.

public class VolleySingleton {

10.

private static VolleySingleton mInstance;


private RequestQueue mRequestQueue;

11.

private ImageLoader mImageLoader;

12.

private static Context mCtx;


private VolleySingleton(Context context) {

9.

13.
14.

mCtx = context;

15.

mRequestQueue = getRequestQueue();

16.

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

17.

private final LruCache<String, Bitmap>


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

18.
19.

@Override
public Bitmap getBitmap(String url) {
return cache.get(url);

20.
21.

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

23/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

22.
23.

@Override
public void putBitmap(String url,
Bitmap bitmap) {
cache.put(url, bitmap);

24.

25.

});

26.

27.

Contactmeforcodeservices
28.
public static synchronized

VolleySingleton

getInstance(Context context) {
29.
30.

if (mInstance == null) {
mInstance = new
VolleySingleton(context);
}

31.

return mInstance;

32.
33.

34.

public RequestQueue getRequestQueue() {

35.
36.

if (mRequestQueue == null) {
mRequestQueue =
Volley.newRequestQueue(mCtx.getApplicationContext()
);

37.

38.

return mRequestQueue;
}

39.
40.

public <T> void addToRequestQueue(Request<T>


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

41.

}
public ImageLoader getImageLoader() {

42.
43.

return mImageLoader;

44.

45.
46.

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

import android.content.Context;

2.

import android.net.ConnectivityManager;

3.

import android.net.NetworkInfo;

4.

public class Helper {


private static final String DIRECTION_API =
"https://maps.googleapis.com/maps/api/directions/js
on?origin=";

5.

6.
7.

public static final String API_KEY =


"AIzaSyCuZCfoPPUV1upJT10kJbC";
public static final int MY_SOCKET_TIMEOUT_MS =
5000;

8.

public static String getUrl(String originLat,


String originLon, String destinationLat, String
destinationLon){

9.

return Helper.DIRECTION_API +
originLat+","+originLon+"&destination="+destination
Lat+","+destinationLon+"&key="+API_KEY;
}

10.

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

24/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

11.

public static boolean


isNetworkAvailable(Context context) {

ConnectivityManager connectivityManager =
(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVI
CE);
13.
NetworkInfo activeNetworkInfo =
Contactmeforcodeservices
connectivityManager.getActiveNetworkInfo();

12.

14.

return activeNetworkInfo != null &&


activeNetworkInfo.isConnected();
}

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:

ANDROID TUTORIAL PART


5: AFRICAN HAIRSTYLE APP

Android CardView and


Toolbar with Material
Design

Android Fragment How to


pass data between
Fragments in an Activity

Create a beautiful Android


Weather App using
OpenWeatherMap API and
Volley Library part 2

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

25/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

Android Food Recipe App


with Php and Mysql
Backend

How to Create Android


Custom Calendar View with
Events

Contactmeforcodeservices
Tags: Android calculate distance between 2 points, Android find
distance between to points, measure distance between two points

ABOUT THE AUTHOR


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

7 COMMENTS

elmahdi

October 14, 2016

Log in to Reply

hi henry,
String routeDistance = leg.getDistance().getText();
String routeDuration = leg.getDuration().getText();
getDistance() and getDuration() arent defined on
LegsObject.
any advice?!
View Comment

Henry Author

October 14, 2016

Log in to Reply

Wow, thanks for pointing it out. I think I mistakenly


used a class from another project.
The class is pasted below and I have updated the
source code
import java.util.List;
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

26/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

public class LegsObject {


private List steps;
private DistanceObject distance;
private DurationObject duration;

Contactmeforcodeservices
public LegsObject(DurationObject
duration,

DistanceObject distance, List steps) {


this.duration = duration;
this.distance = distance;
this.steps = steps;
}
public List getSteps() {
return steps;
}
public DistanceObject getDistance() {
return distance;
}
public DurationObject getDuration() {
return duration;
}
}
View Comment

elmahdi

October 28, 2016

Log in to Reply
hi Henry,
there is no implementation of :
1) DistanceObject class
2) DurationObject class
can you plz put the code.
View Comment

Brian

October 17, 2016

Log in to Reply

Hi Henry,
The update seems not to work. Are there two
other classes missing or the methods are note
clearly defined.
View Comment
https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

27/28

9/12/2016

AndroidfinddistanceanddurationbetweentwopointsonGoogleMap

Rafelcf

October 19, 2016

Log in to Reply

The perfect place to learn and use enough for my


application would fragments code, since it is

Contactmeforcodeservices
based on many json files. You can download the
code ?.
thanks Henry
View Comment

Rafelcf

October 20, 2016

Log in to Reply
Sorry, too complicated for me, GSON for me is new,
only I pretended to renew my app but I find it very
difficult. Thank you
View Comment

Brian

November 11, 2016

Log in to Reply

Can you assist with the source code?


View Comment

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

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

ANDROID TUTORIALS

BUY APPS FROM $1

CONTACT US

https://inducesmile.com/android/androidfinddistanceanddurationbetweentwopointsonandroidmap/

28/28

Você também pode gostar