首页 > 解决方案 > 自定义标记在 mapbox-android 中不可见

问题描述

我正在使用 mapbox-sdk android 进行位置跟踪。我想在指定位置的地图上添加一些自定义标记。但是下面的代码对我不起作用。

MarkerOptions options = new MarkerOptions();
options.title("pos");
IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
Icon icon = iconFactory.fromResource(R.drawable.home);
options.icon(icon);
options.position(new LatLng(80.27, 13.09));
mapboxMap.addMarker(options); 

我使用 mapox-sdk:6.0.1

标签: androidmapbox-androidmapbox-marker

解决方案


这就是我添加自定义标记的方式(从撰写的角度来看)。(您可以根据您的程序结构从 viewModel 执行此操作)

 AndroidView(
    factory = { mapView }, modifier = Modifier.fillMaxWidth()        
) { mView ->
    val bitmap = bitmapFromDrawableRes(context, R.drawable.chicken_marker)!!
    val annotation = mView.annotations
    val pointManager = annotation.createPointAnnotationManager()
    
    list.forEach { point ->
        val pointOptions = PointAnnotationOptions()
            .withPoint(point)
            .withIconImage(bitmap)

        pointManager.create(pointOptions.apply { iconSize = 0.8 })
    }

这是用于获取drawable(“.svg”,“.png”,“.jpeg”)的函数

private fun bitmapFromDrawableRes(context: Context, @DrawableRes resourceId: Int): Bitmap? =
    convertDrawableToBitmap(AppCompatResources.getDrawable(context, resourceId))

private fun convertDrawableToBitmap(sourceDrawable: Drawable?): Bitmap? {
    if (sourceDrawable == null) {
        return null
    }
    return if (sourceDrawable is BitmapDrawable) {
        sourceDrawable.bitmap
    } else {
// copying drawable object to not manipulate on the same reference
        val constantState = sourceDrawable.constantState ?: return null
        val drawable = constantState.newDrawable().mutate()
        val bitmap: Bitmap = Bitmap.createBitmap(
            drawable.intrinsicWidth, drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        bitmap
    }
}

推荐阅读