-2

I am designing an Android weather app using Kotlin. I want to get latitude and longitude of the device in background, then fetch weather data for that.

How can I implement an auto detecting latitude and longitude feature in Kotlin?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • 2
    See https://developer.android.com/training/location – Michael Oct 14 '21 at 13:41
  • I think this post can help you: https://stackoverflow.com/questions/2224844/how-to-get-the-absolute-coordinates-of-a-view – Saeed Afshari Oct 14 '21 at 14:44
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 15 '21 at 14:54

1 Answers1

0

Getting a location is pretty boilerplate. Here's a quick example that uses the last known location.

    const val REQUEST_CODE_LOCATION_PERMISSION = 100

    fun getLocation(context: Context): Location? {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(); return null }

        val mLocationManager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null
        return mLocationManager.getLastKnownLocation(findProvider(mLocationManager) ?: "")
    }

    fun requestPermissions() {
        ActivityCompat.requestPermissions(activity, arrayOf(ACCESS_FINE_LOCATION), REQUEST_CODE_LOCATION_PERMISSION)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) getWeather()
    }

    fun getWeather() {
        getLocation()?.let { fetchWeatherData(it.latitude, it.longitude) }
    }
Chris
  • 1,180
  • 1
  • 9
  • 17