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

4 comments:

Anonymous said...

Hi,

Do you guys watch movies in theater or on internet? I use to rent DVD movies from [b]Netflix.com[/b]. Recently I discovered that we can watch all new movies on internet on day, they are released. So why should I spend money on renting movies??? So, can you guys please tell me where I can [url=http://www.watchhotmoviesfree.com]watch latest movie Dark Life 2010[/url] for free?? I have searched [url=http://www.watchhotmoviesfree.com]Youtube.com[/url], [url=http://www.watchhotmoviesfree.com]Dailymotion.com[/url], [url=http://www.watchhotmoviesfree.com]Megavideo.com[/url] but, Could not find a good working link. If you know any working link please share it with me.


Thanks

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.