Get location android Kotlin

前端 未结 6 1673
傲寒
傲寒 2020-12-13 07:28

I recently added get location function. When I try to show longitude and latitude, it returns zero.

This my LocationListener class:

inner class Myloc         


        
6条回答
  •  [愿得一人]
    2020-12-13 07:55

    I know it's late, but now Google has made it simpler to use. In the developer site, it says that you need to create a Client:

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    

    Then onCreate get the provider:

    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }
    

    And finally, to get your last location just call:

    //Don't forget to ask for permissions for ACCESS_COARSE_LOCATION 
    //and ACCESS_FINE_LOCATION
    @SuppressLint("MissingPermission")
    private fun obtieneLocalizacion(){
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    latitude =  location?.latitude
                    longitude = location?.longitude
                }
    }
    

    *Tested with this implementation for location (Setup in your app gradle file)

    implementation 'com.google.android.gms:play-services-location:15.0.1'
    

    For more info, check this link:

    Obtain last location

提交回复
热议问题