Home >Backend Development >PHP Tutorial >Calculate distance based on longitude and latitude in PHP

Calculate distance based on longitude and latitude in PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 08:42:531206browse

This is a very useful distance calculation function that uses latitude and longitude to calculate the distance from point A to point B. This function can return distance in three unit types: miles, kilometers, and nautical miles.

  1. function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  2. $theta = $lon1 - $lon2;
  3. $dist = sin(deg2rad($lat1)) * sin( deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  4. $dist = acos($dist);
  5. $dist = rad2deg( $dist);
  6. $miles = $dist * 60 * 1.1515;
  7. $unit = strtoupper($unit);
  8. if ($unit == "K") {
  9. return ($miles * 1.609344);
  10. } else if ($unit == "N") {
  11. return ($miles * 0.8684);
  12. } else {
  13. return $miles;
  14. }
  15. }
  16. //Usage:
  17. echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";
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