How to calculate the angle at which two lines intersect in PostGIS?
I had the epiphany. It is rather mundane. I was leaving out one essential piece of information for PostGIS to calculate the right angle.
What I was calculating was the angle between only the two points intersecting the small buffer exterior. To calculate the angle of the intersection, I need to calculate both angles between both points on the buffer exterior and the intersection point of the two line features and subtract them.
I updated the full SQL, but here's the salient bit:
SELECT
...
abs
(
round
(
degrees
(
ST_Azimuth
(
points.point2,
points.intersection
)
-
ST_Azimuth
(
points.point1,
points.intersection
)
)::decimal % 180.0
,2
)
)
AS angle
...
FROM
points
I recently had to calculate the same thing, but decided on a simpler and likely faster approach.
To find the extra points for the azimuth calculation, I just check a permyriad of the length behind the intersection (or after in the rare case that it happens on the very start of the line) using ST_Line_Locate_Point and ST_Line_Interpolate_Point:
abs(degrees(
ST_Azimuth (
intersection,
ST_Line_Interpolate_Point(
line1,
abs(ST_Line_Locate_Point(line1, intersection) - 0.0001)
)
)
-
ST_Azimuth (
intersection,
ST_Line_Interpolate_Point(
line2,
abs(ST_Line_Locate_Point(line2, intersection) - 0.0001)
)
)
))
The permyriad was arbitrary and for more consistent results it would be better to use an absolute offset. To for example check 20m beforehand, you'd change 0.0001 to 20/ST_Length(line1)
and 20/ST_Length(line2)
respectively.