Wednesday, December 4, 2013

PHP: Calculate the centroid of a polygon

A project I've been working on, generates point markers onto a map. But the interesting part, is how I populate that database of points. It's a series of "drivers" for connecting to ArcGIS REST API, OGC WFS, CartoDB, and so on. More on that as it develops...

A need that came up today, was that this particular layer, being served from ArcGIS REST, is polygons and we need points. Normally I would calculate the centroid and use that... but this specific software is being developed on a plain web host: no GEOS or OGR, no PostGIS... just plain ol' PHP.

Some Reading... then Writing


So I did some reading:
http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon

And wrote this, a pure PHP function for calculating the signed area of a polygon, and then the centroid of the polygon:
https://github.com/gregallensworth/PHP-Geometry/blob/master/Polygon.php

Caveats


As described in the file, this is specific to our sorts of use cases: park boundaries, city boundaries, and the like. If the polygon is self-intersecting (that's a no-no) it may be wrong. If it's an L shape it may come up wrong too. And if it's a multipolygon and those rings overlap, it'll double-count the area, as it's not smart enough to find intersecting area between two rings and subtract it out (and this incorrect area may affect the centroid placement).

But, it does what we need it to do, and it may work for you. Enjoy!


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.