PHP Implementation of Haversine Computation

We needed to compute the distance between two points on the Earth using longitude and latitude from Google’s Geocode API service. We use PHP, but there was no reference to a PHP implementation of the Haversine Equation, so I made one. I needed miles, but if you need another unit, just replace $earth_radius with the appropriate value. Enjoy!

public function distance($long_1,$lat_1,$long_2,$lat_2)
$earth_radius = 3963.1676; // in miles

$sin_lat   = sin(deg2rad($lat_2  - $lat_1)  / 2.0);
$sin2_lat  = $sin_lat * $sin_lat;

$sin_long  = sin(deg2rad($long_2 - $long_1) / 2.0);
$sin2_long = $sin_long * $sin_long;

$cos_lat_1 = cos($lat_1);
$cos_lat_2 = cos($lat_2);

$sqrt      = sqrt($sin2_lat + ($cos_lat_1 * $cos_lat_2 * $sin2_long));

$distance  = 2.0 * $earth_radius * asin($sqrt);

return $distance;

Hat tip to Aaron Overton for an error in the $sin_long line.

Leave a Reply

Your email address will not be published. Required fields are marked *