Android Google 地图:GeoJson 填充颜色不起作用

Android Google Maps: GeoJson fill color not working

我用 geojson.io 创建了 GeoJson:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "stroke": "#555555",
        "stroke-width": 1,
        "stroke-opacity": 1,
        "fill": "#cc1414",
        "fill-opacity": 0.5
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              38.91359567642212,
              47.25578268604025
            ],
            [
              38.91415894031525,
              47.25578268604025
            ],
            [
              38.91415894031525,
              47.25588827416263
            ],
            [
              38.91359567642212,
              47.25588827416263
            ],
            [
              38.91359567642212,
              47.25578268604025
            ]
          ]
        ]
      }
    }
  ]
}

属性中有填充颜色:

"properties": {
            "stroke": "#555555",
            "stroke-width": 1,
            "stroke-opacity": 1,
            "fill": "#cc1414",
            "fill-opacity": 0.5
          }

然后我将它从字符串转换为 JSONObject,如下所示:JSONObject(geoJsonString),这就是我将图层应用于地图的方式:

fun drawPolygons(jsonObj: JSONObject) {
        map?.let { map ->
            val layer = GeoJsonLayer(map, jsonObj)
            layer.addLayerToMap()
        }
    }

但是 Google 地图完全忽略了所有属性。没有填充颜色,没有描边宽度。我需要从 geojson 字符串中应用它,没有代码。怎么做?

GeoJSON 中的属性只是 key/value 对的集合。您不应期望它们会自动呈现为要素样式。您的任务是读取要素的属性并将它们应用为样式。

您可以循环遍历功能获取属性的值并应用相应的样式。查看显示如何设置多种多边形样式的代码快照

fun drawPolygons(jsonObj: JSONObject) {
    map?.let { map ->
        val layer = GeoJsonLayer(map, jsonObj)
        for (feature in layer.features) {
            val polygonStyle = GeoJsonPolygonStyle()
            if (feature.hasProperty("stroke")) {
                polygonStyle.strokeColor = feature.getProperty("stroke")
            }
            if (feature.hasProperty("stroke-width")) {
                polygonStyle.strokeWidth = feature.getProperty("stroke-width")
            }
            if (feature.hasProperty("fill")) {
                polygonStyle.fillColor = feature.getProperty("fill")
            }
            feature.polygonStyle = polygonStyle
        }
        layer.addLayerToMap()
    }
}

有关 Android Maps Utils 库及其 类 的更多详细信息,您可以参考位于

的 JavaDoc

https://www.javadoc.io/doc/com.google.maps.android/android-maps-utils/latest/com/google/maps/android/data/geojson/GeoJsonFeature.html

尽情享受吧!