How can I get my location with Kotlin dev Android?

前端 未结 1 2031
长情又很酷
长情又很酷 2021-01-24 18:11

I\'m making a Google Maps app. I\'ve put on the API key, and the default code runs without any problems, but I don\'t know how to localize my position...

I looked around

1条回答
  •  遥遥无期
    2021-01-24 18:36

    Try this code for getting the current location:

    File activity_main.xml

    
    
    
        
    
        
    
    
    

    File MainActivity.kt

    import android.Manifest
    import android.annotation.SuppressLint
    import android.content.Context
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.location.Location
    import android.location.LocationManager
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.os.Looper
    import android.provider.Settings
    import android.widget.TextView
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import com.google.android.gms.location.*
    
    class MainActivity : AppCompatActivity() {
    
        val PERMISSION_ID = 42
        lateinit var mFusedLocationClient: FusedLocationProviderClient
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    
            getLastLocation()
        }
    
        @SuppressLint("MissingPermission")
        private fun getLastLocation() {
            if (checkPermissions()) {
                if (isLocationEnabled()) {
    
                    mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                        var location: Location? = task.result
                        if (location == null) {
                            requestNewLocationData()
                        } else {
                            findViewById(R.id.latTextView).text = location.latitude.toString()
                            findViewById(R.id.lonTextView).text = location.longitude.toString()
                        }
                    }
                } else {
                    Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivity(intent)
                }
            } else {
                requestPermissions()
            }
        }
    
        @SuppressLint("MissingPermission")
        private fun requestNewLocationData() {
            var mLocationRequest = LocationRequest()
            mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            mLocationRequest.interval = 0
            mLocationRequest.fastestInterval = 0
            mLocationRequest.numUpdates = 1
    
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            mFusedLocationClient!!.requestLocationUpdates(
                mLocationRequest, mLocationCallback,
                Looper.myLooper()
            )
        }
    
        private val mLocationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                var mLastLocation: Location = locationResult.lastLocation
                findViewById(R.id.latTextView).text = mLastLocation.latitude.toString()
                findViewById(R.id.lonTextView).text = mLastLocation.longitude.toString()
            }
        }
    
        private fun isLocationEnabled(): Boolean {
            var locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER
            )
        }
    
        private fun checkPermissions(): Boolean {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                return true
            }
            return false
        }
    
        private fun requestPermissions() {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
                PERMISSION_ID
            )
        }
    
    
        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
            if (requestCode == PERMISSION_ID) {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    getLastLocation()
                }
            }
        }
    }
    

    See here for more details: Getting Current Location (latitude, longitude) in Android using Kotlin

    0 讨论(0)
提交回复
热议问题