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.

function simplePolygonCentroid(points)

{

var sumY = 0;

var sumX = 0;

var partialSum = 0;

var sum = 0;

//close polygon
points.push(points[0]);
var n = points.length;

for(var i=0;i<n-1;i++)

{

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);

}

### Like this:

Like Loading...

Awesome! I\’m reusing this code in the VEToolkit. If you are interested in contributing, please let me know.http://codeplex.com/VEToolkit

Great code, here is the same code updated for Bing Maps v7

function simplePolygonCentroid(points) { // param can be either a Bing Map v7 Point class or Location class

var sumY = 0; var sumX = 0; var partialSum = 0; var sum = 0;

//close polygon

points.push(points[0]);

var n = points.length;

for (var i = 0; i < n – 1; i++) {

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 Microsoft.Maps.Location(sumY / 6 / area, sumX / 6 / area);

}