使用php中的纬度和经度计算两点之间的道路距离

时间:2015-05-26 10:52:47

标签: php google-maps

以下是我使用过的代码

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

但它提供了飞行距离,而不是公路。 例如:该函数返回2km作为两点之间的答案,但是当检查谷歌上这两个区域之间的实际距离时,它返回10km,这是正确的。

1 个答案:

答案 0 :(得分:0)

使用google api我可以找到两点之间的距离。只需要创建http请求URL并完成所有操作

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 
        'http://maps.googleapis.com/maps/api/directions/json?origin=add_source&destination=add_destination&sensor=false'
    );
    $content = curl_exec($ch);
    echo $content;

它返回json响应,其中也包括距离。