2010-09-30 67 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