# Calculate polygon main dircetion and create line from it - POSTGIS

I would like to find out the orientation of a polygon and create a line of that direction.

See image below. ## 1 Answer

A true weighted orientation is non-trivial; I'd say the `ST_LongestLine` within a polygon is the best approximation, and will yield consistent results over multiple iterations.

• To get your initial Polygons with a column `dir` in degrees of the main orientation:

``````SELECT <some_column_1>,
...
<some_column_n>,
DEGREES(ST_Azimuth(ST_StartPoint(ll), ST_EndPoint(ll))) AS dir,
<geom_column>
FROM (
SELECT <some_column_1>,
...
<some_column_n>,
<geom_column>,
ST_LongestLine(<geom_column>, <geom_column>) AS ll
FROM <polygon_layer>
) q;
``````
• To get the Linestring of the main orientation, with column `dir`:

``````SELECT *,
DEGREES(ST_Azimuth(ST_StartPoint(geom), ST_EndPoint(geom))) AS dir
FROM (
SELECT <some_column_1>,
...
<some_column_n>,
ST_LongestLine(<geom_column>, <geom_column>) AS geom
FROM <polygon_layer>
) q;
``````
• if you have the `SFCGAL` backend you could create the medial axis (`ST_ApproximateMedialAxis`) and average the azimuths of all resulting line segments based on their weighted length to the total length of the medial axis multiline. I might add this as another answer later (or someone else drops by with this idea), would need some testing first, though (and some time to do that...). – ThingumaBob Oct 23 '18 at 15:22
• Ok great - if you could, that would be great - thanks – user1655130 Oct 23 '18 at 15:54
• @user1655130 out of interest I might...but that might just as well not yield proper results. this above, however, does. – ThingumaBob Oct 23 '18 at 15:59
• @user1655130 not quite sure what you mean, but you don't need the extra `a.geom` in the sub-query: `longline` in your example is the line geometry already. for why `dir` is empty: you are using `a.geom` in `ST_StartPoint` where it should be `longline`, too. ah, or do you want the polygon geometry with an extra field for `dir`? – ThingumaBob Oct 24 '18 at 12:08
• @user1655130 I updated the query to return the polygon geometry instead of the line geometry – ThingumaBob Oct 24 '18 at 12:14