-- -- This routine calculates the distance between two points (given the -- latitude/longitude of those points). It is being used to calculate -- the distance between two locations using GeoDataSource (TM) products -- -- Calculate distance between two points lat1, long1 and lat2, long2 -- Uses radius of earth in kilometers or miles as an argurments -- -- Typical radius: 3963.0 (miles) (Default if no value specified) -- 6387.7 (km) -- -- -- For enquiries, please contact sales@geodatasource.com -- Official Web site: https://www.geodatasource.com -- -- Thanks to Janes Swarowski for contributing the source code. -- -- GeoDataSource.com (C) All Rights Reserved 2022 -- create function dbo.Distance( @lat1 float , @long1 float , @lat2 float , @long2 float) returns float as begin declare @DegToRad as float declare @Ans as float declare @Miles as float set @DegToRad = 57.29577951 set @Ans = 0 set @Miles = 0 if @lat1 is null or @lat1 = 0 or @long1 is null or @long1 = 0 or @lat2 is null or @lat2 = 0 or @long2 is null or @long2 = 0 or (@lat1 = @lat2 and @long1 = @long2) begin return ( @Miles ) end set @Ans = SIN(@lat1 / @DegToRad) * SIN(@lat2 / @DegToRad) + COS(@lat1 / @DegToRad ) * COS( @lat2 / @DegToRad ) * COS(ABS(@long2 - @long1 )/@DegToRad) set @Miles = 3959 * ATAN(SQRT(1 - SQUARE(@Ans)) / @Ans) set @Miles = CEILING(@Miles) return ( @Miles ) end
The sample code is licensed under LGPLv3.