Fused Location Provider

Firstly follow all the steps for asking permission and requesting in realtime from the above part and then follow next.

Fused Location Provider is the Google Play services location APIs, your app can request the last known location of the user’s device.

Use the fused location provider to retrieve the device’s last known location. The fused location provider is one of the location APIs in Google Play services. It provides a simple API so that you can specify requirements at a high level, like high accuracy or low power. It also optimizes the device’s use of battery power.

First, we will create a fusedlocationcleint variable and then give it an instance of FusedLocationProviderClient inside the onCreate

private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
<!--Inside the onCreate give the lateinitialized variable an instance of Fused Location -->
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}

Fused location provider API can broadly categorize two use cases.

  1. getLastLocation(GoogleApiClient) : It should be used when there is no need for continuous access to the location from an application.
  2. requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener) : It should be used when there a need for continuous location updates and the location is accessed when the application is active in the foreground

So, we will we using requestLocationUpdates method and for that, we have to create a request with an instance of LocationRequest() method and for the same, we will create interval, fastestInterval, priority objects.

And after checking the permissions we call the client with requestlocationupdate API in which we pass our request and our Location Listener for updating the location in realtime.

And when the location is changed the listener runs and updates the location coordinates in Firebase Firestore.

val request = LocationRequest()
request.interval = 10000
request.fastestInterval = 5000
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION
)
if (permission == PackageManager.PERMISSION_GRANTED) {
    // Request location updates and when an update is
    // received, store the location in Firebase
    fusedLocationClient.requestLocationUpdates(request, object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val location: Location? = locationResult.lastLocation
            if (location != null) {                       Firebase.firestore.collection("Collection").document(doc).update("Longitude",location!!.longitude,"Latitude", location!!.latitude)
            }
        }
    }, null)
}

 

Discussion
Nice article rohit

2

13

1