使用Python对GeoJSON进行序列化,使其带有舍入坐标。

3

我希望能够在Python中对GeoJSON FeatureCollections进行有限坐标精度的序列化。

例如,这里有一个FeatureCollection(在Python中用dictlist表示):

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "Liberty Island",
        "area_sqm": 24950.40123456,
        "established": 1875,
        "height_ft": 305
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [ -74.04715418815613, 40.690994683044906 ],
            [ -74.04499769210815, 40.68873311507798 ],
            [ -74.04354929924011, 40.689676800252016 ],
            [ -74.04715418815613, 40.690994683044906 ]
          ]
        ]
      }
    }
  ]
}

我可以使用 json.dumps 进行序列化:
print(json.dumps(fc))

这将打印出 JSON:
{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"name": "Liberty Island", "area_sqm": 24950.40123456, "established": 1875, "height_ft": 305}, "geometry": {"type": "Polygon", "coordinates": [[[-74.04715418815613, 40.690994683044906], [-74.04499769210815, 40.68873311507798], [-74.04354929924011, 40.689676800252016], [-74.04715418815613, 40.690994683044906]]]}}]}

这些坐标太精确了。根据维基百科的说法,7个数字大约是厘米级精度,应该足够好了。而我得到的是纳米级的精度。

我想要将GeoJSON FeatureCollection序列化为仅带有七位数字精度的坐标。请注意,我想使用Python默认的序列化方式处理所有的properties内容:因为值可能是任何类型,所以我无法对所需精度做出普遍性的要求。

我的期望输出格式如下:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "Liberty Island",
        "area_sqm": 24950.40123456,
        "established": 1875,
        "height_ft": 305
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [ -74.0471541, 40.6909946 ],
            [ -74.0449976, 40.6887331 ],
            [ -74.0435492, 40.6896768 ],
            [ -74.0471541, 40.6909946 ]
          ]
        ]
      }
    }
  ]
}
1个回答

0

我不确定你需要什么样的序列化,但是当涉及到FeatureCollection简化时,这应该可以帮助你入门:

import json
from copy import copy


def simplify_geometries(feat_collection):
    new_coll = copy(feat_collection)
    old_features = new_coll['features']
    new_features = []

    for feature in old_features:
        geometry = feature['geometry']
        coords = shorten_arr(geometry['coordinates'])
        geometry['coordinates'] = coords

        new_features.append(feature)

    new_coll['features'] = new_features
    return json.dumps(new_coll)


print(simplify_geometries(
    json.loads('{"type": "FeatureCollection",...')
))

其中shorten_arr是一个简单的递归函数:

def shorten_arr(arr, dec_places=7):
    if not isinstance(arr, list):
        return round(arr, dec_places)

    to_ret = []
    for n in arr:
        if isinstance(n, list):
            n = shorten_arr(n, dec_places)
        to_ret.append(shorten_arr(n, dec_places))
    return to_ret

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接