androidandroid-locationkotlin-android

How to get location using "fusedLocationClient.getCurrentLocation" method in Kotlin?


To request the last known location of the user's device, we can use the fused location provider to retrieve the device's last known location using getLastLocation(), but using getCurrentLocation() gets a refresher, and more accurate location.

so, how to use the fusedLocationClient.getCurrentLocation() in Kotlin as there is no example illustrated in the documentation?


Solution

  • According to the documentation, the getCurrentLocation() takes two parameters.

    The 1st parameter it takes is the priority (e.g. PRIORITY_HIGH_ACCURACY) to request the most accurate locations available, or any other priority that can be found here.

    The 2nd parameter it takes is a cancellation token that can be used to cancel the current location request.

    From the Google play services reference, a CancellationToken can only be created by creating a new instance of CancellationTokenSource.

    so here is the code you need to use when using getCurrentLocation()

    class YourActivity : AppCompatActivity() {
    
        private lateinit var fusedLocationClient: FusedLocationProviderClient
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.your_layout)
    
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    
            fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object : CancellationToken() {
                    override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token
    
                    override fun isCancellationRequested() = false
                })
                .addOnSuccessListener { location: Location? ->
                    if (location == null)
                        Toast.makeText(this, "Cannot get location.", Toast.LENGTH_SHORT).show()
                    else {
                        val lat = location.latitude
                        val lon = location.longitude
                    }
    
                }
    
        }
    }