get current location android kotlin

// Step 1: Add permissions in AndroidManifest.xml
// Add these lines in the AndroidManifest.xml file to request location permissions.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

// Step 2: Check and request permissions at runtime
// Check if the necessary permissions are granted, and if not, request them at runtime.
// In your Activity or Fragment:

if (ContextCompat.checkSelfPermission(
        this,
        Manifest.permission.ACCESS_FINE_LOCATION
    ) != PackageManager.PERMISSION_GRANTED
) {
    ActivityCompat.requestPermissions(
        this,
        arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ),
        PERMISSION_REQUEST_CODE
    )
}

// Step 3: Handle permission request response
// Override onRequestPermissionsResult method to handle the permission request response.

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    when (requestCode) {
        PERMISSION_REQUEST_CODE -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, proceed to get the location
                getCurrentLocation()
            } else {
                // Permission denied, handle accordingly (e.g., show a message to the user)
                // You may choose to inform the user that the app requires location permission to function properly.
            }
        }
    }
}

// Step 4: Get the current location
// Use FusedLocationProviderClient to get the current device location.

private fun getCurrentLocation() {
    val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

    fusedLocationClient.lastLocation
        .addOnSuccessListener { location: Location? ->
            // Got last known location. In some rare situations, this can be null.
            if (location != null) {
                // Handle location found
                val latitude = location.latitude
                val longitude = location.longitude
                // Use latitude and longitude as needed
            } else {
                // Location is null, handle accordingly (e.g., request location updates)
                // You may choose to request location updates in this case.
            }
        }
        .addOnFailureListener { e ->
            // Handle failure (e.g., permissions not granted, location services disabled)
            // You may choose to show an error message to the user or log the error for debugging.
        }
}