Jayden King
05/04/2024, 10:42 AMJayden King
05/04/2024, 10:45 AMprivate fun completeTrip(trip: Trip, updateFun: (Trip) -> Unit, markComplete: (Boolean) -> Unit, context: Context) {
val composeView = findViewById<ComposeView>(R.id.trip_compose)
if (
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
Snackbar.make(
composeView.rootView, "Location needs to be enabled to retrieve current location", Snackbar.LENGTH_SHORT
).show()
return
}
val locationRequest = LocationRequest.create()
locationRequest.priority = Priority.PRIORITY_HIGH_ACCURACY
val lsrBuilder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(false)
val settingsClient: SettingsClient = LocationServices.getSettingsClient(context)
val lsrTask: Task<LocationSettingsResponse> = settingsClient.checkLocationSettings(lsrBuilder.build())
lsrTask.addOnSuccessListener lsrTask@{ lsr: LocationSettingsResponse? ->
if (lsr?.locationSettingsStates?.isLocationUsable != true) {
return@lsrTask
}
val currLocRequest = CurrentLocationRequest.Builder()
.setPriority(Priority.PRIORITY_HIGH_ACCURACY)
.setGranularity(Granularity.GRANULARITY_PERMISSION_LEVEL)
.build()
val cts = CancellationTokenSource()
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
val locTask = fusedLocationClient.getCurrentLocation(currLocRequest, cts.token)
locTask.addOnSuccessListener locTask@{ curLoc ->
if (curLoc == null) {
return@locTask
}
val bound = LatLngBounds(
LatLng(trip.destLat - VERIFICATION_RADIUS, trip.destLng - VERIFICATION_RADIUS),
LatLng(trip.destLat + VERIFICATION_RADIUS, trip.destLng + VERIFICATION_RADIUS)
)
if (!bound.contains(LatLng(curLoc.latitude, curLoc.longitude))) {
Snackbar.make(
composeView.rootView, "Current location does not match end location", Snackbar.LENGTH_SHORT
).show()
return@locTask
}
trip.complete = true
markComplete(true)
updateFun(trip)
}
locTask.addOnFailureListener {
Snackbar.make(
composeView.rootView,
"Could not retrieve current location. Please try again later.",
Snackbar.LENGTH_SHORT
).show()
}
}
}