Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert geopandas shapely polygon to geojson

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.

like image 750
conv3d Avatar asked Jul 23 '18 20:07

conv3d


2 Answers

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"}'
like image 57
joris Avatar answered Nov 10 '22 00:11

joris


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))
like image 22
Alex Carruthers Avatar answered Nov 09 '22 23:11

Alex Carruthers