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

从应用调起Google Maps,基于经纬度显示不同颜色多标记

调起Google Maps显示多标记并自定义标记颜色的正确实现

原代码存在的问题

  • 错误将Web地图URL嵌套进geo: URI,不符合Google Maps Intent的调用规范
  • 生成的颜色未关联到标记参数中,无法实现颜色自定义效果
  • Markers参数格式错误(重复设置label参数、编码字符使用不当)

修正后的代码实现

private fun launchMaps(ticketLocationDetails: List<TicketLocationDetails>) {
    try {
        // 为每个位置绑定对应颜色(可根据类型替换为固定预设色)
        val colorMap = ticketLocationDetails.associate {
            it to generateRandomColor(Random())
        }
        val mapIntentUri = constructCustomMapUrl(ticketLocationDetails, colorMap)
            ?: run {
                Toast.makeText(requireContext(), "无有效位置数据", Toast.LENGTH_SHORT).show()
                return
            }

        val mapIntent = Intent(Intent.ACTION_VIEW, mapIntentUri)
        mapIntent.setPackage("com.google.android.apps.maps")
        mapIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(mapIntent)
    } catch (e: Exception) {
        Toast.makeText(requireContext(), "无法启动Google Maps", Toast.LENGTH_SHORT).show()
        e.printStackTrace()
    }
}

private fun constructCustomMapUrl(
    locations: List<TicketLocationDetails>,
    colorMap: Map<TicketLocationDetails, String>
): Uri? {
    if (locations.isEmpty()) return null

    // 构造每个标记的参数:颜色+标签+经纬度
    val markers = locations.mapIndexed { index, location ->
        val color = colorMap[location] ?: "0xFF0000FF" // 默认蓝色
        "markers=color:$color|label:${index + 1}|${location.latitude},${location.longitude}"
    }.joinToString("&")

    // 使用Google Maps专属Intent协议,支持更多自定义参数
    val center = "${locations[0].latitude},${locations[0].longitude}"
    return Uri.parse("comgooglemaps://?center=$center&zoom=10&$markers")
}

// 示例:生成随机十六进制颜色(带透明度前缀0xFF)
private fun generateRandomColor(random: Random): String {
    val red = random.nextInt(256)
    val green = random.nextInt(256)
    val blue = random.nextInt(256)
    return String.format("0xFF%02X%02X%02X", red, green, blue)
}

关键说明

  • 使用comgooglemaps://协议替代geo:,能更好支持标记颜色、标签等自定义参数
  • 标记颜色需传入十六进制格式(如0xFF00FF00表示绿色),可根据TicketLocationDetails的类型替换为固定颜色(比如不同类型对应不同预设色)
  • 每个标记的参数格式为markers=color:颜色值|label:标签文本|纬度,经度,多个标记用&连接
  • 增加了空数据判断,避免无效Intent调用

内容的提问来源于stack exchange,提问作者Kishore Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:16:21