我想动态生成一个具有可变数量多边形的geoJSON。 2个多边形的示例:
{
"type": "FeatureCollection",
"features": [
{"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates":
[[11.0878902207, 45.1602390564],
[0.8251953125, 41.0986328125],
[7.63671875, 48.96484375],
[15.01953125, 48.1298828125]]
},
{
"type": "Polygon",
"coordinates":
[[11.0878902207, 45.1602390564],
[14.931640625, 40.9228515625],
[11.0878902207, 45.1602390564]]
}
]
},
"type": "Feature",
"properties": {}}
]
}
我有一个函数,它给出了每个多边形的坐标列表,因此我可以创建一个多边形列表,这样我就可以构建geoJSON,用for循环迭代它。
问题在于我不知道如何轻松地做到这一点(我想例如将列表作为字符串返回,但将geoJSON构建为字符串看起来不错)。
我被建议这个非常pythonic的想法:
geo_json = [ {"type": "Feature",,
"geometry": {
"type": "Point",
"coordinates": [lon, lat] }}
for lon, lat in zip(ListOfLong,ListOfLat) ]
但是由于我添加了可变数量的多边形而不是点列表,因此这种解决方案似乎不合适。或者至少我不知道如何适应它。
我可以把它建成一个字符串,但我想以更聪明的方式做到这一点。有什么想法吗?
答案 0 :(得分:13)
有python-geojson库(https://github.com/frewsxcv/python-geojson),它似乎也使这项任务变得更加容易。库页面中的示例:
>>> from geojson import Polygon
>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...]]], "type": "Polygon"}
答案 1 :(得分:7)
point
,因此它与构造polygon
对象非常相似。json.dumps
将python对象转换为字符串类似的东西:
geos = []
for longs,lats in LongLatList
poly = {
'type': 'Polygon',
'coordinates': [[lon,lat] for lon,lat in zip(longs,lats) ]
}
geos.append(poly)
geometries = {
'type': 'FeatureCollection',
'features': geos,
}
geo_str = json.dumps(geometries) // import json
答案 2 :(得分:6)
如果你可以安装库,django有一些很好的工具来处理几何对象,这些对象有一个geojson
属性,让你可以访问对象的GeoJSON表示:
https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/
>>> from django.contrib.gis.geos import Polygon, Point, MultiPoint, GeometryCollection
>>>
>>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
>>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
>>> gc.geojson
u'{ "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [ 0.0, 0.0 ] }, { "type": "MultiPoint", "coordinates": [ [ 0.0, 0.0 ], [ 1.0, 1.0 ] ] }, { "type": "Polygon", "coordinates": [ [ [ 0.0, 0.0 ], [ 0.0, 1.0 ], [ 1.0, 1.0 ], [ 0.0, 0.0 ] ] ] } ] }'
GeometryCollection还可以接受几何对象列表:
>>> polys = []
>>> for i in range(5):
... poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
... polys.append(poly)
...
>>> gc = GeometryCollection(polys)