Convert geopandas shapely polygon to geojson

前端 未结 6 1910
猫巷女王i
猫巷女王i 2021-02-18 19: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 acr

相关标签:
6条回答
  • 2021-02-18 19:40

    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

    0 讨论(0)
  • 2021-02-18 19:41

    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))
    
    0 讨论(0)
  • 2021-02-18 19:44

    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

    0 讨论(0)
  • 2021-02-18 19:46

    You can also use PyShp

    import shapefile
    
    with shapefile.Reader("shapefile.shp") as shp:
        geojson_data = shp.__geo_interface__
    

    or

    geojson_data = shapefile.Reader("shapefile.shp").__geo_interface__
    

    example usage:

    >>> geojson_data["type"]
    
    'MultiPolygon'
    
    0 讨论(0)
  • 2021-02-18 19:48

    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"}'
    
    0 讨论(0)
  • 2021-02-18 20:02

    Use the driver provided by fiona:

    data=shapefile.to_file("file.geojson",driver='GeoJSON')
    
    data=geopandas.read_file("file.geojson")
    
    data
    
    0 讨论(0)
提交回复
热议问题