Issue
I'm trying to use Mapbox with compose, but the map is not showing correctly. I try:
@Composable
fun MapView(
modifier: Modifier = Modifier
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
var map = MapView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
getMapboxMap().apply {
cameraOptions {
zoom(19.0)
}
}
}
map
}
)
}
But display empty:
Solution
You firstly have to get the instance of the mapbox with
Mapbox.getInstance(context, public_api_key)
Then inside the mapview you have to get the map asynchronously.
MapView(context).apply {
getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.MAPBOX_STREETS)
val position = CameraPosition.Builder()
.zoom(19.0)
.build()
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 1)
}
}
For the full snippet
AndroidView(
modifier = modifier,
factory = { context ->
Mapbox.getInstance(
context,
public_api_key
)
MapView(context).apply {
getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.MAPBOX_STREETS)
val position = CameraPosition.Builder()
.zoom(19.0)
.build()
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 1)
}
}
}
)
Answered By - Bas Mulder
Answer Checked By - Gilberto Lyons (JavaFixing Admin)