Question

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

Was it helpful?

Solution

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);
  });

OTHER TIPS

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.

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top