2012-06-07 83 views
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?

例如,这map给出443 kmMorbiSurat的距离,但功能给我好了的274 km

+0

我这不是数学天才,但这篇文章帮助我,当我尝试这些事情:http://www.meridianworlddata.com/Distance-Calculation.asp – Daniel

+3

6371是地球的(近似)半径以公里为单位,所以答案应该在km。请注意,任何几何计算都是*直线*距离而不是*绕道*距离。你正在计算两点之间的直线(如果计算正确的话); Google路线指定的路程长度将会更长。 –

+0

'@Andrew Leach'非常感谢您的评论。但任何其他公式来计算完美的距离? (在PHP中) – Veer

回答

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 ."; 
} 
?> 

希望这是有帮助:)