Parsing Google Geo API (Reverse Geocoding) with jQuery

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

I'm sure I'm not the only one, but I cannot parse/return anything when jQuery takes a request to lookup an address when the data being requested is the latitude and longitude so Google can return the data, but it cannot be read by jQuery?

http://maps.googleapis.com/maps/api/geocode/json 

With parameters:

latlng=51.276914,1.077252 &sensor=false 

In Firebug it says 200 OK but nothing is displayed in the response:

I can see it when I open it: http://maps.googleapis.com/maps/api/geocode/json?latlng=51.187296,1.229086&sensor=false&_=1302084865163

What I did was:

$.ajax( {     url: 'http://maps.googleapis.com/maps/api/geocode/json',     data: 'latlng=' + geolocation + '&sensor=false',     dataType: 'json',     cache: false,     success: function(data){ alert(data); } }); 

That doesn't work... neither $.get, $.getJSON with the json dataType.

Why can't jQuery parse/read the response?

回答1:

You need to use googles geocoder for security reasons. See answer here.



回答2:

As noted above by Bjorn there are security constraints due to the endpoint being on a different domain. However you do NOT need to use geocoder, as all that does is make an ajax request - it does little more than what you are doing now.

As Shidhin Cr notes above, one way around the security problem is that you can append callback=?, but all that really is doing is performing a task that jQuery can do for you automatically by using the "jsonp" dataType argument.

Also if you use $.getJSON it should automatically note that this is on a remote server and upgrade the request to jsonp automatically for you - but I might be remembering that wrong, there were some arguments about the jquery documentation related to that particular call.

In either case both of the above suggestions are correct, they were just lacking detail.



回答3:

Change the data parameter like this . you can see the response coming properly

data: 'latlng=' + geolocation + '&sensor=false&callback=?' 


回答4:

try use $.getJSON to get the result

Example

var latlng = "40.06125658,-7.745361328"; var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=false"; $.getJSON(url, function (data) {     for(var i=0;i


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!