Skip to content

Instantly share code, notes, and snippets.

@thunsaker
Created September 10, 2012 22:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thunsaker/3694423 to your computer and use it in GitHub Desktop.
Save thunsaker/3694423 to your computer and use it in GitHub Desktop.
Calculate Distance Between 2 GPS Coordinates
CREATE FUNCTION [dbo].[CalculateDistanceBetweenGPSCoordinates](
@Latitude1 float,
@Longitude1 float,
@Latitude2 float,
@Longitude2 float,
@ReturnUnits char(2) = 'MI'
)
RETURNS float
AS
BEGIN
-- CONSTANTS
DECLARE @EarthRadiusInMiles float = 3956.6;
DECLARE @EarthRadiusInKm float = 6367.5;
DECLARE @EarthRadius float = @EarthRadiusInMiles;
IF (@ReturnUnits = 'KM')
BEGIN
SELECT @EarthRadius = @EarthRadiusInKm
END
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)
) * @EarthRadius;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment