2012-06-07 104 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 ."; 
} 
?> 

希望這是有幫助:)