[mapserver-users] PHP/MapScript : Retrieving the centroid of a shape

Stephen Woodbridge woodbri at swoodbridge.com
Tue Jun 4 12:17:06 EDT 2002



LACROIX Gilles wrote:
> 
> I am trying to use PHP/MapScript to display (dynamic) labels on selected
> shapes from a layer. To do so, I need to retrieve the "centroid" of
> these shapes (a basic "middle of the bounding box" algorithm doesn't
> help because the centroid must fall into the shape, whatever the shape
> looks like). Is it possible with MapScript ?

First, the centroid is NOT required to be inside the polygon, think of
an area like the letter "C".

One way to do this is to construct a point layer that can be used as an
annotation layer for labeling the polygons, where the point is the label
location. You could construct this layer using php, perl or C using this
algorithm:

1) get the bounding box of the polygon.
2) set X to the middle of the bounding box
3) intersect every polygon edge with the line X=middle and make a list
of intersection points (most will not instersect)
4) sort the points in Y
5) set the label point to the midpoint of (X,Y1, X, Y2) which is
garanteed to be inside the polygon.

You can adjust this to set Y and intersect for X, based on whether you
have tall narrow or short wide extents. also if you have only a few
poorly placed points you can just edit their location to a more
suitiable position.

Hope this helps,
  -Steve



More information about the mapserver-users mailing list