I'm trying to get the location of an Android device. I've been following these instructions for using fusedLocationClient.

I can't assign variables outside .addSuccessListener.

I'll that the logs outside the listener are being called before the logs inside the event listener, so I must be trying to assign the variables before the listener is invoked. This makes sense because listeners are asynchronous.

override fun onMapReady() {
        var loc: Location = Location("")
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        fusedLocationClient.lastLocation
            .addOnSuccessListener { location : Location ->
                loc = location
                Log.i("Lat, Long",loc.latitude.toString() + ", " +  loc.longitude.toString()) // this correctly logs the latitude and longitude

            }

        Log.i("Lat, Long",loc.latitude.toString() + " " + loc.longitude.toString()) // this logs latitude and longitude as (0.0,0.0)
}

I've tried putting the fusedLocationClient initialization in onCreate() and having fusedLocationClient as a private property:


    private fusedLocationClient: FusedLocationProviderClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display_map)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        fusedLocationClient.lastLocation
            .addOnSuccessListener { location : Location ->
                loc = location
                Log.e(loc.latitude.toString(), loc.longitude.toString())
            }
    }

I've also tried it in onResume, but still no luck.

1 Answers

0
akaki On

Make a loc property as a delegated property:

var loc: Location? by Delegates.observable(null as? Location){
        _, _, newLoc ->
       // log
}

This delegate helps you observe any changes to the property