views:

48

answers:

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"&gt;&lt;/script&gt;
</head>
<body>
    <script>
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=Chicago,IL&amp;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>
A: 

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

out += i + ": " + json[i] + "\n";
TuomasR
Doh! Good call. I fixed this in my original post, but the second alert still does not have any content.
nhavens
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
I tried moving alert(out) inside the for loop, but then I stopped getting a second alert.
nhavens
+1  A: 

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"&gt;&lt;/script&gt;
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;&lt;/script&gt;
    <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>
nhavens