如何使用pythongeojson从python转储格式化geoJSON文件?

2024-05-15 20:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python和python geojson创建一个features数组。我附加了一些功能,例如带有工作坐标的多边形。但是,当我转储时,geoJson文件中没有缩进。所有数据都在一行上,mapbox不接受数据

f

features = []
poly = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])


features.append(Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]]))
features.append(Feature(geometry=poly, properties={"country": "Spain"}))


feature_collection = FeatureCollection(features)

with open('myfile.geojson', 'w') as f:
   dump(feature_collection,f)
f.close()

这就是输出的外观。它应该缩进而不是像那样聚集

{“类型”:“特征集合”,“特征”:[{“类型”:“多边形”,“坐标”:[[[2.38,57.322],[23.194,-20.28],-120.43,19.15],[2.38,57.322]]},{“几何”:{“类型”:“多边形”,“坐标”:[[2.38,57.322],[23.194,-20.28],-120.43,19.15],[2.38,57.322]}],类型:{“特征”,“属性”:{“国家”:“西班牙”}}


Tags: 文件数据功能类型geojson特征数组多边形
2条回答

将'indent'参数添加到dump()调用:

with open('myfile.geojson', 'w') as f:
   dump(feature_collection, f, indent=4)

然而,奇怪的是,一段代码不接受所有在一行上的JSON。它同样有效,合法。这是代码中的一个bug。使用“缩进”参数通常只是为了便于阅读

备份一点,有三种类型的GeoJSON对象:

  1. 几何学
  2. 特征
  3. 特色收藏

一个Feature包括一个Geometry,一个FeatureCollection包括一个或多个Features。不能直接将Geometry放在FeatureCollection内,但它必须是Feature

在您共享的示例中,您的FeatureCollection包括一个Feature和一个Geometry(在本例中,是一个Polygon)。在将该Polygon添加到FeatureCollection之前,需要将其转换为Feature

不确定您是否打算拥有两个相同的多边形,但您的示例需要如下所示才能输出有效的GeoJSON:

features = []
poly1 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
poly2 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])

features.append(Feature(geometry=poly1, properties={"country": "Spain"}))
features.append(Feature(geometry=poly2))

feature_collection = FeatureCollection(features)

with open('myfile.geojson', 'w') as f:
   dump(feature_collection,f)
f.close()

压痕在这里不重要

您可以在https://www.rfc-editor.org/rfc/rfc7946上阅读更多关于GeoJSON规范的信息

相关问题 更多 >