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

Tob*_*aut 6 android google-maps-markers kotlin

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

我检查了 Stackoverflow,其中一些人建议创建工厂的本地属性并分配它,但这也不起作用。

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

来源

fun Webcam.toMarkerOptions(): MarkerOptions {

    return MarkerOptions()
        .title(name)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_webcam))
        .position(coordinate.toLngLat())
}
Run Code Online (Sandbox Code Playgroud)

源 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
}
Run Code Online (Sandbox Code Playgroud)

Ers*_*han 5

我为此创建了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,
    )
}
Run Code Online (Sandbox Code Playgroud)

其中位图描述符:

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)
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息:https://erselankhan.medium.com/jetpack-compose-custom-google-map-marker-erselan-khan-e6e04178a30b