如何使用jquery ajax调用谷歌地图地理编码服务

我正试图从谷歌地图geocode api获取LatLng。 我的代码在下面,地址值是“纽约,纽约”

$.ajax({ url: 'http://maps.googleapis.com/maps/api/geocode/json', data: { sensor: false, address: address }, success: function (data) { alert(data) } }); 

但我没有得到任何警惕的价值观。

谢谢你的帮助。

您需要就规则与API联系。

 $.getJSON( { url : 'https://maps.googleapis.com/maps/api/geocode/json', data : { sensor : false, address : address }, success : function( data, textStatus ) { console.log( textStatus, data ); } } ); 

编辑:

我多么愚蠢,早上不应该在stackoverflow上! 问题是跨域请求。 出于安全原因,这是不允许的。 请参阅: 如何对Google Maps API进行跨域AJAX调用?

请使用Google自己的Geocoding客户端 。

没有必要使用jquery,谷歌地图javascript API v3已经构建了自己的function,这使得API易于使用。

https://developers.google.com/maps/documentation/javascript/geocoding https://developers.google.com/maps/documentation/geocoding/intro

 var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } }); 

如果有人在这个主题上寻求帮助,我就是这样做的。 请注意,这是反向查找,但正向查找应该以相同的方式工作:

`

  function getLocation() { var latdegrees=40.2298; var londegrees=-41.88754; var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latdegrees + "," + londegrees + "YOUR API KEY"; $.getJSON(url,function (data, textStatus) { var streetaddress=data.results[0].formatted_address; return streetaddress; }); }` 

V3地理编码webservice不支持JSONP请求,但它仍可在V2中使用

请参阅: http : //blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice/

这就是我做到的。 Geocoder似乎正在创建它自己的回调。

 geo.geocode({ 'address': myaddress }, function(data, status) { if (status == google.maps.GeocoderStatus.OK) { var myylocation = data[0].geometry.location; lat = myylocation.lat(); lng = myylocation.lng(); } }); 

或者指定dataType到jsonp?

 $.ajax({ url: 'http://maps.googleapis.com/maps/api/geocode/json', data: { sensor: false, address: address }, dataType:'jsonp', success: function (data) { alert(data) } });