Area of Polygon using Shoelace formula.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Area of Polygon using Shoelace formula
# http://en.wikipedia.org/wiki/Shoelace_formula
# FB - 20120218
# corners must be ordered in clockwise or counter-clockwise direction
def PolygonArea(corners):
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corners[i][1]
area = abs(area) / 2.0
return area
# examples
corners = [(2.0, 1.0), (4.0, 5.0), (7.0, 8.0)]
print PolygonArea(corners)
corners = [(3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)]
print PolygonArea(corners)
|
Tags: math, mathematics
If the corners of the polygon are not sorted then you can sort them first using this:
The above function moves the polygon to origin and adds angles to each corner. The area calculated will still be correct (when using PolygonArea(PolygonSort(corners))). But if you like corners to be sorted w/o changing the corners then you can use this one: