Tobonaut
Tobonaut

Reputation: 2485

How to use custom icon of Google Maps Marker in Compose?

The problem If I use the following helper / extension I will get an exception IBitmapDescriptorFactory is not initialized.

I checked Stackoverflow, some of them recommend to create a local property of the factory and than assign it but this does also not work.

Android Studio shows me the icon on the right side, because of this I think the asset has been added correctly.

Source

fun Webcam.toMarkerOptions(): MarkerOptions {

    return MarkerOptions()
        .title(name)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_webcam))
        .position(coordinate.toLngLat())
}

Source 2 which also crashes

fun MarkerOptions.icon(context: Context, @DrawableRes vectorDrawable: Int): MarkerOptions {
    this.icon(ContextCompat.getDrawable(context, vectorDrawable)?.run {
        setBounds(0, 0, intrinsicWidth, intrinsicHeight)
        val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
        draw(Canvas(bitmap))
        BitmapDescriptorFactory.fromBitmap(bitmap)
    })
    return this
}

Upvotes: 10

Views: 5519

Answers (1)

Erselan Khan
Erselan Khan

Reputation: 845

I have created the MapMarker composable method for this which takes resourceId:

@Composable
fun MapMarker(
    context: Context,
    position: LatLng,
    title: String,
    snippet: String,
    @DrawableRes iconResourceId: Int
) {
    val icon = bitmapDescriptor(
        context, iconResourceId
    )
    Marker(
        position = position,
        title = title,
        snippet = snippet,
        icon = icon,
    )
}

where bitmapDescriptor:

fun bitmapDescriptor(
    context: Context,
    vectorResId: Int
): BitmapDescriptor? {

    // retrieve the actual drawable
    val drawable = ContextCompat.getDrawable(context, vectorResId) ?: return null
    drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
    val bm = Bitmap.createBitmap(
        drawable.intrinsicWidth,
        drawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )

    // draw it onto the bitmap
    val canvas = android.graphics.Canvas(bm)
    drawable.draw(canvas)
    return BitmapDescriptorFactory.fromBitmap(bm)
}

For more details: https://erselankhan.medium.com/jetpack-compose-custom-google-map-marker-erselan-khan-e6e04178a30b

Upvotes: 9

Related Questions