计算距离时的未定义索引

时间:2015-11-12 06:39:07

标签: php google-maps

我试图根据纬度和经度值获得两个地方之间的距离,但我得到了未定义的索引错误。

    <?php  function GetDrivingDistance($lat1, $lat2, $long1, $long2)
    {
    $distance="";
    $duration="";
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);
    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
    $time = $response_a['rows'][0]['elements'][0]['duration']['text'];

    return array('distance' => $dist, 'time' => $time);
}
//echo GetDrivingDistance(17.4999219, 78.47664, 17.4484114, 78.3631118) . " Kilometers<br>";

$dist = GetDrivingDistance(17.4999219, 78.47664, 17.4484114, 78.3631118);
    echo 'Distance: <b>'.$dist['distance'].'</b><br>Travel time duration: <b>'.$dist['time'].'</b>';
?>

2 个答案:

答案 0 :(得分:1)

从您的代码中, 如果我改变lat&amp; amp,我通常会得到结果。很像这样。

$result = GetDrivingDistance(37.691082,40.520775, -99.807927, -106.971013);
print_r($result);
echo "Distance ".$result['distance'];

使用print_r();

输出第一行
Array ( [distance] => 913 km [time] => 8 godz. 56 min ) 

带回声的第二行

913 km

你的问题可能是谷歌找不到你的lat&amp; amp;长

答案 1 :(得分:0)

功能输入中的Lat和log乱序。我添加了一些检查,以确保输出从谷歌有效,这就是你获得索引通知的原因。我更新了代码,如果从谷歌提取时发生错误,则返回false。

<?php
function GetDrivingDistance($lat1, $long1, $lat2, $long2)
{
    $distance="";
    $duration="";
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);

    // check the results
    if($response_a['status'] != 'OK' ||  $response_a['rows'][0]['elements'][0]['status'] == "NOT_FOUND") {
        return false;
    }

    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
    $time = $response_a['rows'][0]['elements'][0]['duration']['text'];

    return array('distance' => $dist, 'time' => $time);
} 
//echo GetDrivingDistance(17.4999219, 78.47664, 17.4484114, 78.3631118) . " Kilometers";

$dist = GetDrivingDistance(17.4999219, 78.47664, 17.4484114, 78.3631118); 
if($dist) {
    echo 'Distance: '.$dist['distance'].'
    Travel time duration: '.$dist['time'].''; 
} else {
    echo "error";
}

?>