php - 计算出的距离给出了错误的值

标签 php google-maps

我在 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 公里 附近给出了正确的计算,但在 500 公里 附近计算是错误的。 我的另一个问题是它真的提供英里或公里吗?

例如这个map给出了从 MorbiSurat443 km 的距离,但是函数给出了 274 km 的结果

最佳答案

好的,既然你想要的道路距离很明确,我们可以给你一个正确的答案,要得到结果,你可以使用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 .";
}
?>

希望这对您有所帮助:)

关于php - 计算出的距离给出了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927062/

相关文章:

search - Google map 搜索栏在 GWT 中调整大小

javascript - 在 Google map 街景 View 中绘制多段线

php - 解决 SQL 查询结果中的歧义

php - 附加到 php 指令而不是替换?

javascript - 新标签页被弹出窗口拦截器拦截

android - RuntimeException : API key not found. 检查 geo.API_KEY 是否在 AndroidManifest.xml 中

google-maps - 资源解释为图像,但在使用 Google map 时传输为文本/html

javascript - 谷歌地图在 IE7 中不工作

php - 'other-table, column-dependent, dynamic table status'是什么?

PHP 日期差异有差异