using jquery.getJson with Google's GeoCoding HTTP Service [closed]

半腔热情 提交于 2019-12-17 22:43:33

问题


Google offers a wonderful REST interface for geocoding and reverse geocoding an address. My API key is valid, and if I enter the request directly into the browser address it works great. However, the following jquery fails terrible and I'm failing to see why. Hoping you could help me out here.

$.getJSON("http://maps.google.com/maps/geo?q="+ address+"&key="+apiKey+"&sensor=false&output=json",
  function(data, textStatus){
     console.log(data);
  });

Google's REST interface doc for this service: http://code.google.com/apis/maps/documentation/geocoding/index.html


回答1:


The problem here is that I wasn't specifying the JSONP callback. The correct code is as follows

$.getJSON("http://maps.google.com/maps/geo?q="+ address+"&key="+apiKey+"&sensor=false&output=json&callback=?",
  function(data, textStatus){
     console.log(data);
  });



回答2:


Due to security restrictions, you can not send an AJAX request to a URL from a page in a different domain. That is why it works if you enter the URL in the browser, but not if you try to make the request from your javascript code.

A common workaround is to use a server side component acting as a proxy: it receives your AJAX requests and sends them to the google geolocator.




回答3:


add an error function

            error: function(xhr, ajaxOptions, thrownError) {
            alert("Ajax Error: " + xhr.status + "\nMsg: " + xhr.responseText);
        }

and try to debug if it is just a json related error




回答4:


I had the exact same trouble. This is how I was able to ultimately get it to work for me.

see google maps api docs



来源:https://stackoverflow.com/questions/898201/using-jquery-getjson-with-googles-geocoding-http-service

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