I don’t know how to get latitude and longitude using Googleapiclient

Asked

Viewed 69 times

0

I’m developing an android app using Kotlin, I followed a tutorial of a topic from here, but it caught the last location that was saved, not latitude and longitude, which is what I need. Follows the code:

class InserirAbastecimentoActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

lateinit var googleApiClient:GoogleApiClient

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_inserir_abastecimento)
    setSupportActionBar(toolbar)

    googleApiClient = GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build()

    //Conectar com GoogleApi
    googleApiClient.connect()
...}
    override fun onStop() {
    super.onStop()
    pararConexaoComGoogleApi()
}

fun pararConexaoComGoogleApi(){
    if (googleApiClient.isConnected){
        googleApiClient.disconnect()
    }
}

override fun onConnected(p0: Bundle?) {
    Log.d("Tag", "Conexão bem sucedida")
}

override fun onConnectionSuspended(p0: Int) {
}

override fun onConnectionFailed(p0: ConnectionResult) {
    pararConexaoComGoogleApi()
}

}

1 answer

0

I would recommend you to use Fusedlocationproviderclient.

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

You add a Listener to it that will return you a Location object when it can pick up the location and inside it are the latitude of logitude:

fusedLocationClient.lastLocation .addOnSuccessListener { location : Location? -> var latitude= location.latitude.toString() var longitude= location.longitude.toString() }

Source: https://developer.android.com/training/location/retrieve-current

Browser other questions tagged

You are not signed in. Login or sign up in order to post.