Rom*_*dgz 8 python json dictionary geojson
我想生成具有可变数量多边形的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": {}}
]
}
Run Code Online (Sandbox Code Playgroud)
我有一个函数,它给我每个多边形的坐标列表,所以我可以创建一个多边形列表,所以我能够构建geoJSON用for循环迭代它.
问题是我没有看到如何轻松地做到这一点(我想例如将列表作为字符串返回,但将geoJSON构建为字符串看起来是个坏主意).
我被建议这个非常pythonic的想法:
geo_json = [ {"type": "Feature",,
"geometry": {
"type": "Point",
"coordinates": [lon, lat] }}
for lon, lat in zip(ListOfLong,ListOfLat) ]
Run Code Online (Sandbox Code Playgroud)
但由于我添加了可变数量的多边形而不是点列表,因此这种解决方案似乎不合适.或者至少我不知道如何适应它.
我可以把它建成一个字符串,但我想以更聪明的方式做到这一点.任何的想法?
cri*_*oss 16
有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"}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
如果可以安装库,则django有一些用于处理几何对象的好工具,并且这些对象具有geojson
属性,可让您访问该对象的GeoJSON表示形式:
https://docs.djangoproject.com/zh-CN/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 ] ] ] } ] }'
Run Code Online (Sandbox Code Playgroud)
GeometryCollection也可以接受几何对象列表:
>>> polys = []
>>> for i in range(5):
... poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
... polys.append(poly)
...
>>> gc = GeometryCollection(polys)
Run Code Online (Sandbox Code Playgroud)
更新2019:
匀称与匀称,以GeoJSON现已能可能会更容易,因为它不要求Django的介绍。
归档时间: |
|
查看次数: |
18989 次 |
最近记录: |