You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google地图Marker添加时默认图标短暂显示问题求助

解决Marker添加时默认图标闪烁问题

方案1:提前设置透明占位图标

添加Marker前,直接给MarkerOptions设置完全透明的占位图标,从根源避免默认图标被渲染:

// 生成1x1的透明Bitmap作为占位
private fun getTransparentPlaceholder(): Bitmap {
    return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888).apply {
        eraseColor(Color.TRANSPARENT)
    }
}

// 添加Marker时先设置占位图标
val markerOptions = MarkerOptions()
    .position(targetLatLng)
    .icon(BitmapDescriptorFactory.fromBitmap(getTransparentPlaceholder()))
val m = mMap?.addMarker(markerOptions)
// 再执行自定义图标和动画逻辑
setIconToMarkerWithAnimation(m, yourCustomBitmap)

方案2:调整动画时序,先隐藏再显式

修改动画逻辑,先将Marker设为完全透明,再设置自定义图标,最后执行渐显动画,确保默认图标没有显示机会:

private fun setIconToMarkerWithAnimation(m: Marker?, bitmap: Bitmap? = null) {
    val mapIcon = bitmap ?: getBitmapFromMarker(m)
    // 先将Marker设为完全透明
    m?.alpha = 0.0F
    // 设置自定义图标
    m?.setIcon(mapIcon?.let { BitmapDescriptorFactory.fromBitmap(it) })
    // 从0到1执行渐显动画
    val animation = ValueAnimator.ofFloat(0.0F, 1.0F)
    animation.duration = MapConstants.DEFAULT_ANIMATION_DURATION
    animation.interpolator = AnticipateOvershootInterpolator()
    animation.addUpdateListener { animationState ->
        val alpha = animationState.animatedValue as Float
        m?.alpha = alpha
    }
    // 加10ms延迟,确保图标加载完成后再启动动画
    animation.startDelay = 10
    animation.start()
}

方案3:预加载自定义图标Bitmap

如果自定义图标是从View生成的,提前在页面初始化阶段预生成所有需要的Bitmap,避免添加Marker时才生成导致的延迟,让setIcon能即时执行:

private val preloadedMarkerBitmaps = mutableMapOf<String, Bitmap>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // 预加载所有类型的Marker图标
    preloadedMarkerBitmaps["shop"] = generateMarkerBitmap(R.layout.marker_shop)
    preloadedMarkerBitmaps["park"] = generateMarkerBitmap(R.layout.marker_park)
}

// 将布局转为Bitmap
private fun generateMarkerBitmap(layoutId: Int): Bitmap {
    val view = LayoutInflater.from(this).inflate(layoutId, null)
    view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    return Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888).apply {
        val canvas = Canvas(this)
        view.draw(canvas)
    }
}

// 添加Marker时直接使用预加载的Bitmap
val targetBitmap = preloadedMarkerBitmaps["shop"]
val m = mMap?.addMarker(MarkerOptions().position(targetLatLng))
setIconToMarkerWithAnimation(m, targetBitmap)

内容的提问来源于stack exchange,提问作者Piyush Maheswari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 03:17:28