Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  83] [ 7]  / answers: 1 / hits: 22527  / 13 Years ago, tue, march 13, 2012, 12:00:00

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.


More From » polygon

 Answers
56

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

[#86865] Monday, March 12, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;