Snippet Name: Calculate Distance
Description: Calculates the distance between two pairs of latitude longitude coordinates. Returns the distance in miles or kilometers.
Comment: (none)
Language: PHP
Highlight Mode: PHP
Last Modified: February 26th, 2009
|
<?PHP
FUNCTION distance($lat1, $lng1, $lat2, $lng2, $miles = TRUE)
{
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;
$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = SIN($dlat / 2) * SIN($dlat / 2) + COS($lat1) * COS($lat2) * SIN($dlng / 2) * SIN($dlng / 2);
$c = 2 * ATAN2(SQRT($a), SQRT(1 - $a));
$km = $r * $c;
RETURN ($miles ? ($km * 0.621371192) : $km);
}
?> |