php计算两个坐标(经度,纬度)之间距离的方法

例子一:

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

例子二:

  1. /**
  2. * 计算两个坐标之间的距离(米)
  3. * @param float $fP1Lat 起点(纬度)
  4. * @param float $fP1Lon 起点(经度)
  5. * @param float $fP2Lat 终点(纬度)
  6. * @param float $fP2Lon 终点(经度)
  7. * @return int
  8. */
  9. function distanceBetween($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){
  10. $fEARTH_RADIUS = 6378137;
  11. //角度换算成弧度
  12. $fRadLon1 = deg2rad($fP1Lon);
  13. $fRadLon2 = deg2rad($fP2Lon);
  14. $fRadLat1 = deg2rad($fP1Lat);
  15. $fRadLat2 = deg2rad($fP2Lat);
  16. //计算经纬度的差值
  17. $fD1 = abs($fRadLat1 - $fRadLat2);
  18. $fD2 = abs($fRadLon1 - $fRadLon2);
  19. //距离计算
  20. $fP = pow(sin($fD1/2), 2) +
  21. cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2/2), 2);
  22. return intval($fEARTH_RADIUS * 2 * asin(sqrt($fP)) + 0.5);
  23. }
  24. /**
  25. * 百度坐标系转换成标准GPS坐系
  26. * @param float $lnglat 坐标(如:106.426, 29.553404)
  27. * @return string 转换后的标准GPS值:
  28. */
  29. function BD09LLtoWGS84($fLng, $fLat){ // 经度,纬度
  30. $lnglat = explode(',', $lnglat);
  31. list($x,$y) = $lnglat;
  32. $Baidu_Server = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x={$x}&y={$y}";
  33. $result = @file_get_contents($Baidu_Server);
  34. $json = json_decode($result);
  35. if($json->error == 0){
  36. $bx = base64_decode($json->x);
  37. $by = base64_decode($json->y);
  38. $GPS_x = 2 * $x - $bx;
  39. $GPS_y = 2 * $y - $by;
  40. return $GPS_x.','.$GPS_y;//经度,纬度
  41. }else
  42. return $lnglat;
  43. }