Edv Beq
Edv Beq

Reputation: 1000

Find polygon centroid with Shapely given vertices with lat, lon

Trying to find the centroid of Polygon with Shapely but I do not understand how to tell the library that the vertices are (lon, lat). Perhaps I need to set a projection?

Here is my code:

from shapely.geometry import Polygon, Point

# LON, LAT
vertices = [
    Point(-79.8726944444444, 8.68505555555556),
    Point(-79.8733888888889, 8.50419444444444),
    Point(-79.54552777777779, 8.68386111111111),
    Point(-79.54622222222221, 8.503),
    Point(-79.8726944444444, 8.68505555555556),
]

p1 = Polygon(vertices)
centroid = p1.centroid
print(centroid)

# POINT (-1805804163717.8823 6592764402.930745) 

The result is clearly wrong.

Upvotes: 0

Views: 1746

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54668

It's a degenerate shape. It's bowtie that crosses itself. Shapely can't handle that.

Shapely does allow a polygon to narrow itself to zero width at one spot. If you reorganize the data by including the center point, it works.

import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point

# LON, LAT
vertices = [
    (-79.8726944444444, 8.68505555555556),
    (-79.8733888888889, 8.50419444444444),
    (-79.7091111111111, 8.594625),
    (-79.54622222222221, 8.503),
    (-79.54552777777779, 8.68386111111111),
    (-79.7091111111111, 8.594625),
    (-79.8726944444444, 8.68505555555556)
]

p1 = Polygon(vertices)
print(p1)
print(p1.area)
print(p1.bounds)
print(p1.centroid)

plt.plot( [v[0] for v in vertices], [v[1] for v in vertices] )
plt.show()

Upvotes: 1

Related Questions