Jayden King
05/18/2024, 12:34 PMlifecycleScope
with something I can use in KMM https://github.com/googlemaps/android-maps-compose/blob/d5533b47f407414ef27c47eefd[…]ava/com/google/maps/android/compose/LocationTrackingActivity.ktJayden King
05/18/2024, 12:37 PMprivate val locationFlow = callbackFlow {
while (true) {
++counter
val location = newLocation()
Log.d(TAG, "Location $counter: $location")
trySend(location)
delay(2_000)
}
}.shareIn(
lifecycleScope,
replay = 0,
started = SharingStarted.WhileSubscribed()
)
Łukasz Nowakowski
05/18/2024, 1:07 PMJayden King
05/18/2024, 1:32 PMconst val DEFAULT_ZOOM = 17f
val DEFAULT_LOC = LatLng(0.0, 0.0)
@Composable
@SuppressLint("MissingPermission")
actual fun Map(modifier: Modifier) {
Setup()
if (
ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
Toast.makeText(
appContext,
"Location needs to be enabled to retrieve current location",
Toast.LENGTH_SHORT
).show()
return
}
val cameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(DEFAULT_LOC, DEFAULT_ZOOM)
}
val context = LocalContext.current
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
val failureMessage = "Could not retrieve current location. Please try again later."
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
location?.let { curLoc ->
CoroutineScope(Dispatchers.Main).launch {
val cameraPosition = CameraPosition.fromLatLngZoom(LatLng(curLoc.latitude, curLoc.longitude), DEFAULT_ZOOM)
cameraPositionState.animate(CameraUpdateFactory.newCameraPosition(cameraPosition), 1_000)
}
} ?: run {
Toast.makeText(context, failureMessage, Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener { e ->
Toast.makeText(context, failureMessage, Toast.LENGTH_SHORT).show()
e.message?.let { Log.e({}.javaClass.enclosingMethod?.name, it) }
}
GoogleMap(
modifier = modifier.fillMaxSize(),
cameraPositionState = cameraPositionState,
properties = MapProperties(isMyLocationEnabled = true)
)
}