【问题标题】:jQuery Google Maps questionjQuery 谷歌地图问题
【发布时间】:2011-04-26 15:47:22
【问题描述】:

谁能帮我理解为什么下面的代码在第二个警报中没有显示任何内容?浏览到我传递给 getJSON() 的相同 url 会在我的浏览器窗口中产生输出。

<!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>

【问题讨论】:

    标签: jquery google-maps


    【解决方案1】:

    问题与same origin policy 有关。 This post 非常有帮助。我已修改我的代码以使用Client-side Google Maps Geocoding API。这是工作代码:

    <!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>
    

    【讨论】:

      【解决方案2】:

      您的 obj 变量似乎未定义。你的意思是:

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

      【讨论】:

      • 噢!好决定。我在原来的帖子中修复了这个问题,但第二个警报仍然没有任何内容。
      • 尝试在 for 循环中添加警报。然后在第一个之后中断,否则您将在接下来的几个小时内关闭对话框......
      • 我尝试将 alert(out) 移到 for 循环中,但后来我停止收到第二个警报。