By David in How To. May 10, 2009
Recently implemented a 'distance between UK post codes' system for a couple of web sites. Thought I'd share the PHP code for others that might be interested. It's using the Haversine formula to calculate the distance in kilometers between latitude and longitude points.
This it in action showing Leeds to London from Street Finder.co.uk
$A_lat = 53.1506; $A_lon = -1.8444; $B_lat = 52.2047; $B_lon = 0.1406; $source_lat = $A_lat * pi() / 180; $source_lon = $A_lon * pi() / 180; $dest_lat = $B_lat * pi() / 180; $dest_lon = $B_lon * pi() / 180; $R = 6371; // earth's mean radius in km $dLat = $dest_lat - $source_lat; $dLong = $dest_lon - $source_lon; $a = sin($dLat/2) * sin($dLat/2) + cos($source_lat) * cos($dest_lat) * sin($dLong/2) * sin($dLong/2); $b = 2 * atan2(sqrt($a), sqrt(1-$a)); $distance = $R * $b;
Related Articles : Recent Work, How To : Convert Google 'My Maps' KML Placemarks, How To : Create Your Own Points Of Interest