2

Can anyone help me understand why the following code does not display any content in the second alert? Browsing to the same url that I pass to getJSON() produces output in my browser window.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <script>
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=Chicago,IL&sensor=false',
            function(json, textStatus) {
                alert("textStatus:" + textStatus);
                var out = '';
                for (var i in json) {
                    out += i + ": " + json[i] + "\n";
                }
                alert(out);
                //alert("JSON Data:" + json.results[0].formatted_address);
            });
    </script>
</body>
</html>
nhavens
  • 252
  • 1
  • 3
  • 11

2 Answers2

1

The problem was related to same origin policy. This post was very helpful. I have modified my code to use the Client-side Google Maps Geocoding API. Here is the working code:

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        var geocoder;
        $(document).ready(function() {
            geocoder = new google.maps.Geocoder();
        });
        function codeAddress() {
            var address=$('#address').val();
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    $('#location').html('<p><b>Location:</b>' + results[0].geometry.location + '</p>');
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
    </script>
</head>
<body>
    <div>
        <input id="address" type="textbox" value="Chicago,IL"/>
        <input type="button" value="Geocode" onclick="codeAddress()" />
    </div>
    <div id="location">
    </div>
</body>
</html>
Community
  • 1
  • 1
nhavens
  • 252
  • 1
  • 3
  • 11
0

It seems that your obj variable is undefined. Did you mean:

out += i + ": " + json[i] + "\n";
TuomasR
  • 2,296
  • 18
  • 28
  • Doh! Good call. I fixed this in my original post, but the second alert still does not have any content. – nhavens Oct 17 '10 at 20:11
  • Try adding an alert inside the for-loop. Then break after the first one, otherwise you'll be dismissing the dialogs for the next few hours... – TuomasR Oct 17 '10 at 20:29
  • I tried moving alert(out) inside the for loop, but then I stopped getting a second alert. – nhavens Oct 18 '10 at 19:38