VB Snippet - Math - Algorithm for the area of any polygon
VB Code:
Public Function Area(xpoly, ypoly, npoly)
'***********************************************************************
'Calculates the area of a closed contour (polygon) of any shape
'defined by xpoly(i),ypoly(i) with i=1,2,...,npoly
'The last point must close the contour, i.e.
'xpoly(1)=xpoly(npoly) & ypoly(1)=ypoly(npoly)
'Minimum npoly is 4 (i.e. a triangle)
'***********************************************************************
Dim a As Single
'Check for minimum num. of pts.
If npoly < 4 Then
Area = 0
Exit Function
End If
a = 0 'Initialize area
For i = 1 To npoly - 1
a = a + xpoly(i) * (ypoly(i + 1) - ypoly(i)) - ypoly(i) * (xpoly(i + 1) - xpoly(i))
Next
Area = 0.5 * a
End Function
Warning: error spotted and corrected
I have found that this function I posted some time ago in the VB code bank for area calculations was wrong and returned incorrect results (in some cases).
I thought it was working fine when I first checked it because the inaccuracies were small and thus difficult to spot for polygons with a large number of vertices, but then I found it failed in the most trivial cases.
I have re-edited the post and rewritten the code. Now the function is much simpler (and hopefully correct). I apologize for any inconveniences.