CREATE FUNCTION [dbo].[DistanceBetween]
(
@Lat1 as real,
@Long1 as real,
@Lat2 as real,
@Long2 as real
)
RETURNS real
AS
-- returns distance as the crow flies (in km) between two lat/long coordinates
BEGIN
DECLARE
@dLat1InRad as float(53),
@dLong1InRad as float(53),
@dLat2InRad as float(53),
@dLong2InRad as float(53),
@dLongitude as float(53),
@dLatitude as float(53),
@a as float(53),
@c as real,
@kEarthRadius as real,
@dDistance as real
SET @dLat1InRad = @Lat1 * (PI()/180.0)
SET @dLong1InRad = @Long1 * (PI()/180.0)
SET @dLat2InRad = @Lat2 * (PI()/180.0)
SET @dLong2InRad = @Long2 * (PI()/180.0)
SET @dLongitude = @dLong2InRad - @dLong1InRad
SET @dLatitude = @dLat2InRad - @dLat1InRad
/* Intermediate result a. */
SET @a = SQUARE (SIN (@dLatitude / 2.0)) + COS (@dLat1InRad) * COS (@dLat2InRad) * SQUARE(SIN (@dLongitude / 2.0))
/* Intermediate result c (great circle distance in Radians). */
SET @c = 2.0 * ATN2 (SQRT (@a), SQRT (1.0 - @a))
/* SET kEarthRadius = 3956.0 miles */
SET @kEarthRadius = 6376.5
/* kms */
SET @dDistance = @kEarthRadius * @c
RETURN (@dDistance)
END