I want my Kotlin app to get the current accurate (GPS) location once only when requested by the user.
Up to now I've been using fusedLocationClient.lastLocation
. This has generally worked successfully, but occasionally the app returns a distant location (sometimes a mile or two away) even when Google Maps and another app running on the same phone have an accurate GPS location.
I've tried implementing the getCurrentLocation method using code from How to get location using "fusedLocationClient.getCurrentLocation" method in Kotlin?. However, Android Studio reports an error at fusedLocationClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, object : CancellationToken()
saying that I should either:
"Rename reference"
or
"Create extension function for 'FusedLocationProviderClient.getCurrentLocation'"
Is it possible to force the lastLocation
method to use the GPS location? (In the Manifest I have only included the ACCESS_FINE_LOCATION
permission, but that doesn't seem to do the job.)
Failing that, can anyone show me how to create an extension function for the getCurrentLocation
method, please?. I've not found any examples online.
EDIT, following Gabe Sechan's answer
Although the FusedLocation provided by Google Play Services is often said to be what Google prefers, it cannot be relied on to provide the most accurate available location, as Gabe Sechan has commented in his answer.
For my purpose, therefore, I have turned to imthegaga's code provided in his answer in Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location - Stack Overflow. This code uses the Android location classes to get the last known locations from the GPS Provider if available and from the Network Provider if available and, if both are available, returns the more accurate one.