我正在尝试按照 https://utsmannn.github.io/osm-android-compose/ 上的说明为 Android Compose 实现 openStreetMap。但 OpenStreetMap 复合函数被标记为未解析的链接。
问题已解决:网站上的gradle实现库名称错误:
tech.utsmankece:osm-androd-compose:${latest_version}.
正确的库名称必须是:
tech.utsmankece:osm-android-compose:${latest_version}.
安装依赖项
// MapLibre SDK
implementation("org.maplibre.gl:android-sdk:9.6.0")
implementation("org.maplibre.gl:android-sdk-turf:5.9.0")
// MapLibre plugins
implementation ("org.maplibre.gl:android-plugin-localization-v9:1.0.0")
implementation ("org.maplibre.gl:android-plugin-annotation-v9:1.0.0")
implementation ("org.maplibre.gl:android-plugin-markerview-v9:1.0.0")
创建MapCompose.kt文件
import android.os.Bundle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMapOptions
import com.telecom.menzil.R
@Composable
fun rememberMapViewLifecycle(): MapView {
val context = LocalContext.current
val mapboxMapOptions = MapboxMapOptions()
// Enable texture mode
mapboxMapOptions.textureMode(true)
val mapView = remember {
Mapbox.getInstance(context)
MapView(context).apply {
id = R.id.map
onCreate(Bundle())
}
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(key1 = lifecycle, key2 = mapView){
val lifecycleObserver = getMapLifecycleObserver(mapView)
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
return mapView
}
private fun getMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
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()
}
}
用法
val map = rememberMapViewLifecycle()
AndroidView(
modifier = Modifier
.fillMaxSize()
.zIndex(0f),
factory = {
map.apply {
getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.Builder().fromUri("asset://local_style_file.json")) {
}
}
}
},
update = {
}
)
将 local_style_file.json 文件添加到资产文件夹中,如下所示,openstreatmap 平铺服务器 url 也在这里