Skip to content

Instantly share code, notes, and snippets.

@RaheemJnr
Last active April 12, 2024 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaheemJnr/9dbaa74cd0888aa902dd9a273c4514a3 to your computer and use it in GitHub Desktop.
Save RaheemJnr/9dbaa74cd0888aa902dd9a273c4514a3 to your computer and use it in GitHub Desktop.
/**
* Manages all location related tasks for the app.
*/
//A callback for receiving notifications from the FusedLocationProviderClient.
lateinit var locationCallback: LocationCallback
//The main entry point for interacting with the Fused Location Provider
lateinit var locationProvider: FusedLocationProviderClient
@SuppressLint("MissingPermission")
@Composable
fun getUserLocation(context: Context): LatandLong {
// The Fused Location Provider provides access to location APIs.
locationProvider = LocationServices.getFusedLocationProviderClient(context)
var currentUserLocation by remember { mutableStateOf(LatandLong()) }
DisposableEffect(key1 = locationProvider) {
locationCallback = object : LocationCallback() {
//1
override fun onLocationResult(result: LocationResult) {
/**
* Option 1
* This option returns the locations computed, ordered from oldest to newest.
* */
for (location in result.locations) {
// Update data class with location data
currentUserLocation = LatandLong(location.latitude, location.longitude)
Log.d(LOCATION_TAG, "${location.latitude},${location.longitude}")
}
/**
* Option 2
* This option returns the most recent historical location currently available.
* Will return null if no historical location is available
* */
locationProvider.lastLocation
.addOnSuccessListener { location ->
location?.let {
val lat = location.latitude
val long = location.longitude
// Update data class with location data
currentUserLocation = LatandLong(latitude = lat, longitude = long)
}
}
.addOnFailureListener {
Log.e("Location_error", "${it.message}")
}
}
}
//2
if (hasPermissions(
context,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
locationUpdate()
} else {
askPermissions(
context, REQUEST_LOCATION_PERMISSION, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
}
//3
onDispose {
stopLocationUpdate()
}
}
//4
return currentUserLocation
}
//data class to store the user Latitude and longitude
data class LatandLong(
val latitude: Double = 0.0,
val longitude: Double = 0.0
)
@TheHamed8
Copy link

hello. where is the code of "hasPersmission" and "askPermission"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment