Skip to content

Instantly share code, notes, and snippets.

@oussama-dz
Last active June 18, 2023 15:46
Show Gist options
  • Save oussama-dz/59146c9cebd873035d2313c236a0f579 to your computer and use it in GitHub Desktop.
Save oussama-dz/59146c9cebd873035d2313c236a0f579 to your computer and use it in GitHub Desktop.
Show the current user's location on the map using MapBoxComposable.
@Composable
fun MapScreen() {
var point: Point? by remember {
mutableStateOf(null)
}
var relaunch by remember {
mutableStateOf(false)
}
val context = LocalContext.current
val permissionRequest = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions(),
onResult = { permissions ->
if (!permissions.values.all { it }) {
//handle permission denied
}
else {
relaunch = !relaunch
}
}
)
Column(
modifier = Modifier.fillMaxSize(),
) {
MapBoxMap(
point = point,
modifier = Modifier
.fillMaxSize()
)
}
LaunchedEffect(key1 = relaunch) {
try {
val location = LocationService().getCurrentLocation(context)
point = Point.fromLngLat(location.longitude, location.latitude)
} catch (e: LocationService.LocationServiceException) {
when (e) {
is LocationService.LocationServiceException.LocationDisabledException -> {
//handle location disabled, show dialog or a snack-bar to enable location
}
is LocationService.LocationServiceException.MissingPermissionException -> {
permissionRequest.launch(
arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
)
}
is LocationService.LocationServiceException.NoNetworkEnabledException -> {
//handle no network enabled, show dialog or a snack-bar to enable network
}
is LocationService.LocationServiceException.UnknownException -> {
//handle unknown exception
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment