Often it is useful to be able to calculate the center of a polygon. There are several ways to do this. One way is to calculate the average latitude and longitude points of the coordinates that make up the polygon. This method however can result in a point that is no where close to the center of the polygon if there is a large number of points grouped together. A second method is to calculate the center of mass of the polygon which gives us the center of a polygons centroid based on it’s area. This can be done in 3-dimensions to account for the curvature of the earth, however assuming the earth is flat for small areas makes the math far easier. The standard formula for calculating the area of a polygon is as follows:
We can then use this area and calculate the x and y components of the centroid.
We can use these formulas to calculate an approximate centroid of a polygon. The following function that takes in an array of coordinates that represent a polygon and returns a VELatLong object for the centroid.
var sumY = 0;
var sumX = 0;
var partialSum = 0;
var sum = 0;
//close polygon points.push(points); var n = points.length;
partialSum = points[i].Longitude*points[i+1].Latitude - points[i+1].Longitude*points[i].Latitude;
sum += partialSum;
sumX += (points[i].Longitude+points[i+1].Longitude) * partialSum;
sumY += (points[i].Latitude+points[i+1].Latitude) * partialSum;
var area = 0.5*sum;
return new VELatLong(sumY/6/area,sumX/6/area);