views:

2635

answers:

3

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

+2  A: 

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.

Guido
According to JQuery's website, $.getJSON has native support for JSONP request. Thus, there should be no need for said Proxy
Scott
No problem as long as the remote URL you're calling supports JSONP. Google has disabled JSONP for V3 of the GeoCoding API being mentioned above.
Gabe
A: 

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

balint
+6  A: 

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