feedback
Jul 11 2005

Latitude/Longitude Distance Calculation in SQL Server

by John Dyer

Originally, my Google Maps church search page was finding the nearest churches by making an approximate square around the zip code's latitude and longitude. For large distances (over ~25 miles), this proved pretty inaccurate. To fix this, I created a SQL Function so that I could run a query like this:

SELECT * 
FROM 
dts_Alumni_Churches
WHERE 
dbo.CoordinateDistanceMiles(Latitude, Longitude, @ZipLatitude, @ZipLongitude) < @Radius

Here's the SQL function:

CREATE FUNCTION CoordinateDistanceMiles(
@Latitude1 float,
@Longitude1 float,
@Latitude2 float,
@Longitude2 float
)
RETURNS float 
AS  
BEGIN 
-- CONSTANTS
DECLARE @EarthRadiusInMiles float;
SET @EarthRadiusInMiles = 3963.1
DECLARE @PI  float;
SET @PI = PI();
-- RADIANS conversion
DECLARE @lat1Radians float;
DECLARE @long1Radians float;
DECLARE @lat2Radians float;
DECLARE @long2Radians float;
SET @lat1Radians = @Latitude1 * @PI / 180;
SET @long1Radians = @Longitude1 * @PI / 180;
SET @lat2Radians = @Latitude2 * @PI / 180;
SET @long2Radians = @Longitude2 * @PI / 180;
RETURN Acos(
Cos(@lat1Radians) * Cos(@long1Radians) * Cos(@lat2Radians) * Cos(@long2Radians) + 
Cos(@lat1Radians) * Sin(@long1Radians) * Cos(@lat2Radians) * Sin(@long2Radians) + 
Sin(@lat1Radians) * Sin(@lat2Radians)
) * @EarthRadiusInMiles;
END

If anyone has a faster method for use in SQL Server, I'd love to see it.

Comments

Billy Leo March 2. 2008 20:23

Hello there,
Thank you very much for this clear code!
It has been very helpful to me.
I seem to have a bit of a problem tho, The function seems to be 2 to 3 miles off to the north in it's calculations. Did this happen for you?
Anyway, Great Site Bud!
Thanks
Billy

Billy Leo

John Dyer March 3. 2008 13:36

@Billy, I did this 2-3 years ago, so I might very well have had a slight error! I saw another post recently that does something similar and might be more accurate: http://blog.troyd.net/PermaLink,guid,847b0f1f-498c-43d4-80de-d29902fbd2eb.aspx

John Dyer's last post: Wii + Flash + Papervision3D + C# = Alumni World Map

John Dyer

rap March 28. 2008 11:22

hi, actually i don't really understand about this kind of thing.
but there's some query here :www.viawindowslive.com/.../...eversegeocoding.aspx

it's different from you, but i think the query is also try to calculate the same thing with you.
can you tell me, which one better?

rap

Alamak June 4. 2008 03:30

You can get the sample codes in several programming languages (other than the SQL) from the following URL.

http://www.zipcodeworld.com/developers.htm

Alamak

pingback July 25. 2008 13:39

Pingback from epgunara.com

Latitude/Longitude Distance Calculation in SQL Server

epgunara.com

SunilGrewal October 31. 2008 00:01

I have distance between latitude and longitude

SunilGrewal

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading