Calculate the angle between line segments in a multilinestring or linestring in QGIS

I need to calculate the angle between line segments in a long chain of linestring as in the figure below:

The way I approached this is:

1. I assigned the id to the feature using:`\$id`

2. Now each feature is assigned a unique id, I calculated the azimuth of each line segment using:

``````CASE
WHEN ((yat(-1)-yat(0)) = 0 and (xat(-1) - xat(0)) >0) THEN 90
WHEN ((yat(-1)-yat(0)) = 0 and (xat(-1) - xat(0)) <0) THEN 270
ELSE (atan((xat(-1)-xat(0))/(yat(-1)-yat(0)))) * 180/pi() +
(180 * (((yat(-1)-yat(0)) < 0) + (((xat(-1)-xat(0)) < 0 AND (yat(-1) - yat(0)) > 0)*2)))
END
``````
1. Then, I calculated the angle difference between the consecutive if as:
``````attributes(
get_feature_by_id(
@layer ,
\$id + 1
)
)['Azimuth'] - "Azimuth"
``````

The main issue with my approach is the id might not always be assigned to the consecutive line segment. So there could be a simpler way to find the angle between the line segments in a long chain of linestring.

• Check this : gis.stackexchange.com/questions/397497/… Commented Dec 24, 2022 at 12:08
• What do you want to do with the resulting angles?
– Bera
Commented Dec 24, 2022 at 15:00
• Use these angles for modeling purposes in project Commented Dec 25, 2022 at 16:01
• The solution in the above link is not valid to linestring. While using 'point_n(geometry, index)' the index value 1 and 2 are only possible. Only two vertices in one line feature. Commented Dec 26, 2022 at 13:02
• Now you just have to merge the lines that are connected to get a linestring. If you label this linestring with the second expression in the answer linked above (the one starting with `array_foreach (...`, you get the left hand side angle at each but the first and last vertex, see: i.sstatic.net/iGpjH.png - about disconnected features: this is a separate question and should be asked separately - and similiar questions have been asked before on this site. Commented Dec 26, 2022 at 15:45