簡體   English   中英

Google Maps API無法使用服務器端代碼,但可以在客戶端使用

[英]Google Maps API not working with server side code but works client side

我正在生成一個URL,例如:

http://maps.googleapis.com/maps/api/geocode/json?address=143+Blackstone+Street%2C+Mendon%2C+MA+-+01756&key= ***********

如果我在瀏覽器中打開它,我將成功獲得結果。 但是,如果我使用curl使用相同的URL,則會得到:

錯誤:無法連接到主機

這是我的PHP代碼

$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode('143 Blackstone Street, Mendon, MA - 01756')."&key=***********";    
$ch = curl_init();
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 100,            
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
    echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);

更新

使用Google API時,我遇到了一個稱為server keybrowser key的術語。 但是,在API管理器中,我似乎看不到在哪里設置或更改API類型。

您正在對需要以純文本格式顯示的url部分進行urlencode。

僅對您的參數進行編碼

<?php
$address = urlencode("143 Blackstone Street, Mendon, MA - 01756");
$key = urlencode("************");
$ch = curl_init();
$options = array(
    CURLOPT_URL => "http://maps.googleapis.com/maps/api/geocode/json?address=".$address."&key=".$key,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 100,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
    echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);

如果您從curl收到“無法連接到主機”錯誤消息,則聽起來問題可能不在Google Maps API方面,而是在代理/網絡方面。 無論鍵類型或url參數如何,都應始終可以連接到maps.googleapis.com。

我將研究這里建議的步驟: 如何解決cURL錯誤(7):無法連接到主機?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM