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

Android Auto中如何用Kotlin为PlaceListMapTemplate添加自定义标记

在PlaceListMapTemplate中添加自定义标记失败,求帮助

我尝试在PlaceListMapTemplate中添加自定义标记,但未能成功,希望有人能提供帮助。相关代码如下:

override fun onGetTemplate(): Template {

        val itemListBuilder = ItemList.Builder().setNoItemsMessage("No places to show")
        ItemRepository.getItems().forEach { itemListBuilder.addItem(itemRow(it)) }

        val builder = PlaceListMapTemplate.Builder()
        .setItemList(itemListBuilder.build())

        if (hasLocationPermission) {
            builder.setCurrentLocationEnabled(true)
        }

        return builder.build()
    }

解决步骤

要实现自定义标记,需要借助MapTemplate.MapCallback接口来操作地图实例,具体操作如下:

  • 1. 实现MapCallback接口
    在你的模板提供类中实现该接口,重写onMapCreated方法获取GoogleMap实例,之后在该实例上添加自定义标记:

    class YourTemplateProvider : TemplateProvider, MapTemplate.MapCallback {
        private var googleMap: GoogleMap? = null
    
        override fun onMapCreated(map: GoogleMap) {
            this.googleMap = map
            addCustomMarkers()
        }
    
        private fun addCustomMarkers() {
            googleMap?.let { map ->
                ItemRepository.getItems().forEach { item ->
                    val latLng = LatLng(item.latitude, item.longitude)
                    val markerOptions = MarkerOptions()
                        .position(latLng)
                        .title(item.title)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_custom_marker))
                    map.addMarker(markerOptions)
                }
            }
        }
    
        // 其他原有方法...
    }
    
  • 2. 为PlaceListMapTemplate设置回调
    在onGetTemplate方法中,通过builder绑定刚才实现的回调:

    override fun onGetTemplate(): Template {
        val itemListBuilder = ItemList.Builder().setNoItemsMessage("No places to show")
        ItemRepository.getItems().forEach { itemListBuilder.addItem(itemRow(it)) }
    
        val builder = PlaceListMapTemplate.Builder()
            .setItemList(itemListBuilder.build())
            .setMapCallback(this) // 绑定回调
    
        if (hasLocationPermission) {
            builder.setCurrentLocationEnabled(true)
        }
    
        return builder.build()
    }
    
  • 3. 注意事项

    • 确保自定义标记的图片资源存在于res/drawable目录下
    • 确认Item实体类包含经纬度字段(latitude、longitude)
    • 必须等待地图初始化完成(即onMapCreated回调触发)后再添加标记,避免空指针异常

内容的提问来源于stack exchange,提问作者raagull sakthivel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:13:09