46

I want to create a polygon from shapely points.

from shapely import geometry
p1 = geometry.Point(0,0)
p2 = geometry.Point(1,0)
p3 = geometry.Point(1,1)
p4 = geometry.Point(0,1)

pointList = [p1, p2, p3, p4, p1]

poly = geometry.Polygon(pointList)

gives me an type error TypeError: object of type 'Point' has no len()

How to create a Polygon from shapely Point objects?

jberrio
  • 972
  • 2
  • 9
  • 20
Sounak
  • 4,803
  • 7
  • 30
  • 48
  • 2
    I submitted an issue on GitHub regarding this: [Inconsistency in creating collections with a sequence of Point's](https://github.com/Toblerity/Shapely/issues/706). They say it's a bug to be fixed. – Georgy May 24 '19 at 14:26
  • 2
    This question is outdated; it does not produce an error anymore. See Adam's answer. – jberrio Sep 30 '20 at 00:38
  • With Shapely 2.0, this raises: `ValueError: Inconsistent coordinate dimensionality` – swiss_knight Jan 19 '23 at 11:07

5 Answers5

75

If you specifically want to construct your Polygon from the shapely geometry Points, then call their x, y properties in a list comprehension. In other words:

from shapely import geometry

poly = geometry.Polygon([[p.x, p.y] for p in pointList])

print(poly.wkt)  # prints: 'POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))'

Note that shapely is clever enough to close the polygon on your behalf, i.e. you don't necessarily have to pass-in the first point again at the end.

songololo
  • 4,724
  • 5
  • 35
  • 49
  • for me it works like poly = Polygon([[p[0].x, p[0].y] for p in pointList]) – Piyush May 30 '16 at 10:28
  • Sounds like you have nested points (multipoint?) or a line instead? – songololo May 30 '16 at 11:13
  • @songololo how can it know how to close the polygon if it only has one x, y location? How does it know how big it is? Is there a way to pass x1, y1, x2, y2 coordinates instead? – mikey Mar 31 '22 at 13:04
25

A Polygon object requires a nested list of numbers, not a list of Point objects.

polygon = Polygon([[0, 0], [1, 0], [1, 1], [0, 1]])
johan
  • 1,664
  • 2
  • 14
  • 30
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
9

In version 1.7a2 they have fixed this.

The code in question will just work.

Link to CHANGES.txt

Adam
  • 1,470
  • 1
  • 17
  • 13
3

The Polygon constructor doesn't expect a list of Point objects but a list of point coordinates.

See https://shapely.readthedocs.io/en/latest/manual.html#polygons

Georgy
  • 12,464
  • 7
  • 65
  • 73
dlask
  • 8,776
  • 1
  • 26
  • 30
-1

You could just do that instead:

p1 = geometry.Point(0,0)
p2 = geometry.Point(1,0)
p3 = geometry.Point(1,1)
p4 = geometry.Point(0,1)

pointList = [p1, p2, p3, p4]
poly = geometry.Polygon([i for i in pointList])
Karantai
  • 73
  • 8