# Estimating direction of travel of road line segment based on long/lat in PostGIS?

Well, this seems pretty simple but haven't been answered cleanly in previous relevant questions for example:

I have a large dataset of road network (`multi-linestrings`) of an area of interest converted to linestrings using `ST_Dump()`. For each `linestring`, I would like to estimate "the direction of travel" (north to south, east to west and vice versa) based on extracted X,Ys. Two sample linestrings are shown below.

For the above sample linestrings, `ST_StartPoint()` and `ST_EndPoint()` return the start and end points (`Xs`, `Ys`) of the same. Based on these `X`,`Ys` (long/lat), how do I estimate the direction of travel of these linestrings?

UPDATE

Assuming that I have my area of interest in the northern hemisphere. Following diagram may "represent" the "direction of travel" (from north to south).

## 1 Answer

You are looking for ST_Azimuth

http://postgis.net/docs/manual-2.4/ST_Azimuth.html

• Thank you for your words =) Please correct me if I am terribly wrong. ST_Azimuth(ST_StartPoint(geom), ST_EndPoint(geom)) estimates the north-based azimuth (direction) of linestring. While, I am trying to estimate whether linestring is north-to-south and vice versa etc. based on latitudes/longitudes differences. Is there something wrong with this approach? – khajlk Jan 2 '18 at 11:23
• As suggested here: gis.stackexchange.com/questions/75554/… linestring's "direction of travel" can be determined by the order of coordinates as well. – khajlk Jan 2 '18 at 11:24
• I might misunderstand what you want. As I understand it toy want the direction of theline from start point to end point. That you get from ST_Azimuth, both for geometry and geography type. From that value you can tell if the direction is north or south or east or west. You can have a table with ranges defining the directions and join the answer against that if you want it expressed in text. A table with fields for min radians, max radians and text representation. Or is there a "direction of travel" based on something else than start point and end point that you are searching? – Nicklas Avén Jan 2 '18 at 12:21
• My bad! Probably, I was unable to provide better explanations. I am aware that ST_Azimuth() would return me line segment's direction in degrees or radians. Basically, this is not what I am looking for. I wanted to identify whether line segment is towards north-south (in the first case, for example) or not based on long/lat differences i.e., what is the "direction of travel" based on order/difference of coordinates of linestring. I will add one more figure to help clarify "direction of travel". – khajlk Jan 2 '18 at 12:34
• I am afraid I still miss something. From your last example, you will get approx pi as azimuth, which tells you that the direction between the 2 points is towards south. Isn't that want you want to find out? – Nicklas Avén Jan 3 '18 at 12:50