按照互聯網上的幾個教程,我設法在我的應用程式中繪制了一張谷歌地圖:
@Composable
fun MyMap(
lat: Double,
lon: Double
) {
val mapView = rememberMapViewWithLifeCycle()
Column(
modifier = Modifier
.background(Color.White)
) {
AndroidView(
{ mapView }
) { mapView ->
CoroutineScope(Dispatchers.Main).launch {
val map = mapView.awaitMap()
map.uiSettings.isZoomControlsEnabled = false
val destination = LatLng(lat, lon)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(destination, 16f))
val markerOptionsDestination = MarkerOptions()
.position(destination)
map.addMarker(markerOptionsDestination)
map.mapType = com.google.android.libraries.maps.GoogleMap.MAP_TYPE_HYBRID
}
}
}
}
@Composable
fun rememberMapViewWithLifeCycle(): MapView {
val context = LocalContext.current
val mapView = remember {
MapView(context).apply {
id = R.id.map_frame
}
}
val lifeCycleObserver = rememberMapLifecycleObserver(mapView)
val lifeCycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifeCycle) {
lifeCycle.addObserver(lifeCycleObserver)
onDispose {
lifeCycle.removeObserver(lifeCycleObserver)
}
}
return mapView
}
@Composable
fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
remember(mapView) {
LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> mapView.onCreate(Bundle())
Lifecycle.Event.ON_START -> mapView.onStart()
Lifecycle.Event.ON_RESUME -> mapView.onResume()
Lifecycle.Event.ON_PAUSE -> mapView.onPause()
Lifecycle.Event.ON_STOP -> mapView.onStop()
Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
else -> throw IllegalStateException()
}
}
}
我從另一個具有更多元素(如文本等)的可組合物中加載此可組合物:
@Composable
fun MyMain() {
Box(
modifier = Modifier
.fillMaxWidth()
.size(300.dp)
) {
MyMap(lat, lon)
}
}
加載地圖需要時間,不長,可能 1 秒或更短。但我希望 MyMain 可組合而不是第二個空框(包含地圖的框),以顯示加載微調器。我怎么能實作這個?
uj5u.com熱心網友回復:
您可能可以這樣做:
如果在 mapView.awaitMap() 之后地圖實際上沒有完全加載,請嘗試用延遲(1000)替換該行。(或超過 1000 毫秒)
@Composable
fun MyMap(
lat: Double,
lon: Double,
) {
val mapView = rememberMapViewWithLifeCycle()
var isMapLoading by remember { mutableStateOf(true) }
LaunchedEffect(mapView) {
mapView.awaitMap()
isMapLoading = false
}
Box {
AndroidView(
{ mapView }
) { mapView ->
CoroutineScope(Dispatchers.Main).launch {
val map = mapView.awaitMap()
map.uiSettings.isZoomControlsEnabled = false
val destination = LatLng(lat, lon)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(destination, 16f))
val markerOptionsDestination = MarkerOptions()
.position(destination)
map.addMarker(markerOptionsDestination)
map.mapType = com.google.android.libraries.maps.GoogleMap.MAP_TYPE_HYBRID
}
}
if (isMapLoading) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.matchParentSize()
.background(Color.White)
) {
CircularProgressIndicator()
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421276.html
標籤:
上一篇:為什么使用變數時無法導航到Flutter中的URL?
下一篇:使用addMarker方法
