Spatial SQL -> MS-SQL. Calculate angle between given Geography points

We know coordinates of 3 geography points and want to measure angle between them.


-- ============================================================================
-- function: sfn_calcangle_LL
-- calculate angle between 3 given Geography points
-- input: three points (of geography type)
-- output: (value between 0 and 360) float
-- ============================================================================

-- drop prev version
IF EXISTS (
  SELECT * FROM sys.objects
  WHERE object_id = OBJECT_ID(N'dbo.sfn_calcangle_LL')
  AND type IN (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION dbo.sfn_calcangle_LL
GO


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

  DECLARE @FCTAngle FLOAT, @CFAzimuth FLOAT, @CTAzimuth FLOAT, @dAz FLOAT;
  DECLARE @Pi2 FLOAT;

  SET @Pi2 = Pi() * 2;

  SET @CFAzimuth = dbo.sfn_Bearing_2pts_LL (@CPoint, @FPoint);
  SET @CTAzimuth = dbo.sfn_Bearing_2pts_LL (@CPoint, @TPoint);

  -- delta azimuth
  SET @dAz = @CTAzimuth - @CFAzimuth;

  -- set result variable in degrees
  SET @FCTAngle = CONVERT(FLOAT,((@dAz/@Pi2) * 360));

  IF (@FCTAngle < 0)
    SET @FCTAngle = @FCTAngle + 360;

  RETURN @FCTAngle;

END
GO




sqlexamples.info