 # Calculate Distance in Miles from Latitude and Longitude

,

With the advent of GPS and other widely available global location data, there is an increasing need to be able to accurately calculate the distance between two points over the earth's surface, from latitudes and longitudes. This SQL function does just that ,returning the distance in miles.

this function has several other advantages as well, first, it is very accurate, usually 4 to 5 decimal places. and secondly, it is much faster than most other, less accurate, algorithims. (if even more speed is needed, then include this calculation in-line in the body of your query.)

```Create Function LatLonDistance(
@Lat1 Float,
@Lon1 Float,
@Lat2 Float,
@Lon2 Float
) Returns Float
/*
Faster way to calculate distance in miles using Latitude & Longitude.
This is accurate in miles to about 4.5 decimal places, except for very small distances.

NOTE: 57.295779513082323 = 180.0 / PI
(converts Lat/Lon degrees to spherical radians)

Ref: The formula is derived from the Spherical Law of Cosines,

--RBarryYoung, 31-Jan-2009
*/ As
Begin
/* tests:
select dbo.calculateDistance(31.0, -93.0, 31.1, -93.0)        --should be 6.9169 miles
select dbo.calculateDistance(31.0, -93.0, 31.0, -93.1)        --should be 5.9290 miles
select dbo.calculateDistance(20.0, -93.0, 20.0, -93.1)        --should be 6.4998 miles
select dbo.calculateDistance(40.0, -93.0, 40.0, -93.1)        --should be 5.2987 miles
*/
Return 3963.0*acos(
sin(@Lat1/57.295779513082323)
* sin(@Lat2/57.295779513082323)
+ cos(@Lat1/57.295779513082323)
* cos(@Lat2/57.295779513082323)
* cos((@Lon2-@Lon1)/57.295779513082323)
)
End```

4.69 (16)

4.69 (16)