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 solution to this.
My problem is that I need to be able to calculate the center of gravity for both regular and irregular polygons and even self intersecting polygons.
Is that possible?
I've also read that: http://paulbourke.net/geometry/polyarea/ But this is restricted to non self intersecting polygons.
How can I do this? Can you point me to the right direction?
in cold c++ and while assuming that you have a Vec2 struct with x and y properties :
and in javascript :
or in good old c and while assuming that you have a Point struct with x and y properties :
Since we are all having so much fun implementing this algo in different languages, here is my version I knocked up for Python:
In php:
Read more at:
PHP: How to determine the center of a Polygon
Swift 4, based on the c answer given above
The center of gravity (also known as "center of mass" or "centroid" can be calculated with the following formula:
Extracted from Wikipedia: The centroid of a non-self-intersecting closed polygon defined by n vertices (x0,y0), (x1,y1), ..., (xn−1,yn−1) is the point (Cx, Cy), where
and where A is the polygon's signed area,
Example using VBasic:
For more info check this website or Wikipedia.
Hope it helps.
Regards!
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.