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

Android GoogleMaps:如何保持GeoJsonLayer.features与原GeoJSON文件顺序一致?

问题描述

我有一个名为location的GeoJSON文件,内容如下:

{"type":"FeatureCollection", "features":[{"type":"Feature","properties":{"name":"West"}},{"type":"Feature","properties":{"name":"East"}},{"type":"Feature","properties":{"name":"North"}}]}

通过以下代码加载:

var geoJsonLayer = GeoJsonLayer(googleMap, R.raw.location, this)

geoJsonLayer.features.forEach {
   print(it.properties)
}

发现geoJsonLayer.features的顺序变为:

{"East","West","North"}

官方文档未说明该方法是否随机返回feature元素,我希望遍历geoJsonLayer.features时能获取与原location文件一致顺序的properties,请问有解决办法吗?

解决办法
  • 手动解析GeoJSON文件,保留原始顺序
    Google Maps Android Utils的GeoJsonLayer内部大概率使用了无序集合存储Features,导致原始顺序丢失。你可以用JSON解析库(如Gson、Moshi)直接读取并解析原始文件,得到有序的Feature列表:
// Gson示例代码
val gson = Gson()
val jsonContent = resources.openRawResource(R.raw.location).bufferedReader().readText()
val featureCollection = gson.fromJson(jsonContent, FeatureCollection::class.java)

// 遍历有序的features列表
featureCollection.features.forEach {
    print(it.properties)
}

// 对应的数据类定义
data class FeatureCollection(
    val type: String,
    val features: List<Feature>
)

data class Feature(
    val type: String,
    val properties: Properties
)

data class Properties(
    val name: String
)
  • 给Features添加自定义顺序标识
    在原始GeoJSON的每个Feature的properties中添加order字段标记原始顺序:
{"type":"FeatureCollection", "features":[
    {"type":"Feature","properties":{"name":"West", "order":0}},
    {"type":"Feature","properties":{"name":"East", "order":1}},
    {"type":"Feature","properties":{"name":"North", "order":2}}
]}

加载后通过order字段排序再遍历:

geoJsonLayer.features.sortedBy { it.properties["order"] as Int }.forEach {
    print(it.properties)
}
  • 修改GeoJsonLayer源码(不推荐)
    如果必须依赖GeoJsonLayer,可以查看其源码,找到存储Features的集合(比如HashSet这类无序容器),替换为ArrayList等有序集合。但这种方式需要依赖库源码,后续版本更新会导致修改失效,维护成本较高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:55:25