Real time location tracking via Google Maps v2 API in Android
Posted By : Sunidhi Sharma | 29-Apr-2019
Overview:
Real-time location tracking has long become a key feature in mobile applications. Be it for content restriction or tracking the live location and updating it over maps, all these features require the geolocation tracking. This blog discusses how one can implement this in their own Android Application.
We are going to set-up an Android Project and integrate the Google Maps API. Then, we are going to add live map markers and finally, end it with live location tracking.
Requirements:
1. Android device.
2. Android Gradle version 3 or above.
3. Android Studio Project for Version 23 (Marshmallow) or higher support
Implementation in a Project:
Step 1: Creating your Google Maps API Project and Credentials
In order to start integration, we’ll first need an API Key. You can do so by simply following the steps written in this link.
This will help you generate a unique key which can be linked to your Android application. You can manage the API from the Google API console here.
Edit your project's gradle.properties file. Add your key as shown below:
GOOGLE_MAPS_API_KEY=PASTE-YOUR-API-KEY-HERE
When you build your app, Gradle copies the API key into the app's Android manifest.
Step 2: Instantiating the Location Listeners
The LocationServices interface is the main entry point for Android location services.
To use the APIs, instantiate GeoDataClient, PlaceDetectionClient, and FusedLocationProviderClient in your fragment's or activity's onCreate() method, as shown in the following code sample:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Construct a GeoDataClient.
mGeoDataClient = Places.getGeoDataClient(this, null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
Step 3: Adding the necessary permissions.
Our app must request location permission in order to determine the location of the device and to allow the user to tap the My Location button on the map.
This tutorial provides the code you need to request fine location permission.
Add the permission as a child of the <manifest> element in your Android manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.currentplacedetailsonmap">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
Next step involves requesting the runtime permission for the location from the user. You ask the user to grant the location permission in case she hasn’t already.
private void getLocationPermission() {
/*
* Request the permission
* Method onRequestPermissionsResult is used for callbacks
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
// The onRequestPermissionsResult() method helps in handling result of the request:
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
Step 4: Adding a Map:
One can simply display a map in an Android application by using Maps SDK. After adding the necessary dependencies in your app level gradle, you’ll need to add a <fragment> element to your activity’s layout file as shown below:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.currentplacedetailsonmap.MapsActivityCurrentPlace" />
Implementing the onMapReadyCallback interface will help you get the GoogleMap object when the map object becomes available.
public void onMapReady(GoogleMap map) {
mMap = map;
updateLocationUI();
// Getting the current location of the device and setting the position of the map.
getDeviceLocation();
}
You can take getMapAsync() method’s help for getting map callback:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Write an updateLocationUI() method to set the location controls on the map. If the permission is granted you can allow the MY LOCATION and the related map controls otherwise restrict them.
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
Step 5: Displaying the current location:
To find the current location, we can use fused location provider, and this location can be used to reposition the Map. The code to the same is shown below:
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch(SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
Conclusion:
To conclude, this blog just demonstrated how you can show the current location using the Maps SDK and Google Maps API v2 on an Android application. For more information, you can read the official documentation from this link.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sunidhi Sharma
An ardent computer science enthusiast working in the field of Android application development.