我發現代碼中的幾個問題 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;
}
希望這有助於
你肯定你的谷歌地圖API密鑰在您的谷歌開發的儀表板配置呢? https://developers.google.com/books/docs/v1/using – pirs
我可以推薦使用guzzle很容易使用和閱讀;) –