Home  >  Article  >  Backend Development  >  php calculate distance between two coordinates (longitude, latitude)

php calculate distance between two coordinates (longitude, latitude)

WBOY
WBOYOriginal
2016-07-25 08:43:06961browse

php calculates the distance between two coordinates (longitude, latitude), and returns the result as meters 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. $r = 6372.797; // mean radius of Earth in km
  9. $dlat = $lat2 - $lat1;
  10. $dlng = $lng2 - $lng1;
  11. $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
  12. $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
  13. $km = $r * $c;
  14. return ($miles ? ($km * 0.621371192) : $km);
  15. }
Copy code

php


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn