PHP Numbers
Finding the Distance Between Two Places
Problem
You want to find the distance between two coordinates on planet Earth.Solution
Example Finding the distance between two points
function sphere_distance($lat1, $lon1, $lat2, $lon2, $radius = 6378.135) {
$rad = doubleval(M_PI/180.0);
$lat1 = doubleval($lat1) * $rad;
$lon1 = doubleval($lon1) * $rad;
$lat2 = doubleval($lat2) * $rad;
$lon2 = doubleval($lon2) * $rad;
$theta = $lon2 - $lon1;
$dist = acos(sin($lat1) * sin($lat2) +
cos($lat1) * cos($lat2) *
cos($theta));
if ($dist < 0) { $dist += M_PI; }
// Default is Earth equatorial radius in kilometers
return $dist = $dist * $radius;
}
// NY, NY (10040)
$lat1 = 40.858704;
$lon1 = -73.928532;
// SF, CA (94144)
$lat2 = 37.758434;
$lon2 = -122.435126;
$dist = sphere_distance($lat1, $lon1, $lat2, $lon2);
// It's about 2570 miles from NYC to SF
// $formatted is 2570.18
$formatted = sprintf("%.2f", $dist * 0.621); // Format and convert to miles
Discussion
Because the Earth is not flat, you cannot get an accurate distance between two locations using a standard Pythagorean distance formula. You must use a Great Circle algorithm instead, such as the one in sphere_distance().
Pass in the latitude and longitude of your two points as the first four arguments. The latitude and longitude of the origin come first, and then the latitude and longitude of the destination. The value returned is the distance between them in kilometers.
Because the Earth is not a perfect sphere, these calculations are somewhat approximate and could have an error up to 0.5%. sphere_distance() accepts an alternative sphere radius as an optional fifth argument.
This lets you, for example, discover the distance between points on Mars:
$martian_radius = 3397;
$dist = sphere_distance($lat1, $lon1, $lat2, $lon2, $martian_radius);
$formatted = sprintf("%.2f", $dist * 0.621); // Format and convert to miles
No comments:
Post a Comment