python构建json_使用Python构建GeoJSON

I want to generate dynamically a geoJSON with a variable number of polygons. Example for 2 polygons:

{

"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": {}}

]

}

I have a function which gives me the list of coordinates for each polygon, so I can create a list of polygons, so I am able to build the geoJSON iterating it with a for loop.

The problem is that I don't see how to do it easily (I thought for example in returning the list as a string, but building the geoJSON as a string looks like a bad idea).

I have been suggested this very pythonic idea:

geo_json = [ {"type": "Feature",,

"geometry": {

"type": "Point",

"coordinates": [lon, lat] }}

for lon, lat in zip(ListOfLong,ListOfLat) ]

But since I am adding a variable number of Polygons instead of a list of points, this solutions does not seem suitable. Or at least I don't know how to adapt it.

I could build it as a string, but I'd like to do it in a smarter way. Any idea?

解决方案

If you can get the libraries installed, django has some good tools for dealing with geometry objects, and these objects have a geojson attribute, giving you access to the GeoJSON representation of the object:

>>> 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 can also accept a list of geometry objects:

>>> polys = []

>>> for i in range(5):

... poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )

... polys.append(poly)

...

>>> gc = GeometryCollection(polys)

Update 2019:

shapely with shapely-geojson is now available can may be more easily to introduce as it doesn't required django.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值