I have got very accurate location using FusedLocationProviderClient
(Google Play services required)
Permissions Required
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_COARSE_LOCATION
Dependency
'com.google.android.gms:play-services-location:15.0.0'
Kotlin Code
val client = FusedLocationProviderClient(this)
val location = client.lastLocation
location.addOnCompleteListener {
// this is a lambda expression and we get an 'it' iterator to access the 'result'
// it.result.latitude gives the latitude
// it.result.longitude gives the longitude
val geocoder = Geocoder(applicationContext, Locale.getDefault())
val address = geocoder.getFromLocation(it.result.latitude, it.result.longitude, 1)
if (address != null && address.size > 0) {
// Get the current city
city = address[0].locality
}
}
location.addOnFailureListener {
// Some error in getting the location, let's log it
Log.d("xtraces", it.message)
}