2017-04-24 68 views
0

我正在嘗試與Lalarvel 5.3中的Google溝槽cURL進行通信。 我得到一個空的答覆,但是一個200狀態代碼。 這裏是我的代碼:打電話給谷歌地圖API,但得到空迴應

public function directionGet($origin, $destination) { 
    $callToGoogle = curl_init(); 
    $googleApiKey = '**************************'; 

    curl_setopt_array(
     $callToGoogle, 
     array (
      CURLOPT_URL => 'http://maps.googleapis.com/maps/api/directions/json?origin='. $origin.'&destination=' . $destination . '&key= ' . $googleApiKey, 
      CURLOPT_POST => true, 
      CURLOPT_RETURNTRANSFER => true, 
      CURLOPT_HEADER => 0 
     ) 
    ); 
    $response = curl_exec($callToGoogle); 
    curl_close($callToGoogle); 
    return response()->json($response); 
} 
+0

你肯定你的谷歌地圖API密鑰在您的谷歌開發的儀表板配置呢? https://developers.google.com/books/docs/v1/using – pirs

+0

我可以推薦使用guzzle很容易使用和閱讀;) –

回答

0

我發現代碼中的幾個問題 1.我認爲谷歌需要你使用https而不是http安全 2. $起點和終點$需要編碼的URL格式捲曲發前 3.您有1個空格$鍵後

所以,你試試這個代碼

public function directionGet($origin, $destination) { 

    $googleApiKey = '****************************'; 

    $url   = 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey; 

    $curl = curl_init(); 

    curl_setopt_array($curl, [ 
     CURLOPT_URL   => $url, 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_ENCODING  => "", 
     CURLOPT_MAXREDIRS  => 10, 
     CURLOPT_TIMEOUT  => 30, 
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
     CURLOPT_CUSTOMREQUEST => "GET", 
     CURLOPT_HTTPHEADER  => [ 
      "cache-control: no-cache" 
     ], 
    ]); 

    $response = curl_exec($curl); 

    return $response; 
} 

$origin = "75 9th Ave, New York, NY"; 
$destination = "MetLife Stadium Dr East Rutherford, NJ 07073"; 

$directions = directionGet($origin, $destination); 

你問我關於你的代碼有什麼問題 答案是 1.我將http改爲https 2.我添加修改你的頭文件(刪除文章頭文件,因爲它使用get方法) 3.我以url格式編碼字符串(用urlencode)

我修改代碼,例如

function directionGet($origin, $destination) { 
    $callToGoogle = curl_init(); 
    $googleApiKey = '*************************'; 

    curl_setopt_array(
     $callToGoogle, 
     array (
      CURLOPT_URL => 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey, 
      CURLOPT_CUSTOMREQUEST => "GET", 
      CURLOPT_RETURNTRANSFER => true, 
     ) 
    ); 
    $response = curl_exec($callToGoogle); 
    curl_close($callToGoogle); 
    return $response; 
} 

希望這有助於

+0

它的工作!我做錯了什麼?我是新的捲曲,所以我很樂意學習 – McMazalf

+0

我在舊帖子中添加答案 –