8

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

Scott
  • 11,046
  • 10
  • 51
  • 83

4 Answers4

17

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
  • 11,046
  • 10
  • 51
  • 83
  • 3
    It's working because you specify yourself the `callback` parameter at the end of the query but if you let jQuery handle it (by specifying `dataType: 'jsonp'`) it won't, please see: http://blog.mikecouturier.com/2011/03/fix-jquery-jsonp-request-to-google-maps.html – Mike Gleason jr Couturier Mar 21 '11 at 02:12
3

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
  • 46,642
  • 28
  • 120
  • 174
  • 1
    According to JQuery's website, $.getJSON has native support for JSONP request. Thus, there should be no need for said Proxy – Scott May 22 '09 at 15:01
  • 2
    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 Sumner May 31 '10 at 05:49
  • JSONP is a work around to the XSS security built into browsers, this actually started out as a security loophole but is now so widely used I don't see them ever fixing it. – Agile Noob Feb 17 '11 at 15:42
  • @Gabe: They didn't disabled it, just secured it even more (than v2) :) – Mike Gleason jr Couturier Mar 21 '11 at 02:13
0

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

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
s15199d
  • 7,261
  • 11
  • 43
  • 70
0

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
  • 3,391
  • 7
  • 41
  • 50