Distance
Posted by Philip Leitch
Monday, March 08, 2010 10:37:37 PM
CREATE function [dbo].[Distance]
(@Lat1 float, @Long1 float, @Lat2 float, @Long2 float)
/*
www.prlsoftware.com
Author: Philip Leitch
Date: 2010
Purpose: This function measures the distance between two geospatial points.
Copyright: Philip Leitch 2010
Licensing: This code may be used or modified but if the code is included in a software package attribution to me must be made.
Liability: The developer assumes all liability when using this code.
Notes:
Based on the "ellipsoidal Vincenty formula". This might not be quite as accurate as others, but is close on accuracy and very fast.
Please visit this web site for scripts that are easily converted into any language:
http://www.movable-type.co.uk/scripts/latlong.html
The result is in kilometres Multiply by 1000 for metres
*/
returns float
as
begin
if abs(@lat1 - @lat2) < 0.00001 and abs(@long1 - @long2) < 0.00001
return 0
Declare @Radius float
set @Radius = dbo.Earth_Radius((@lat1 + @lat2)/cast(2 as float))
--Convert to radians
set @Lat1 = @lat1 * (pi()/180)
set @Long1 = @long1 * (pi()/180)
set @Lat2 = @lat2 * (pi()/180)
set @Long2 = @long2 * (pi()/180)
Declare @return float
set @return = acos(
Cos(@Lat1) * cos(@Long1) *
Cos(@Lat2) * cos(@Long2) +
cos(@lat1) * sin(@Long1) *
cos(@lat2) * sin(@Long2) +
sin(@lat1) * sin(@lat2)
) * @Radius
return @return
end
Copyright 2009 Philip Leitch