Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert geojson to shapely polygon?

i have a geoJSON

geo = {'type': 'Polygon',
 'coordinates': [[[23.08437310100004, 53.15448536100007],
   [23.08459767900007, 53.15448536100007],
   [23.08594514600003, 53.153587050000056],
   (...)
   [23.08437310100004, 53.15448536100007]]]}

and i want to use these coordinates as an input to shapely.geometry.Polygon. The problem is that Polygon only accepts tuple values, meaning i have to convert this geojson to a polygon. When i try to input this type of data into a Polygon there's an error ValueError: A LinearRing must have at least 3 coordinate tuples

I tried this:

[tuple(l) for l in geo['coordinates']]

but this dosen't quite work since it only returns this

[([23.08437310100004, 53.15448536100007],
  [23.08459767900007, 53.15448536100007],
  (...)
  [23.08437310100004, 53.15448536100007])]

and what i need is this (i think it's a tuple)

([(23.08437310100004, 53.15448536100007),
  (23.08459767900007, 53.15448536100007),
  (...)
  (23.08437310100004, 53.15448536100007)])

is there a function for this?

like image 627
adamDud Avatar asked Dec 21 '25 11:12

adamDud


2 Answers

A generic solution is to use the shape function:

Returns a new, independent geometry with coordinates copied from the context.

This works for all geometries not just polygons.

from shapely.geometry import shape
from shapely.geometry.polygon import Polygon

geo: dict = {'type': 'Polygon',
   'coordinates': [[[23.08437310100004, 53.15448536100007],
   [23.08459767900007, 53.15448536100007],
   [23.08594514600003, 53.153587050000056],
   [23.08437310100004, 53.15448536100007]]]}
polygon: Polygon = shape(geo)
like image 151
bensentropy Avatar answered Dec 23 '25 01:12

bensentropy


Try this,

from itertools import chain


geom = {...}
polygon = Polygon(list(chain(*geom['coordinates']))
like image 21
Crash0v3rrid3 Avatar answered Dec 23 '25 01:12

Crash0v3rrid3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!