2010-09-30 58 views
2

無論出於何種原因,以下請求沒有得到谷歌的迴應。但是,如果我將URL粘貼到地址欄中,它可以正常工作。我不確定爲什麼會發生這種情況。 Google是否通過引薦來源的標題過濾了請求?谷歌地圖json地理編碼,在瀏覽器中沒有響應

http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=3122%2C%20Australia

 $.ajax({ 
      url:'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+post_code+encodeURIComponent(', Australia'), 
      success:function(data) { 
       alert(data); 
       if(data['status'] == 'OK') { 
        var location = data['results'][0]['geometry']['location']; 
        map.panTo(location['lat']+':'+location['lng']); 
        map.setZoom(8); 
       } 
      } 

     }); 

回答

10

看起來你可能會得到封鎖的Same Origin Policy

當Google地圖爲JavaScript提供全功能Client-side Geocoding API時,您正在嘗試使用Server-side Geocoding Web Service。還有一個v2 version,但最近已被棄用。

這會自動解決您的同源問題,此外,請求限制將根據客戶端IP地址而不是每個服務器IP地址進行計算,這對於熱門網站會產生巨大差異。

客戶端服務應該很容易使用。下面是使用第3版API一個非常簡單的地理編碼例如:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Geocoding Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <script type="text/javascript"> 
    var geocoder = new google.maps.Geocoder(); 

     if (geocoder) { 
     geocoder.geocode({ 'address': 'Australia' }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       console.log(results[0].geometry.location); 
      } 
      else { 
       console.log('No results found: ' + status); 
      } 
     }); 
     } 
    </script> 
</body> 
</html> 

上述應打印(-25.274398, 133.775136)到控制檯。

+0

感謝您的快速響應!我得到它的工作,並回來發現你已經改變它使用geometry.location。工作很好,我相信這對其他人很有用。 – Keyo 2010-09-30 00:20:40

+0

謝謝! – callumander 2011-06-10 10:31:11

+0

關於如何扭轉這種情況的任何提示,我需要從latlng值中獲得一個城鎮/城市。 – 2011-10-25 14:01:18