【问题标题】:jQuery getJSON() not working with Google maps apijQuery getJSON() 不适用于 Google 地图 API
【发布时间】:2014-03-30 16:29:28
【问题描述】:

我是 JSON 和谷歌地图的新手。所以请告诉我我错过了什么

   <!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.15&sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>

    $function({
    $("#search").click(function(){
        $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=awan%20town&sensor=false",function(result){
            $.each(result,function(i,field){
                $("#map-canvas").append(field + " " );
            });
        });
    });
}); 



</script>
</head>
<body>

<button  id="search">Search</button>
<div id="map-canvas" style="width:100%;height:100%;"></div>
</body>
</html>

【问题讨论】:

    标签: jquery json google-maps-api-3


    【解决方案1】:

    尝试将您的代码包装在 DOM 就绪处理程序 $(function() {...}); 中,以确保在执行 jQuery 代码之前已正确加载所有 DOM 元素:

    $(function () {
        $("#search").click(function () {
            $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=awan%20town&sensor=false", function (result) {
                $.each(result, function (i, field) {
                    $.("#map-canvas").append(field + " ");
                });
            });
        });
    });
    

    你还需要改变:

    $.("#search")
    $.("#map-canvas")
    

    到:

    $("#search")
    $("#map-canvas")
    

    这里的选择器之前不需要.

    【讨论】:

    • 要从返回的 JSON 中获取哪些字段?
    • 我猜我写的代码会从这个 URL 全部返回,我实际上想要获取任何特定字段如何做到这一点maps.googleapis.com/maps/api/geocode/…
    • 我建议您学习有关 JSON 的基本教程,以更好地了解 JSON 的工作原理。
    • 我在 w3school 上做过,但现在如果你只是更正我的代码说我想访问 formatted_address 我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多