14

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?

3 Answers 3

37

A generic solution is to use the shape function. 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)
4
  • Really good answer here!
    – saru
    Dec 4, 2021 at 23:56
  • 1
    This should be the accepted answer. Feb 15, 2022 at 16:52
  • 1
    it doesnt work!
    – Beikeni
    Dec 9, 2022 at 16:56
  • any details on why its not working? Dec 12, 2022 at 10:43
4

Try this,

from itertools import chain


geom = {...}
polygon = Polygon(list(chain(*geom['coordinates']))
1
  • This method should be more accurate I think, because in other answers only first polygon is taken into account, so if a polygon has an inner ring, it will not show up. Jan 30, 2022 at 14:45
2
from shapely.geometry import Polygon
geo = {'type': 'Polygon',
 'coordinates': [[[23.08437310100004, 53.15448536100007],
   [23.08459767900007, 53.15448536100007],
   [23.08594514600003, 53.153587050000056],
   [23.08437310100004, 53.15448536100007]]]}
Polygon([tuple(l) for l in geo['coordinates'][0]])

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.