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

Android Google Map解析JSON为各子行政区绘制多边形方法

问题根因

你的代码存在两个核心问题导致多边形绘制错乱:

  1. 你在循环外定义了全局共享的points列表,遍历每个子行政区时没有清空该列表,后续行政区绘制时会把之前所有行政区的坐标点都包含进去,导致所有多边形边界连为一体。
  2. JSON中存储边界坐标的字段名为polygon_coordinate,代码中直接读取coordinates字段,如果数据模型没有做字段名映射,会无法正确读取对应行政区的边界坐标。
修复方案
  • 取消全局共享的点位列表,处理每个子行政区时单独创建独立的点位集合,从根源上避免不同行政区的坐标互相污染
  • 核对数据模型和JSON字段的映射关系,确保能正确读取每个子行政区的边界坐标
  • 每个子行政区的点位收集完成后,立即绘制对应独立多边形
修正后实现代码
private fun drawSubdistrict() {
    val jsonFileString = readJsonFile(requireContext(), "area_statistic.json")
    val data: AreaStatisticDataModel =
        Gson().fromJson(jsonFileString, AreaStatisticDataModel::class.java)

    // 直接遍历每个子行政区条目,无需提前抽取所有坐标
    data.statistic?.forEach { subdistrictItem ->
        // 为当前子行政区创建独立的点位列表,和其他行政区数据完全隔离
        val currentDistrictPoints = mutableListOf<LatLng>()
        // 读取当前行政区的边界坐标,注意字段名要和JSON返回的polygon_coordinate匹配
        subdistrictItem?.polygonCoordinate?.forEach { coordinate ->
            coordinate?.let {
                currentDistrictPoints.add(LatLng(it.lat!!, it.long!!))
            }
        }
        // 为当前子行政区绘制独立多边形
        mMap.addPolygon(
            PolygonOptions()
                .addAll(currentDistrictPoints)
                .fillColor(0x22FF0000)
                .strokeColor(0xFFFF0000) // 可选:添加红色描边,更方便区分行政区边界
        )
    }
}
额外注意

如果你的Kotlin数据类中坐标字段命名和JSON字段不一致,需要添加@SerializedName注解做映射,参考示例:

data class SubdistrictStatisticItem(
    val subdistrict: String?,
    val total_crime: Int?,
    // 映射JSON中的polygon_coordinate字段
    @SerializedName("polygon_coordinate")
    val polygonCoordinate: List<CoordinatesItem>?
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 19:31:41