Last active
April 12, 2024 09:14
-
-
Save RaheemJnr/9dbaa74cd0888aa902dd9a273c4514a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello. where is the code of "hasPersmission" and "askPermission"