Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery won't get json?

So I'm trying to complete the simple task of getting json data from google, but this little bit of jquery code won't run. Will you please help me figure out why?

  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){
    $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false", function(jsondata) {
            alert(jsondata.status);
    });
  });
  </script>

Best solution: add "&callback=?" to the end of the url. Thank you so much for all your help guys!

like image 781
Andrew Avatar asked Mar 12 '11 06:03

Andrew


1 Answers

Yup, this is absolutely a Same Origin Policy bug.

It seems that the latest version of the Google Maps API (v3) does not support jsonp. As a result, if you want to geocode, you're going to need to use the maps api:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script>
    $(document).ready(function(){
        var loc = "1600 Amphitheatre Parkway, Mountain View, CA";
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode( {'address': loc },
            function(data, status) { console.log(data); });
    });
</script>

Other alternatives:

  • Use a 'proxy' service, as ctcherry pointed out, to fetch the data for you.
  • Use the old V2 API with JSONP, but you'll need a Maps API key.
like image 126
Pandincus Avatar answered Nov 12 '22 13:11

Pandincus