I am trying to write a PHP function that will calculate the center of gravity of a polygon.
I\'ve looked at the other similar questions but I can\'t seem to find a s
This was my implementation in Java of the accepted solution, I added an extra conditional check because some of my polygons were flat and had no area, and rather than giving me the midpoint, it was returning (0,0). Thus in this case, I reference a different method which simply averages the vertices. The rounding at the end is because I wanted to keep my output object as integers even though it is imprecise, but I welcome you to remove that bit. Also, since all of my points were positive integers, the check made sense for me, but for you, adding an area check == 0 would also make sense.
private Vertex getCentroid() {
double xsum = 0, ysum = 0, A = 0;
for (int i = 0; i < corners.size() ; i++) {
int iPlusOne = (i==corners.size()-1)?0:i+1;
xsum += (corners.get(i).getX() + corners.get(iPlusOne).getX()) * (corners.get(i).getX() * corners.get(iPlusOne).getY() - corners.get(iPlusOne).getX() * corners.get(i).getY());
ysum += (corners.get(i).getY() + corners.get(iPlusOne).getY()) * (corners.get(i).getX() * corners.get(iPlusOne).getY() - corners.get(iPlusOne).getX() * corners.get(i).getY());
A += (corners.get(i).getX() * corners.get(iPlusOne).getY() - corners.get(iPlusOne).getX() * corners.get(i).getY());
}
A = A / 2;
if(xsum==0 &&ysum==0)
{
area = averageHeight/2;
return getMidpointCenter();
}
double x = xsum / (6 * A);
double y = ysum / (6 * A);
area = A;
return new Vertex((int) Math.round(x), (int) Math.round(y));
}