Created
September 10, 2012 22:24
-
-
Save thunsaker/3694423 to your computer and use it in GitHub Desktop.
Calculate Distance Between 2 GPS Coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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