How can you find the centroid of a concave irregular polygon given its vertices in JavaScript?
I want to pass a set of x,y points to a JavaScript function and be given an x,y point.
var my_points = [{x:3,y:1},{x:5,y:8},{x:2,y:9}];
function get_polygon_centroid(points){
// answer
}
var my_centroid = get_polygon_centroid(my_points);
The my_points
variable is only supposed to represent the format of the points to be given, not to represent the specific count of points to be given.
The centroid returned will be a point somewhere inside the polygon.
The end goal would be to add a marker at the centroid of a polygon in a Google Maps V3 application.
For the centroid of the 2D surface (which is likely to be what you need), The best is to start with a little bit of maths.
I adapted it here to your own notation :
function get_polygon_centroid(pts) {
var first = pts[0], last = pts[pts.length-1];
if (first.x != last.x || first.y != last.y) pts.push(first);
var twicearea=0,
x=0, y=0,
nPts = pts.length,
p1, p2, f;
for ( var i=0, j=nPts-1 ; i<nPts ; j=i++ ) {
p1 = pts[i]; p2 = pts[j];
f = p1.x*p2.y - p2.x*p1.y;
twicearea += f;
x += ( p1.x + p2.x ) * f;
y += ( p1.y + p2.y ) * f;
}
f = twicearea * 3;
return { x:x/f, y:y/f };
}