Calculate the Distance Between Two Coordinates (latitude, longitude)


 / Published in: PHP
 

This PHP function calculates the distance between to pairs of latitude longitude coordinates. Returns the distance in miles or kilometers.

  1. function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
  2. {
  3. $pi80 = M_PI / 180;
  4. $lat1 *= $pi80;
  5. $lng1 *= $pi80;
  6. $lat2 *= $pi80;
  7. $lng2 *= $pi80;
  8.  
  9. $r = 6372.797; // mean radius of Earth in km
  10. $dlat = $lat2 - $lat1;
  11. $dlng = $lng2 - $lng1;
  12. $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
  13. $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
  14. $km = $r * $c;
  15.  
  16. return ($miles ? ($km * 0.621371192) : $km);
  17. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: grkkid on January 17, 2009

great work...tested it with my zipcode database and worked great

Posted By: dougdo on December 4, 2009

Thanks for the function. Was very helpful on a number of my geographic sites to show the distance of nearby points (see example)

Posted By: arucordoba on November 5, 2010

Thanks! Great job!

You need to login to post a comment.