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

升级Google Maps服务19.0.0添加多边形触发ClassCastException

Play Services Maps 19.0.0升级后添加Polygon抛出ClassCastException的解决方案

问题根源

升级com.google.android.gms:play-services-maps从18.0.2到19.0.0后,调用GoogleMap.addPolygon()触发ClassCastException,核心原因是:
19.0.0版本的PolygonOptions对points/holes的类型校验更严格,要求必须是实现Parcelable的真实LatLng实例;而旧版本可能存在隐式兼容逻辑,允许非LatLng的Map对象被转换使用。

从你提供的输出差异也能验证这一点:18.0.2显示的是LatLng实例的原生toString格式,19.0.0显示的是Moshi反序列化生成的LinkedHashTreeMap键值对格式,说明反序列化后得到的不是LatLng对象,而是普通Map集合。

解决方案

1. 编写Moshi的LatLng适配器

强制让Moshi将JSON坐标序列化为LatLng实例,而非默认的Map对象:

class LatLngAdapter {
    @FromJson
    fun fromJson(json: Map<String, Double>): LatLng {
        val lat = json["latitude"] ?: 0.0
        val lng = json["longitude"] ?: 0.0
        return LatLng(lat, lng)
    }

    @ToJson
    fun toJson(latLng: LatLng): Map<String, Double> {
        return mapOf(
            "latitude" to latLng.latitude,
            "longitude" to latLng.longitude
        )
    }
}

创建Moshi实例时添加该适配器:

val moshi = Moshi.Builder()
    .add(LatLngAdapter())
    .build()

2. 修复PolygonOptions构建逻辑

确保传入的points和holes都是List<LatLng>类型的真实实例。如果是从JSON恢复数据,先手动将Map列表转换为LatLng列表:

// 示例:将反序列化得到的Map列表转为LatLng列表
val rawPoints: List<Map<String, Double>> = // 从JSON反序列化的结果
val latLngPoints = rawPoints.map { LatLng(it["latitude"]!!, it["longitude"]!!) }
val polygonOptions = PolygonOptions().addAll(latLngPoints)

3. 无需处理PolygonOptions的混淆字段

问题根源不在PolygonOptions本身,而是其依赖的LatLng类型不符合要求,因此不需要针对混淆后的zza/zzb等字段编写适配器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:47:05