Skip to content

Instantly share code, notes, and snippets.

@pierdom
Created August 17, 2018 08:17
Show Gist options
  • Save pierdom/20a1b90f9e104dd733d1c7f26cc1eb13 to your computer and use it in GitHub Desktop.
Save pierdom/20a1b90f9e104dd733d1c7f26cc1eb13 to your computer and use it in GitHub Desktop.
[Convert a shapely Polygon to GeoJson using GeoPandas] from: https://stackoverflow.com/questions/51486454/convert-geopandas-shapely-polygon-to-geojson #python #datascience #gis
In [1]: from shapely.geometry import Point
In [2]: import geopandas as gpd
In [3]: shapely_polygon = Polygon([(0, 0), (0, 1), (1, 0)])
In [4]: gpd.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'}
@habibutsu
Copy link

import shapely
import json

shapely_polygon = shapely.geometry.Polygon([(0, 0), (0, 1), (1, 0)])
print(
    json.dumps(
        shapely.geometry.mapping(shapely_polygon),
        indent=4
    )
)

Output

{
    "type": "Polygon",
    "coordinates": [
        [
            [
                0.0,
                0.0
            ],
            [
                0.0,
                1.0
            ],
            [
                1.0,
                0.0
            ],
            [
                0.0,
                0.0
            ]
        ]
    ]
}

@feromes
Copy link

feromes commented Dec 30, 2021

Excelent! Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment