Name

ST_Angle — Returns the angle between 3 points, or between 2 vectors (4 points or 2 lines).

Synopsis

float ST_Angle(geometry point1, geometry point2, geometry point3, geometry point4);

float ST_Angle(geometry line1, geometry line2);

Description

For 3 points, computes the angle measured clockwise of P1P2P3. If input are 2 lines, get first and last point of the lines as 4 points. For 4 points,compute the angle measured clockwise of P1P2,P3P4. Results are always positive, between 0 and 2*Pi radians. Uses azimuth of pairs or points.

ST_Angle(P1,P2,P3) = ST_Angle(P2,P1,P2,P3)

Result is in radian and can be converted to degrees using a built-in PostgreSQL function degrees(), as shown in the example.

Availability: 2.5.0

Examples

Geometry Azimuth in degrees

	WITH rand AS (
		SELECT s, random() * 2 * PI() AS rad1
			, random() * 2 * PI() AS rad2
		FROM  generate_series(1,2,2) AS s
	)
	 , points AS (
		SELECT s, rad1,rad2, ST_MakePoint(cos1+s,sin1+s) as p1, ST_MakePoint(s,s) AS p2, ST_MakePoint(cos2+s,sin2+s) as p3
		FROM rand
			,cos(rad1) cos1, sin(rad1) sin1
			,cos(rad2) cos2, sin(rad2) sin2
	)
	SELECT s, ST_AsText(ST_SnapToGrid(ST_MakeLine(ARRAY[p1,p2,p3]),0.001)) AS line
		, degrees(ST_Angle(p1,p2,p3)) as computed_angle
		, round(degrees(2*PI()-rad2 -2*PI()+rad1+2*PI()))::int%360 AS reference
		, round(degrees(2*PI()-rad2 -2*PI()+rad1+2*PI()))::int%360 AS reference
	FROM points ;

1 | line | computed_angle | reference
------------------+------------------
1 | LINESTRING(1.511 1.86,1 1,0.896 0.005) | 155.27033848688 | 155