dongqiang5865 2012-06-07 06:57
浏览 113
已采纳

计算的距离给出错误的值

I have a function in PHP which calculates the distance between two places.

Here is the php code :

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;
 }

It gives good calculations around 25 km, but around 500 km the calculations are wrong. My other question is it really giving miles or kilometers?

For example this map gives a distance of 443 km from Morbi to Surat, but the function gives me a result of 274 km

  • 写回答

1条回答 默认 最新

  • douqi1625 2012-06-07 07:58
    关注

    Ok, now that's clear that you want the road distance, we can give you a proper answer, to get the result, you can use the Google API Distance Matrix, you have different options and parameters, you have to figure out which suits you the most, be aware that there's some limitation (for the free edition):

    <<
    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.
    >>
    

    However for the purpose of answering your question i wrote a simple PHP script that gets a XML file and parse the distance/duration with 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 .";
    }
    ?>
    

    Hope this was helpful :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题