开发者

jQuery Google Maps question

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&开发者_如何学JAVAgt;
<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>


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>


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

out += i + ": " + json[i] + "\n";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜