Saturday, November 8, 2008

Haversine implementation in PHP. (Calculate distance in google maps)

This is how haversine formulae can be used to calculate distance between two places represented by latitude and longitude in degrees

$radius = 6378100; // radius of earth in meters
$latDist = $lat - $lat2;
$lngDist = $lng - $lng2;
$latDistRad = deg2rad($latDist);
$lngDistRad = deg2rad($lngDist);
$sinLatD = sin($latDistRad);
$sinLngD = sin($lngDistRad);
$cosLat1 = cos(deg2rad($lat));
$cosLat2 = cos(deg2rad($lat2));
$a = $sinLatD*$sinLatD + $cosLat1*$cosLat2*$sinLngD*$sinLngD*$sinLngD;
if($a<0) $a = -1*$a;
$c = 2*atan2(sqrt($a), sqrt(1-$a));
$distance = $radius*$c;


The variable $distance is the distance between the two points in meters

3 comments:

Anonymous said...

"$c = 2*atan2(sqrt($a), sqrt(1-$a));" can be simplified to "$c = 2*asin(sqrt($a));"

Anonymous said...

Thanks for posting this code...I found it helpful, although you should know that there are ERRORS...the results are way off, and here is why...
$sinLatD and $sinLngD should actually be sine of HALF of the difference. Also, "$sinLngD*$sinLngD*$sinLngD" is incorrect, as it is multiplied one too many times. Making these changes gives the correct values. And yes, you can simplify $c as someone previously pointed out. Here is a good reference for Haversine...http://www.movable-type.co.uk/scripts/latlong.html.
With these changes, it is a good function.

Anonymous said...

What a great web log. I spend hours on the net reading blogs, about tons of various subjects. I have to first of all give praise to whoever created your theme and second of all to you for writing what i can only describe as an fabulous article. I honestly believe there is a skill to writing articles that only very few posses and honestly you got it. The combining of demonstrative and upper-class content is by all odds super rare with the astronomic amount of blogs on the cyberspace.