[postgis-users] Longest axis of a polygon
Michael Fuhr
mike at fuhr.org
Tue Jan 31 17:57:21 PST 2006
On Tue, Jan 31, 2006 at 05:01:13PM +1100, Christian Heine wrote:
> > I'm not familiar with solving this problem so maybe this isn't
> > correct or what you need, but could you look for the pair of points
> > on the polygon's (simplified) exterior ring or convex hull separated
> > by the most distance? It would be easy to iterate through the
> > points in a function.
>
> Thanks for the suggestion! I looked at convexhull() and this seems
> to be quite ok for my purposes -
> How do I loop over a set of points in PostGIS/SQL?
Here's a function that I've only minimally tested. As I said, I'm
not familiar with solving this particular problem so corrections
or improvements are welcome. One possible problem is that for
certain geometries the function might return a linestring that lies
entirely outside the geometry, except for the endpoints; a crescent
comes to mind.
CREATE FUNCTION longestaxis(geom geometry) RETURNS geometry AS $$
DECLARE
hull geometry := convexhull(geom);
ering geometry;
len double precision;
maxlen double precision := -1;
maxi integer;
maxj integer;
BEGIN
IF geometrytype(hull) IN ('POINT', 'LINESTRING') THEN
RETURN hull;
END IF;
ering := exteriorring(hull);
FOR i IN 1 .. npoints(ering) - 2 LOOP
FOR j IN i + 1 .. npoints(ering) - 1 LOOP
len := distance(pointn(ering, i), pointn(ering, j));
IF len > maxlen THEN
maxlen := len;
maxi := i;
maxj := j;
END IF;
END LOOP;
END LOOP;
RETURN makeline(pointn(ering, maxi), pointn(ering, maxj));
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
--
Michael Fuhr
More information about the postgis-users
mailing list