1

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:

Android mapbox emulator

mamcx
  • 15,916
  • 26
  • 101
  • 189

2 Answers2

2

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)
                }
            }
        }
    )
Bas Mulder
  • 36
  • 3
1

You can set public_api_key as mapbox_access_token in string resource file

Nabeel
  • 455
  • 3
  • 14