We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

tylerhall on 04/24/07


Tagged

math longitude distance latitude


Versions (?)


Who likes this?

14 people have marked this snippet as a favorite

nicolaspar
eunjoo1984
koncept
d4rk
joedavex
neuroasis
hudge
willcodeforfood
jonhenshaw
marteki
gardnern
Steffen82
jeppeb
sumandahal


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 

You need to login to post a comment.