You want to find the distance between two coordinates on planet Earth.
Use pc_sphere_distance, as shown in Example 2-10.
Finding the distance between two points
Since 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 pc_sphere_distance( ).
Pass in the latitude and longitude of your two points as the first four arguments. First come the latitude and longitude of the origin, and then come the latitude and longitude of the destination. The value returned is the distance between them in kilometers:
// NY, NY (10040) $lat1 = 40.858704; $lon1 = -73.928532; // SF, CA (94144) $lat2 = 37.758434; $lon2 = -122.435126; $dist = pc_sphere_distance($lat1, $lon1, $lat2, $lon2); printf("%.2f\n", $dist * 0.621); // Format and convert to miles
This code finds the distance between New York City and San Francisco, converts the distance to miles, formats it to have two decimal places, and then prints out the result.
Because the Earth is not a perfect sphere, these calculations are somewhat approximate and could have an error up to 0.5%.
pc_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 = pc_sphere_distance($lat1, $lon1, $lat2, $lon2, $martian_radius); printf("%.2f\n", $dist * 0.621); // Format and convert to miles
2.17.4. See Also
Recipe 2.12 for trig basics; the Wikipedia entry on Earth Radius at http://en.wikipedia.org/wiki/Earth_radius; and the article "Trip Mapping with PHP" at http://www.onlamp.com/pub/a/php/2002/11/07/php_map.html .