Spatial SQL -> MS-SQL. Calculate Azimuth between given points (in LL coordinates)


/*
  =================================================================
   this function calculates Azimuth between two points
   input: points in WGS84 coordinates (Lat-Long)
   output: Azimuth in radians
  =================================================================
*/


IF EXISTS (SELECT name FROM sys.objects
  WHERE name = 'sfn_Azimuth_2pts_LL' AND type IN (N'FN',N'IF', N'TF',N'FS', N'FT')
  DROP FUNCTION sfn_Azimuth_2pts_LL
GO

CREATE FUNCTION sfn_Azimuth_2pts_LL (@FPoint GEOGRAPHY, @TPoint GEOGRAPHY)
  RETURNS FLOAT
AS
BEGIN

  DECLARE @Azimuth FLOAT;
  DECLARE @lon1 FLOAT, @lon2 FLOAT, @lat1 FLOAT, @lat2 FLOAT;

  SET @lon1 = @FPoint.Long; SET @lat1 = @FPoint.Lat; -- from point coords
  SET @lon2 = @TPoint.Long; SET @lat2 = @TPoint.Lat; -- to point coords

  SET @Azimuth = ATN2(COS(@lat1) * SIN(@lat2) - SIN(@lat1) * COS(@lat2)
  * COS(@lon2 - @lon1), SIN(@lon2 - @lon1) * COS(@lat2));

  -- return value
  RETURN @Azimuth;

END
GO

/* Milan city. Aproximate Azimuth between Duomo and Castello Sforzesco */

DECLARE @FP GEOGRAPHY, @TP GEOGRAPHY;

SET @FP = GEOGRAPHY::STGeomFromText(
  'POINT(' + CONVERT(Varchar(30),9.1918377, 2)
  + ' ' + CONVERT(Varchar(30),45.4642822, 2) + ')',4326);
SET @TP = GEOGRAPHY::STGeomFromText(
  'POINT(' + CONVERT(Varchar(30),9.1794726, 2)
  + ' ' + CONVERT(Varchar(30),45.4702864, 2) + ')',4326);

SELECT dbo.sfn_Azimuth_2pts_LL(@FP,@TP);


Result will be like this:
1.73933903068331




sqlexamples.info