Polygon area calculation using Latitude and Longitude generated from Cartesian space and a world file
I checked on internet for various polygon area formulas(or code) but did not find any one good or easy to implement.
Now I have written the code snippet to calculate area of a polygon drawn on earth surface. The polygon can have n vertices with each vertex has having its own latitude longitude.
Few Important Points
- The array input to this function will have "n + 1" elements. The last element will have same values as that of first one.
- I have written very basic C# code, so that guys can also adapt it in other language.
- 6378137 is the value of earth radius in metres.
The output area will have unit of square metres
private static double CalculatePolygonArea(IList<MapPoint> coordinates) { double area = 0; if (coordinates.Count > 2) { for (var i = 0; i < coordinates.Count - 1; i++) { MapPoint p1 = coordinates[i]; MapPoint p2 = coordinates[i + 1]; area += ConvertToRadian(p2.Longitude - p1.Longitude) * (2 + Math.Sin(ConvertToRadian(p1.Latitude)) + Math.Sin(ConvertToRadian(p2.Latitude))); } area = area * 6378137 * 6378137 / 2; } return Math.Abs(area); } private static double ConvertToRadian(double input) { return input * Math.PI / 180; }
I am modifying a Google Map so that a user can calculate the area of a polygon by clicking the vertices. It wasn't giving correct areas until I made sure the Math.cos(latAnchor) was in radians first
So:
double xPos = (lon-lonAnchor)*( Math.toRadians( 6378137 ) )*Math.cos( latAnchor );
became:
double xPos = (lon-lonAnchor)*( 6378137*PI/180 ) )*Math.cos( latAnchor*PI/180 );
where lon, lonAnchor and latAnchor are in degrees. Works like a charm now.
1% error seems a bit high due to just your approximation. Are you comparing against actual measurements or some ideal calculation? Remember that there is error in the GPS as well that might be contributing.
If you want a more accurate method for doing this there's a good answer at this question. If you're going for a faster way you can use the WGS84 geoid instead of your reference sphere for converting to cartesian coordinates (ECEF). Here's the wiki link for that conversion.