Documente Academic
Documente Profesional
Documente Cultură
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
ANDROID
IOS (SWIFT)
TIPS
APPS FROM $1
FORUM
Home Android
Android Real-time User Location Tracking Using Google Map API v2
Android
6 Comments
In this
tutorial, we
are going to
learn how to
implement
Android Realtime user
EMAIL SUBSCRIPTION
Enter your email address:
location
tracking using
Google Map
API v2.
Tracking user
Subscribe
Delivered by FeedBurner
location can
be beneficial when you want to record the distance and route a user
has gone through during exercise or other activities. Based on the
distance, you can calculate other parameters and present a
LIKE US ON
FACEBOOK
1/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
Android real-time user location tracking using Google Map API v2 are
usually use in sports and social networking apps.
Inducesmile
Megustaestapgina
If you are looking for a way to draw path between two points on
Google Map or to measures the distance and duration between
two points, I will suggest you first read my posts on these topics.
Selprimerodetusamigosenindicarquele
gustaesto.
APP
SCREENSHOT
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/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
2/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
Contactmeforcodeservices
3/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
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: AndroidRealtimeLocationTracking
Package: com.inducesmile.androidrealtimelocationtracking
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
Contactmeforcodeservices
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
4/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
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.
Contactmeforcodeservices
5/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
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.
<resources>
2.
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:71:B7:0D:2C:%3Bcom.inducesm
ile.androidmapdrawroute
6.
7.
57:A8:DD:42:FF:9E:88:E6:EC:69::46;com.inducesmile.a
ndroidmapdrawroute
8.
9.
https://developers.google.com/maps/documentation/an
droid/start#get-key
10.
Contactmeforcodeservices
11.
string in this file.
12.
-->
13.
<string name="google_maps_key"
templateMergeStrategy="preserve"
translatable="false">YOUR GOOGLE MAP API KEY
HERE</string>
14.
</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
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.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
6/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
2.
android {
3.
compileSdkVersion 24
4.
buildToolsVersion "24.0.1"
5.
defaultConfig {
6.
applicationId
"com.inducesmile.androidlocationtracking"
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.
dependencies {
compile fileTree(dir: 'libs', include:
['*.jar'])
20.
testCompile 'junit:junit:4.12'
21.
22.
23.
compile 'com.android.support:appcompatv7:24.2.1'
compile 'com.google.android.gms:play-servicesmaps:9.4.0'
Contactmeforcodeservices
24.
compile 'com.google.android.gms:play-serviceslocation:9.4.0'
25.
compile
'com.readystatesoftware.sqliteasset:sqliteassethelp
er:+'
26.
compile 'com.google.code.gson:gson:2.6.1'
27.
compile 'com.mcxiaoke.volley:library:1.0.19'
28.
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
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.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
7/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
1.
2.
<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid"
3.
package="com.inducesmile.androidlocationtracking">
4.
5.
6.
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATI
ON" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCA
TION" />
<uses-permission
android:name="android.permission.INTERNET" />
<application
android:name=".network.CustomApplication"
7.
8.
android:allowBackup="true"
9.
10.
android:icon="@mipmap/ic_launcher"
11.
android:label="@string/app_name"
12.
13.
android:supportsRtl="true"
android:theme="@style/AppTheme">
14.
<activity android:name=".MainActivity">
<intent-filter>
15.
16.
17.
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
18.
</activity>
19.
20.
<meta-data
21.
22.
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"
23.
/>
24.
<activity
Contactmeforcodeservices
android:name=".MapTrackingActivity"
25.
26.
android:label="@string/title_activity_map_tracking"
></activity>
27.
28.
<activity android:name=".SettingsActivity">
</activity>
<service
29.
android:name=".RouteService"
30.
android:enabled="true"
31.
android:exported="false"></service>
32.
33.
34.
<activity
android:name=".RecordResultActivity"></activity>
</application>
</manifest>
STRINGS.XML
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
8/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
<resources>
2.
3.
<string name="title_activity_map_tracking">Map
Route Tracking</string>
4.
5.
6.
<string name="permission_title">Location
Permission Denied</string>
7.
<string name="cancel_permission_notice">Wow,
please come back again when you need it and grant
the permission</string>
8.
</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.
2.
<resources>
3.
<color name="colorPrimary">#4CAF50</color>
5.
<color name="colorPrimaryLight">#C8E6C9</color>
6.
<color name="colorAccent">#4CAF50</color>
7.
<color name="colorPrimaryText">#212121</color>
Contactmeforcodeservices
4.
<color name="colorPrimaryDark">#388E3C</color>
8.
9.
10.
11.
<color
name="colorSecondaryText">#757575</color>
<color name="colorIcons">#FFFFFF</color>
<color name="colorDivider">#BDBDBD</color>
</resources>
ACTIVITY_MAP_TRACKING.XML
The MapTracking class main layout file consist of a Framelayout
ViewGroup with a Fragment and Button as children.
Open the layout file and add the code below.
1.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/a
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
9/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
ndroid"
2.
3.
xmlns:map="http://schemas.android.com/apk/resauto"
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_height="match_parent"
5.
android:orientation="vertical"
6.
android:layout_width="match_parent">
7.
<fragment
8.
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
9.
10.
android:name="com.google.android.gms.maps.SupportMa
pFragment"
11.
android:layout_width="match_parent"
12.
android:layout_height="match_parent"
13.
android:layout_gravity="center"
14.
tools:context="com.inducesmile.androidlocationtrack
ing.MapTrackingActivity" />
<Button
15.
16.
android:id="@+id/start_tracking"
17.
android:layout_width="match_parent"
18.
android:layout_height="wrap_content"
android:padding="16dp"
19.
20.
android:background="@color/colorPrimaryDark"
21.
android:textColor="@color/colorIcons"
22.
23.
android:text="@string/start_tracking"
android:layout_gravity="bottom"
24.
android:layout_marginBottom="40dp"
25.
android:layout_marginRight="16dp"
26.
android:layout_marginLeft="16dp"
android:gravity="center"/>
27.
28.
</FrameLayout>
Contactmeforcodeservices
MAPTRACKINGACTIVITY CLASS
The MapTrackingActivity class will implement the
GoogleApiClient.ConnectionCallback interface. We will create an
instance of the GoogleApiClient which we will use to connect to
Google Play Services and interact with the Location Service API.
In the onConnection() callback method, we will create a location
request and check if the our device has the right location settings
before we can obtain the device current location. The
GoogleApiClient object is released in the onStop() callback method.
We have also created an inner RouteBroadCastReceiver class which
will receive intent from the background service to update the Map
route UI.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
10/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
Open the MapTrackingActivity class and add the code below to it.
1.
import android.Manifest;
2.
3.
import android.content.BroadcastReceiver;
import android.content.Context;
4.
import android.content.Intent;
5.
import android.content.IntentFilter;
6.
import android.content.pm.PackageManager;
7.
8.
import android.graphics.Color;
import android.location.Location;
9.
import android.os.Bundle;
10.
import android.support.annotation.NonNull;
11.
import android.support.annotation.Nullable;
12.
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
13.
14.
import
android.support.v4.content.LocalBroadcastManager;
15.
import android.util.Log;
16.
import
com.google.android.gms.common.api.GoogleApiClient;
import
com.google.android.gms.common.api.PendingResult;
17.
18.
import
com.google.android.gms.common.api.ResultCallback;
19.
import com.google.android.gms.common.api.Status;
import
com.google.android.gms.location.LocationRequest;
20.
21.
import
com.google.android.gms.location.LocationServices;
import
com.google.android.gms.location.LocationSettingsReq
uest;
23.
import
com.google.android.gms.location.LocationSettingsRes
ult;
Contactmeforcodeservices
24.
import
com.google.android.gms.location.LocationSettingsSta
tusCodes;
22.
25.
import
com.google.android.gms.maps.CameraUpdateFactory;
26.
import com.google.android.gms.maps.GoogleMap;
import
com.google.android.gms.maps.OnMapReadyCallback;
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
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;
import
com.inducesmile.androidlocationtracking.database.Da
tabaseQuery;
import java.util.ArrayList;
import java.util.List;
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
11/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
setContentView(R.layout.activity_map_tracking);
52.
53.
54.
if (mGoogleApiClient == null) {
mGoogleApiClient = new
GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
55.
56.
57.
58.
59.
}
mQuery = new DatabaseQuery(this);
startToPresentLocations =
mQuery.getAllLocationObjects();
mLocationRequest = createLocationRequest();
routeReceiver = new
RouteBroadCastReceiver();
62.
// Obtain the SupportMapFragment and get
notified when the map is ready to be used.
Contactmeforcodeservices
60.
61.
63.
SupportMapFragment mapFragment =
(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.m
ap);
mapFragment.getMapAsync(this);
64.
65.
66.
@Override
public void onMapReady(GoogleMap googleMap) {
67.
68.
69.
70.
71.
mMap = googleMap;
}
private void
markStartingLocationOnMap(GoogleMap mapObject,
LatLng location){
mapObject.addMarker(new
MarkerOptions().position(location).title("Current
location"));
72.
73.
74.
75.
mapObject.moveCamera(CameraUpdateFactory.newLatLng(
location));
}
@Override
public void onConnected(@Nullable Bundle
bundle) {
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
12/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
86.
&&
ActivityCompat.checkSelfPermission(getApplicationCo
ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);
if (mLastLocation !=
null) {
87.
88.
latitudeValue =
89.
mLastLocation.getLatitude();
90.
Contactmeforcodeservices
mLastLocation.getLongitude();
91.
92.
longitudeValue =
Log.d(TAG,
"Latitude 4: " + latitudeValue + " Longitude 4: " +
longitudeValue);
refreshMap(mMap);
93.
94.
95.
markStartingLocationOnMap(mMap, new
LatLng(latitudeValue, longitudeValue));
startPolyline(mMap,
new LatLng(latitudeValue, longitudeValue));
}
}
break;
96.
97.
98.
case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAIL
ABLE:
break;
99.
100.
101.
});
102.
103.
104.
105.
@Override
public void onConnectionSuspended(int i) {
106.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
13/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
107.
108.
109.
110.
111.
112.
113.
114.
startToPresentLocations =
mQuery.getAllLocationObjects();
if(startToPresentLocations.size() >
115.
0){
//prepare map drawing.
116.
117.
118.
119.
List<LatLng> locationPoints =
getPoints(startToPresentLocations);
refreshMap(mMap);
markStartingLocationOnMap(mMap,
locationPoints.get(0));
drawRouteOnMap(mMap,
120.
locationPoints);
}
121.
122.
123.
124.
125.
private List<LatLng>
getPoints(List<LocationObject> mLocations){
List<LatLng> points = new ArrayList<LatLng>
126.
();
127.
128.
129.
130.
Contactmeforcodeservices
}
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
map.animateCamera(CameraUpdateFactory.newCameraPosi
tion(cameraPosition));
145.
146.
}
private void drawRouteOnMap(GoogleMap map,
List<LatLng> positions){
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
14/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
147.
148.
149.
Polyline polyline =
map.addPolyline(options);
150.
151.
152.
154.
.bearing(90)
.tilt(40)
155.
.build();
153.
156.
157.
158.
159.
160.
161.
162.
map.animateCamera(CameraUpdateFactory.newCameraPosi
tion(cameraPosition));
}
private void refreshMap(GoogleMap mapInstance){
mapInstance.clear();
}
protected LocationRequest
createLocationRequest() {
LocationRequest mLocationRequest = new
LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
163.
164.
165.
mLocationRequest.setPriority(LocationRequest.PRIORI
TY_HIGH_ACCURACY);
return mLocationRequest;
166.
167.
168.
169.
170.
}
@Override
protected void onResume() {
super.onResume();
Contactmeforcodeservices
if(routeReceiver ==
171.
172.
173.
174.
null){
routeReceiver = new
RouteBroadCastReceiver();
}
IntentFilter filter = new
IntentFilter(RouteService.ACTION);
175.
176.
177.
178.
LocalBroadcastManager.getInstance(this).registerRec
eiver(routeReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
179.
180.
181.
182.
183.
184.
LocalBroadcastManager.getInstance(this).unregisterR
eceiver(routeReceiver);
}
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
185.
186.
187.
@Override
protected void onStop() {
188.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
15/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
mGoogleApiClient.disconnect();
super.onStop();
189.
190.
191.
192.
ROUTESERVICE CLASS
The RouteService class is an android service class that runs in the
background. The service starts when a user toggle the start tracking
button and you can as well stop it with the button is the button uses
a flag to tracking the state of the service class.
The RouteService class implements the GoogleApiClient
OnConnectionCallbacks, OnConnectionFailedListener and
LocationListener.
The LocationListener overrides the onLocationChange() method
which pass the current location as parameter.
The location is stored in SQLite database and the Service class will
notify the Local Broadcast Receiver class of the location update.
Open the RouteService.java file and add the code below.
1.
import android.Manifest;
import android.app.Service;
3.
import android.content.Intent;
Contactmeforcodeservices
4.
import android.content.pm.PackageManager;
2.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import
android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import
com.google.android.gms.common.ConnectionResult;
import
com.google.android.gms.common.api.GoogleApiClient;
15.
import
com.google.android.gms.common.api.PendingResult;
16.
import
com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
17.
18.
import
com.google.android.gms.location.LocationListener;
19.
import
com.google.android.gms.location.LocationRequest;
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
16/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
20.
21.
22.
import
com.google.android.gms.location.LocationServices;
import
com.google.android.gms.location.LocationSettingsReq
uest;
import
com.google.android.gms.location.LocationSettingsRes
ult;
23.
import
com.google.android.gms.location.LocationSettingsSta
tusCodes;
24.
import
com.inducesmile.androidlocationtracking.database.Da
tabaseQuery;
import
com.inducesmile.androidlocationtracking.helpers.Cus
tomSharedPreference;
public class RouteService extends Service
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG =
RouteService.class.getSimpleName();
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
@Override
Contactmeforcodeservices
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
17/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
56.
57.
58.
59.
60.
}
@Override
public int onStartCommand(Intent intent, int
flags, int startId) {
isServiceRunning = true;
return Service.START_STICKY;
61.
62.
63.
@Nullable
@Override
public IBinder onBind(Intent intent) {
64.
65.
return null;
66.
67.
68.
69.
70.
}
@Override
public void onConnected(@Nullable Bundle
bundle) {
Log.d(TAG, "Connection method has been
called");
71.
LocationSettingsRequest.Builder builder =
new
LocationSettingsRequest.Builder().addLocationReques
t(mLocationRequest);
72.
PendingResult<LocationSettingsResult>
result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient, builder.build());
73.
result.setResultCallback(new
ResultCallback<LocationSettingsResult>() {
@Override
74.
75.
76.
77.
case
LocationSettingsStatusCodes.SUCCESS:
Contactmeforcodeservices
79.
if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
80.
&&
ActivityCompat.checkSelfPermission(getApplicationCo
ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
81.
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);
82.
if (mLastLocation !=
null) {
78.
latitudeValue =
83.
mLastLocation.getLatitude();
longitudeValue =
84.
mLastLocation.getLongitude();
85.
Log.d(TAG,
"Latitude 1: " + latitudeValue + " Longitude 1: " +
longitudeValue);
86.
LocationServices.FusedLocationApi.requestLocationUp
dates(mGoogleApiClient, mLocationRequest,
RouteService.this);
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
18/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
87.
88.
89.
90.
91.
break;
case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAIL
ABLE:
break;
}
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
});
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull
ConnectionResult connectionResult) {
}
102.
protected LocationRequest
createLocationRequest() {
103.
104.
105.
mLocationRequest.setFastestInterval(3000);
106.
107.
108.
109.
110.
mLocationRequest.setPriority(LocationRequest.PRIORI
TY_HIGH_ACCURACY);
return mLocationRequest;
}
@Override
public void onLocationChanged(Location
location) {
isServiceRunning);
113.
if(isRouteTrackingOn() &&
startTimeInMilliSeconds == 0){
111.
114.
115.
116.
117.
118.
119.
startTimeInMilliSeconds =
System.currentTimeMillis();
}
if(isRouteTrackingOn() &&
startTimeInMilliSeconds > 0){
latitudeValue = location.getLatitude();
longitudeValue =
location.getLongitude();
Log.d(TAG, "Latitude " + latitudeValue
+ " Longitude " + longitudeValue);
// insert values to local sqlite
120.
database
121.
122.
123.
query.addNewLocationObject(System.currentTimeMillis
(), latitudeValue, longitudeValue);
// send local broadcast receiver to
application components
Intent localBroadcastIntent = new
Intent(ACTION);
124.
localBroadcastIntent.putExtra("RESULT_CODE",
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
19/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
"LOCAL");
125.
LocalBroadcastManager.getInstance(getApplicationCon
text()).sendBroadcast(localBroadcastIntent);
long timeoutTracking = 2 * 60 * 60 *
126.
1000;
127.
128.
if(System.currentTimeMillis() >=
startTimeInMilliSeconds + timeoutTracking){
//turn of the tracking
129.
130.
131.
customSharedPreference.setServiceState(false);
Log.d(TAG, "SERVICE HAS BEEN
STOPPED");
this.stopSelf();
}
}
if(!isRouteTrackingOn()){
132.
133.
134.
135.
1");
isServiceRunning = false;
136.
137.
138.
139.
140.
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
);
this.startActivity(dialogIntent);
this.stopSelf();
141.
142.
143.
144.
145.
}
private boolean isRouteTrackingOn(){
Log.d(TAG, "SERVICE STATE " +
customSharedPreference.getServiceState());
return
customSharedPreference.getServiceState();
Contactmeforcodeservices
147.
}
146.
@Override
public void onDestroy() {
mGoogleApiClient.disconnect();
148.
149.
150.
super.onDestroy();
151.
152.
153.
This brings us to the end of this tutorial. I hope that you have learn
something. Run your app and take a work around you will see how
your location is being drawn on the map.
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.
20/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
Contactmeforcodeservices
API
Android
Json Parsing using
Android Camera2
Gson and RecyclerView
Example Tutorial
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
21/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
6 COMMENTS
roger
Log in to Reply
Hi Henry,
This is very useful tutorial. I just wonder if you can
also post class source code of LocationObject as
well as the database source code so that to make
it as a complete example that I can learn and try.
Thanks a lot
Ling
View Comment
Henry Author
Log in to Reply
Contactmeforcodeservices
akhil
Log in to Reply
Henry Author
Log in to Reply
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
22/23
9/12/2016
AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2
roger
Log in to Reply
Thanks a lot! Look forward to see the SQLite
database for location data
View Comment
roger
Log in to Reply
ADD A COMMENT
You must be logged in to post a comment.
INDUCESMILE ANDROID TUTORIAL, ANDROID APPS, ANDROID STUDIO, ANDROID SDK, ANDROID
Contactmeforcodeservices
ANDROID TUTORIALS
CONTACT US
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/
23/23