欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP计算地图上两点间的距离

程序员文章站 2022-06-04 21:58:26
...
  1. class GeoHelper
  2. {
  3. /**
  4. * @param int $lat1
  5. * @param int $lon1
  6. * @param int $lat2
  7. * @param int $lon2
  8. * @param string $unit
  9. * @return
  10. */
  11. public static function distance($lat1, $lon1, $lat2, $lon2, $unit = "K")
  12. {
  13. $theta = $lon1 - $lon2;
  14. $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad
  15. ($lat2)) * cos(deg2rad($theta));
  16. $dist = acos($dist);
  17. $dist = rad2deg($dist);
  18. $miles = $dist * 60 * 1.1515;
  19. $unit = strtoupper($unit);
  20. if ($unit == "K") {
  21. return ($miles * 1.609344);
  22. } else
  23. if ($unit == "N") {
  24. return ($miles * 0.8684);
  25. } else { //mi
  26. return $miles;
  27. }
  28. }
  29. /**
  30. *
  31. * @param string $address
  32. * @param string $apikey
  33. * @return array [1]:lat [0]:lng
  34. */
  35. public static function getLatLng($address, $apikey)
  36. {
  37. $find = array("\\n", "\\r", " ");
  38. $replace = array("", "", "+");
  39. $address = str_replace($find, $replace, $address);
  40. $url = 'http://maps.google.com/maps/geo?q=' . $address . '&key=' . $apikey .
  41. '&sensor=false&output=xml&oe=utf8';
  42. $response = self::xml2array($url);
  43. $coordinates = $response['kml']['Response']['Placemark']['Point']['coordinates'];
  44. if (!empty($coordinates)) {
  45. $point_array = split(",", $coordinates);
  46. return $point_array;
  47. }
  48. }
  49. }
复制代码

图上, PHP