LocationServices getFusedLocationProviderClient is not working

1.4k Views Asked by At

I want to return current user location when location is available.

this is my code:

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            super.onLocationResult(locationResult)
            if (locationResult.lastLocation != null && locationResult.lastLocation.latitude > 0 && locationResult.lastLocation.longitude > 0) {

                lastLocation = locationResult.lastLocation
                currentUserLatLng = LatLng(lastLocation.latitude, lastLocation.longitude)

                fusedLocationClient.removeLocationUpdates(locationCallback)

            }
        }
    }

the problem is, it's never called, I have the permission and allow my app to use gps, I set a debugger for it and it never comes in

could you help me? what is wrong with this code?

2

There are 2 best solutions below

0
MMG On

Why have you written locationResult.lastLocation.latitude > 0 & locationResult.lastLocation.longitude > 0 in your code? They can be negative

0
Dmitriy Puchkov On

Did you call requestLocationUpdates somewhere?

fusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper());