# POSTGIS get the max length of the polygon and the average width

I have in postgis a polygon type table.

I need to calculate automatically the maximum length of the polygon: And the second one is the average width: I am doubting rigth now if this is possible as although all my polygons will be nearly rectangular in other cases it can be really ambiguous and it is nearly imposible to distinguish between width and height.

Let's see if someone can shed light on this.

Regards,

• It's an interesting question, and it definitely is possible. At the very least you simply draw a line from every vertex to every other, polynomial runtime for sure, but a solution. For more elegant solutions, take a look at gis.stackexchange.com/questions/32552/… – John Powell Jan 30 '15 at 16:24
• Your illustration of "max length" seems clear, but your example "avg width" is not perpendicular to said length. Shouldn't it be? Then you mention "height". All a bit confusing! – Martin F Jan 30 '15 at 16:30
• I think more detail is needed on this concept of average width, in particular with examples of the actual geometries you are using – raphael Jan 30 '15 at 17:30

For the first part of your question: What about ST_LongestLine using the same geometry twice as input?

``````SELECT
ST_Length(ST_LongestLine(
(SELECT geom FROM mylayer WHERE gid=1),
(SELECT geom FROM mylayer WHERE gid=1))
);
``````

For the second part of your question:

Concerning the calculation of the average width of polygons some interesting answers can be found here: How can I calculate the average width of a polygon?

• That's clever, didn't know that function. – John Powell Jan 30 '15 at 17:24
• That's super useful. Is there a way creating a polyline from this resultant longest line? – user1655130 Oct 20 '18 at 9:24

For part one use ST_MaxDistance

Returns the 2-dimensional maximum distance between two linestrings in projected units. If g1 and g2 is the same geometry the function will return the distance between the two vertices most far from each other in that geometry.

Example:

``````SELECT
gid,
ST_MaxDistance(geom, geom) AS "Max Length"
FROM layer
``````