3

我有一个函数PHP可以计算两个地方之间的距离。

这是php代码:

function distance($lat1, $lon1, $lat2, $lon2) {
   $earth_radius = 6371; 
   $delta_lat = $lat2 - $lat1 ;
   $delta_lon = $lon2 - $lon1 ;

  $distance  = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($delta_lon)) ;
  $distance  = acos($distance);
  $distance  = rad2deg($distance);
  $distance  = $distance * 60 * 1.1515;
  $distance  = round($distance, 4);
  return $distance = $distance * 1.609344;
 }

它给出了很好的计算25 km,但周围500 km的计算是错误的。我的另一个问题是it really giving miles or kilometers?

例如,这张地图给出的距离为443 kmfrom Morbito Surat,但该函数给了我一个结果274 km

4

1 回答 1

1

好的,既然您想要道路距离,我们可以给您一个正确的答案,要得到结果,您可以使用Google API Distance Matrix,您有不同的选项和参数,您必须找出适合您的大多数,请注意有一些限制(免费版):

<<
The Distance Matrix API has the following limits in place:
100 elements per query.
100 elements per 10 seconds.
2 500 elements per 24 hour period.
>>

但是,为了回答您的问题,我编写了一个简单的 PHP 脚本,该脚本获取 XML 文件并使用 SimpleXMLElement 解析距离/持续时间......

<?php
$start = "morbi";   // You can either set lon and lat separated with a comma ex: 22.814162,70.834351
$destination = "surat";
$mode = "driving";  // Different modes: driving,walking,bicycling (be aware that some of the modes aren't available for some poi's ...)

$xml = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=$start&destinations=$destination&mode=$mode&language=en-EN&sensor=false");
$data = new SimpleXMLElement($xml);
$distance = $data->row->element->distance->text;
$time = $data->row->element->duration->text;
if(empty($distance) OR empty($time)){
    echo "Oops, this mode ($mode) isn't available ...";
}else{
    echo "The distance between $start and $destination is $distance and the travel duration while $mode is $time .";
}
?>

希望这有帮助:)

于 2012-06-07T07:58:24.177 回答