如何在 Compose 中使用 Google 地图标记的自定义图标?

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

问题 如果我使用以下助手/扩展程序,我将得到一个异常 IBitmapDescriptorFactory is not initialized.

我检查了 Whosebug,他们中的一些人建议创建工厂的本地 属性 然后分配它,但这也不起作用。

Android Studio 向我显示了右侧的图标,因此我认为资产已正确添加。

来源

fun Webcam.toMarkerOptions(): MarkerOptions {

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

同样崩溃的来源 2

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
}

我为此创建了 MapMarker 可组合方法,它采用 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,
    )
}

其中位图描述符:

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)
}

更多详情:https://erselankhan.medium.com/jetpack-compose-custom-google-map-marker-erselan-khan-e6e04178a30b