Archive for the 'PHP' > 'Mapping' Category


Well, this is a pretty awsome function. It takes two points of reference, using Longitude and Latitude and returns the distance between them.

I use this for compairing distances between zip codes and displaying results based on the values returned. Its pretty sleak if you ask me...

Good luck...

<?php

/**
* Function: distance
* Param1: lat1 - Latitude of point 1.
* Param2: lon1 - Longitude of point 1.
* Param3: lat2 - Latitude of point 2.
* Param4: lon2 - Longitude of point 2.
* Param4: unit - M(Miles) K(Kilometers) N(Nautical Miles)
*
* Takes the longitude and latitude of two locations along with a unit type.
* Calculates the distance between the two and returns a result.
*/
function distance($lat1, $long1, $lat2, $long2, $unit) {

$theta = $long1- $long2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);

if ($unit == "K")
return ($miles * 1.609344);
else if ($unit == "N")
return ($miles * 0.8684);
else
return $miles;
}

//Following values used for testing purposes.//
//Chandler, Arizona -> Las Vegas Nevada//

echo distance(33.239097, -111.86355, 36.233655, -115.06881, "M") . " Miles
";
echo distance(33.239097, -111.86355, 36.233655, -115.06881, "K") . " Kilometers
";
echo distance(33.239097, -111.86355, 36.233655, -115.06881, "N") . " Nautical Miles
";

?>

Posted by OLLIE at 22:46pm