How do I get the current GPS location programmatically in Android?

前端 未结 22 3504
梦谈多话
梦谈多话 2020-11-21 04:42

I need to get my current location using GPS programmatically. How can i achieve it?

22条回答
  •  轮回少年
    2020-11-21 05:06

    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)
    }
    

提交回复
热议问题