如何解决RadiusMarkerClusterer不显示自定义MarkerWithLabel标签的问题?
解决RadiusMarkerClusterer不显示自定义Marker标签的问题
问题原因
RadiusMarkerClusterer默认会自行创建普通Marker实例来替代你添加的自定义Marker(即使未聚合),导致你的MarkerWithLabel的draw方法从未被调用,标签无法显示。
修复步骤
1. 修正自定义Marker的draw方法
原代码的draw方法存在冗余调用,调整为直接在重写的方法中处理绘制逻辑:
class MarkerWithLabel(mapView: MapView?, val label: String) : Marker(mapView) { val textPaint = Paint() init { with(textPaint) { color = Color.BLACK textSize = 35f isAntiAlias = true typeface = Typeface.DEFAULT_BOLD textAlign = Paint.Align.CENTER } // 设置锚点,确保标签位置与图标对齐 setAnchor(0.5f, 1.0f) } override fun draw(c: Canvas, osmv: MapView?, shadow: Boolean) { // 先调用父类绘制图标 super.draw(c, osmv, shadow) // 阴影层不绘制标签 if (shadow) return val p: Point = mPositionPixels c.drawText(label, p.x.toFloat(), (p.y + 30).toFloat(), textPaint) } }
2. 自定义RadiusMarkerClusterer子类
重写createMarker方法,强制Clusterer创建你的MarkerWithLabel实例:
class CustomRadiusMarkerClusterer(mapView: MapView) : RadiusMarkerClusterer(mapView) { override fun createMarker(item: OverlayItem): Marker { // 从OverlayItem中获取标签信息,这里假设标签存在于title,可根据实际调整 val markerLabel = item.title return MarkerWithLabel(mMapView, markerLabel).apply { position = item.point setIcon(item.marker) title = item.title snippet = item.snippet setAnchor(0.5f, 1.0f) } } }
如果你的标签信息需要单独存储,可以自定义OverlayItem子类:
// 自定义OverlayItem,携带专属标签字段 class LabelOverlayItem(point: GeoPoint, title: String, val markerLabel: String) : OverlayItem(point, title, "") // 对应修改createMarker方法 override fun createMarker(item: OverlayItem): Marker { val labelItem = item as LabelOverlayItem return MarkerWithLabel(mMapView, labelItem.markerLabel).apply { position = labelItem.point setIcon(labelItem.marker) title = labelItem.title setAnchor(0.5f, 1.0f) } }
3. 使用自定义Clusterer替代原类
在代码中初始化并使用CustomRadiusMarkerClusterer:
val mapView = findViewById<MapView>(R.id.mapview) val clusterer = CustomRadiusMarkerClusterer(mapView) // 添加自定义OverlayItem到clusterer clusterer.add(LabelOverlayItem(GeoPoint(xxx, xxx), "标题", "自定义标签")) // 将clusterer添加到地图 mapView.overlays.add(clusterer)
这样Clusterer创建的所有Marker都会是你的MarkerWithLabel实例,标签就能正常显示了。
内容的提问来源于stack exchange,提问作者Matteo
相关产品推荐
相关产品推荐

