2017-02-23 23 views
0

我有一小段PHP代碼使用JSON來獲取谷歌地圖的時間和距離。它的作品,如果我輸入合作伙伴到URL中,但當我從變量加載它不起作用?我究竟做錯了什麼?php和json不使用變量

的代碼是:

<? 

$lat1= "52.40860600000001"; 
$long1= "-1.5499760999999808"; 
$lat2= "53.7668532"; 
$long2= "-2.4743857999999364"; 

$orig = $lat1.",".$long1; 
$dest = $lat2.",".$long2; 

$new_url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$orig."&destinations=".$dest."&key=AIzaSyC3lhU4E-viZZ_OBths87Gd0Z7eGR-_1yI"; 

function GetDrivingDistance() 
{ 
    $url = $new_url; 
    $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); 
} 

$dist = GetDrivingDistance(); 

回聲距離:「。$ DIST [ '距離']「。
旅行時間:'。$ dist ['time']。''; echo $ new_url;

?> 
+1

'$ new_url'不在函數的作用域內。你應該考慮把它作爲一個論點。 – apokryfos

+0

[參考:什麼是變量作用域,哪些變量可以從哪裏訪問以及什麼是「未定義變量」錯誤?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope哪位變量 - 是可訪問的,從-其中和) –

回答

0

問題是,$new_url是不是在GetDrivingDistance範圍。你應該修改你的函數,通過url(或者更好的,傳遞經緯度值)

function GetDrivingDistance($lat1, $long1, $lat2, $long2) 
{ 
    $orig = $lat1.",".$long1; 
    $dest = $lat2.",".$long2; 
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$orig."&destinations=".$dest."&key=AIzaSyC3lhU4E-viZZ_OBths87Gd0Z7eGR-_1yI"; 

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

$lat1= "52.40860600000001"; 
$long1= "-1.5499760999999808"; 
$lat2= "53.7668532"; 
$long2= "-2.4743857999999364"; 
$dist = GetDrivingDistance($lat1, $long1, $lat2, $long2); 
echo 'Distance: <b>'.$dist['distance'].'</b><br>Travel time duration: <b>'.$dist['time'].'</b>';