Android - How To Draw Path Between 2 Points On Google Map
Android - How To Draw Path Between 2 Points On Google Map
AndroidHowtodrawpathbetween2pointsonGoogleMap
DROID MOBILE
NOW
FOOD
TRENDING:
ORDERING APP FOR RESTAURANT STUDENTS PROJECT IDEA
ANDROID
IOS (SWIFT)
TIPS
APPS FROM $1
FORUM
Home Android
Android How to draw path between 2 points on Google Map
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.
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
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
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
google_maps_api.xml as shown.
1.
2.
<resources>
<!--
3.
4.
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.
7.
57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C::46;com.i
nducesmile.androidmapdrawroute
8.
9.
https://developers.google.com/maps/documentation/an
droid/start#get-key
10.
11.
12.
13.
14.
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
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.
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>
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.
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.
2.
<resources>
3.
<color name="colorPrimary">#3F51B5</color>
4.
<color name="colorPrimaryDark">#303F9F</color>
5.
6.
<color name="colorAccent">#FF4081</color>
</resources>
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
9/28
9/12/2016
AndroidHowtodrawpathbetween2pointsonGoogleMap
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.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
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.
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.
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.
128.
if (grantResults[0] ==
PackageManager.PERMISSION_DENIED) {
129.
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.
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.
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.
263.
error) {
error.printStackTrace();
264.
265.
};
266.
267.
268.
269.
270.
271.
272.
273.
274.
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.
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.
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.
305.
306.
}
return poly;
307.
308.
309.
310.
{
"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.
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.
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.
10.
}
public String getStatus() {
return status;
11.
12.
13.
14.
15.
LEGSOBJECT.JAVA
1.
2.
import java.util.List;
public class LegsObject {
3.
4.
5.
6.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
21/28
9/12/2016
AndroidHowtodrawpathbetween2pointsonGoogleMap
7.
8.
9.
10.
Contactmeforcodeservices
POLYLINEOBJECT.JAVA
1.
2.
3.
4.
5.
6.
7.
8.
9.
ROUTEOBJECT.JAVA
1.
2.
import java.util.List;
public class RouteObject {
3.
4.
5.
6.
7.
8.
9.
10.
STEPSOBJECTS.JAVA
1.
2.
3.
4.
5.
6.
7.
8.
9.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
22/28
9/12/2016
AndroidHowtodrawpathbetween2pointsonGoogleMap
Contactmeforcodeservices
name
it CustomApplication.java.
import android.app.Application;
2.
import com.android.volley.RequestQueue;
public class CustomApplication extends Application{
3.
4.
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.
15.
16.
17.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
23/28
9/12/2016
AndroidHowtodrawpathbetween2pointsonGoogleMap
18.
19.
20.
this.tClass = tClass;
21.
this.listener = listener;
Contactmeforcodeservices
22.
mGson = new Gson();
}
23.
24.
25.
26.
this.tClass = tClass;
27.
this.params = params;
28.
this.listener = listener;
this.headers = null;
29.
30.
}
@Override
31.
32.
33.
34.
35.
@Override
36.
37.
38.
39.
40.
41.
42.
43.
@Override
44.
45.
protected Response<T>
parseNetworkResponse(NetworkResponse response) {
try {
46.
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.
9.
10.
11.
12.
13.
14.
mCtx = context;
mRequestQueue = getRequestQueue();
15.
16.
mImageLoader = new
ImageLoader(mRequestQueue, new
ImageLoader.ImageCache() {
17.
18.
19.
return cache.get(url);
20.
21.
22.
@Override
23.
24.
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.
42.
43.
44.
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.
5.
6.
7.
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.
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
26/28
9/12/2016
AndroidHowtodrawpathbetween2pointsonGoogleMap
Android GridView Vs
GridLayout Example
Tutorial
Contactmeforcodeservices
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
ASK QUESTIONS
CONTACT US
Contactmeforcodeservices
https://inducesmile.com/android/androidhowtodrawpathbetween2pointsongooglemap/
28/28