Utilizo esta función para calcular la distancia entre latitud y longitud.
La tengo tanto para SQL Server como PHP
/** * Calcular la distancia entre latitudes y longitudes * @param decimal $latitude1 [description] * @param decimal $longitude1 [description] * @param decimal $latitude2 [description] * @param decimal $longitude2 [description] * @param string $unit [description] * @param integer $decimals [description] * @return decimal [description] */ function getDistance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Km', $decimals = 2) { $theta = $longitude1 - $longitude2; $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta))); $distance = acos($distance); $distance = rad2deg($distance); $distance = $distance * 60 * 1.2015; switch ($unit) { case 'Mi': break; case 'Km': $distance = $distance * 1.609344; break; case 'm': $distance = $distance * 1.609344 * 1000; break; } return round($distance, $decimals); }
ALTER FUNCTION [dbo].[fn_DistanciaGPS] ( @lat1 AS decimal(18,8) , @lon1 AS decimal(18,8) , @lat2 AS decimal(18,8) , @lon2 AS decimal(18,8) ) RETURNS decimal(18,3) AS BEGIN -- routine body goes here, e.g. DECLARE @P1 AS GEOGRAPHY SET @P1 = GEOGRAPHY::Point(@lat1 , @lon1 , 4326) -- en metros RETURN @P1.STDistance(GEOGRAPHY::Point(@lat2, @lon2 , 4326)) END