Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert from a list of Points to a Polygon #21

Closed
ispmarin opened this issue Aug 24, 2012 · 3 comments
Closed

Convert from a list of Points to a Polygon #21

ispmarin opened this issue Aug 24, 2012 · 3 comments

Comments

@ispmarin
Copy link

Hi all,

I didn't find a mailing list of a forum, so I'm going to ask here. Is there a "canonical" form to convert from a list of Points to a Polygon? For example,

list_points = []
vertices = [Point(1,1), Point(2,2), Point(3,3)]
for i in xrange(len(vertices)):
    list_points.append(vertices[i])
polygon = Polygon(list_points)

This code doesn't work. I had to use convex_hull:

poly = MultiPoint(list_points).convex_hull

What is not exaclty what I'm looking for.

Thanks for the patience and the good work!

@sgillies
Copy link
Contributor

Here's thing: polygon rings (instances of LinearRing) aren't defined by Points, they are defined by sequences of coordinate tuples. Points and coordinates are different things to Shapely. You need to pass the coordinates of the points to the Polygon constructor. Like this:

>>> points = [Point(0,0), Point(2,2), Point(2,0)]
>>> coords = sum(map(list, (p.coords for p in points)), [])
>>> poly = Polygon(coords)
>>> poly.area
2.0

@kannes
Copy link
Contributor

kannes commented May 2, 2017

As I keep googling for this every now and then, here is how I prefer to do it (I find it more readable like this):

>>> points = [Point(0,0), Point(2,2), Point(2,0)]
>>> coords = [(p.x, p.y) for p in points]
>>> poly = Polygon(coords)
>>> poly.area
2.0

timeit says things might be getting cached but @sgillies's approach seems consistently 2/3 faster (~65µs mine vs ~45µs his) so if you need super ultra hardcore performance for gazillions of points or polys, consider that.

@snorfalorpagus
Copy link
Member

Ever so slightly faster again:

points = [Point(0,0), Point(2,2), Point(2,0)]
coords = [p.coords[:][0] for p in points]
poly = Polygon(coords)
poly.area

jorisvandenbossche pushed a commit to jorisvandenbossche/shapely that referenced this issue Nov 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants