Convert geopandas shapely polygon to geojson

这一生的挚爱 提交于 2020-05-26 10:34:24

问题


I created a circle using geopandas and it returned a shapely polygon:

POLYGON: ((...))

I want this same polygon as a geojson object. I ran across this:

shapely.geometry.mapping(shapelyObject)

which returns this:

{'type': 'Polygon', 'coordinates': (((570909.9247264927, 125477.71811034005)...}

But when I try to map this in mapbox it does not show anything. I think maybe it is not fully a geojson object.


回答1:


If you don't want to create this dict manually, you can also rely on geopandas creating it:

In [1]: import shapely.geometry

In [2]: import geopandas

In [3]: shapely_polygon = shapely.geometry.Polygon([(0, 0), (0, 1), (1, 0)])

In [4]: geopandas.GeoSeries([shapely_polygon]).__geo_interface__
Out[4]: 
{'bbox': (0.0, 0.0, 1.0, 1.0),
 'features': [{'bbox': (0.0, 0.0, 1.0, 1.0),
   'geometry': {'coordinates': (((0.0, 0.0),
      (0.0, 1.0),
      (1.0, 0.0),
      (0.0, 0.0)),),
    'type': 'Polygon'},
   'id': '0',
   'properties': {},
   'type': 'Feature'}],
 'type': 'FeatureCollection'}

(Note that this gives a FeatureCollection and not a single feature.)

Or to a string (or file):

In [4]: geopandas.GeoSeries([shapely_polygon]).to_json()
Out[4]: '{"features": [{"bbox": [0.0, 0.0, 1.0, 1.0], "geometry": {"coordinates": [[[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]], "type": "Polygon"}, "properties": {}, "id": "0", "type": "Feature"}], "bbox": [0.0, 0.0, 1.0, 1.0], "type": "FeatureCollection"}'



回答2:


Something like this should do the trick:

features = [{'type': 'Feature', 'properties': {}, 'geometry': shapely.geometry.mapping(shapelyObject)}]

Now you can try to map features in mapbox. Hope this helps.

Reference: https://gis.stackexchange.com/questions/213717/geometry-workflow-from-shapely-to-geojson




回答3:


To write a standard geojson object using pandas you shall use the driver provided by fiona as recommended in the documentation

gdf.to_file('path/to/file.geojson', driver='GeoJSON')

See import fiona; fiona.supported_drivers for a list of fully supported drivers




回答4:


Shapely returns a python dict where all the coordinates are in tuples. You need to convert to JSON in order for mapbox, etc... to properly accept it.

json.dumps(shapely.geometry.mapping(shapelyObject))


来源:https://stackoverflow.com/questions/51486454/convert-geopandas-shapely-polygon-to-geojson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!