我目前有一个GeoJSON FeatureCollection
,但是我需要在Python语言中对这个文件执行的函数只支持GeoJSON几何对象,如Point
或Polygon
(没有所有的属性和坐标数据)。有没有一种方法可以在Python语言中简单地将GeoJSON FeatureCollection
转换为GeoJSON几何对象?
发布于 2016-03-11 18:41:40
嗯,最简单的方法是循环遍历您的特征集合,并从中提取几何图形。我想你现在已经找到了你问题的答案,因为从那以后就没有另一个帖子了?
发布于 2021-07-25 03:40:12
要拆分GeoJSON特性集合的特性,需要遍历feature元素并导出每个特性。
for f in data['features']:
if f.get("type") == "Feature":
with open(somefile, "w") as out:
json.dump(f, out)
以下Python代码将遍历GeoJSON特性集合并拆分每个特性,将其保存在单独的GeoJSON文件中。
如果源GeoJSON文件有10个要素,则它们将保存在文件中: 1.geojson,2.geojson,...,10.geojson。
import json
import sys
class Splitter:
def __init__(self):
self.count = 0
def check(self, input_file):
print("Input:", input_file)
with open(input_file, encoding="utf-8") as file:
data = json.load(file)
data_type = data.get("type")
if data_type == "FeatureCollection":
for f in data['features']:
obj_type = f.get("type")
if obj_type == "Feature":
self.export_feature(data, f)
else:
print("WARN: non-feature:", obj_type)
elif data_type == "Feature":
print("GeoJSON is already a feature object")
else:
print("WARN: unknown/other type:", data_type)
def export_feature(self, parent, feature):
self.count += 1
name = f"{self.count}.geojson"
print("Output:", name)
if "crs" in parent and "crs" not in feature:
# copy coordinate reference system (CRS) definition from parent
# if not present in feature
feature["crs"] = parent["crs"]
with open(name, "w") as out:
json.dump(feature, out)
##############################################################################
# main #
##############################################################################
if len(sys.argv) < 2:
print("usage: geojson-split.py <file>")
sys.exit(0)
splitter = Splitter()
for f in sys.argv[1:]:
splitter.check(f)
如果需要将GeometryCollection拆分为其组件几何图形,请参阅相关answer。
https://stackoverflow.com/questions/29171316
复制相似问题