Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery如何将$.getJSON或$.ajax与Google地图一起使用(不带jQuery)_Javascript_Json - Fatal编程技术网

Javascript jQuery如何将$.getJSON或$.ajax与Google地图一起使用(不带jQuery)

Javascript jQuery如何将$.getJSON或$.ajax与Google地图一起使用(不带jQuery),javascript,json,Javascript,Json,新手在谷歌地图上查询两个城市之间的距离这一简单任务上遇到了麻烦。 实际上,这是获取JSON数据并加以利用的第一次学习尝试 首先,我在谷歌上搜索了很多相关的答案。(尽管我最终在这里找到了主要答案。) 我粘贴了所有的代码,以及关于我在想什么的注释,希望有人能用初学者的术语解释我遗漏了什么 主要的问题是,我使用我尝试过的两种方法之一($.ajax,但不是$.getJSON,虽然我认为这两种方法都可以工作)获取数据,请参见代码末尾的控制台输出,但我不知道如何实际获取/使用数据。具体来说,在多嵌套对象/数

新手在谷歌地图上查询两个城市之间的距离这一简单任务上遇到了麻烦。 实际上,这是获取JSON数据并加以利用的第一次学习尝试

首先,我在谷歌上搜索了很多相关的答案。(尽管我最终在这里找到了主要答案。)

我粘贴了所有的代码,以及关于我在想什么的注释,希望有人能用初学者的术语解释我遗漏了什么

主要的问题是,我使用我尝试过的两种方法之一($.ajax,但不是$.getJSON,虽然我认为这两种方法都可以工作)获取数据,请参见代码末尾的控制台输出,但我不知道如何实际获取/使用数据。具体来说,在多嵌套对象/数组组合中,我试图获取返回的“responseText”中“routes”中“legs”中“distance”中的“text”

[编辑:]好的,我终于找到了一个存在的SO问题,这个问题[足以解决]()

事后看来,我本应该继续寻找更多现有的答案

我不确定是要离开、删除还是删除,但我会编辑一下,暂时离开,因为问题的某些部分仍然令人困惑,包括:

  • 在下面的代码中,如何使用$.getJSON——这不也应该起作用吗
  • 如何确切地知道整个JSON对象的哪一部分用作$.parseJSON()方法中的参数
  • 如果可以看到输出的对象,并且看起来对象/数组组合已经存在,那么为什么还要使用$.parseJSON。见下文评论

    <!DOCTYPE html>
    <html>
    <head>
    <title>City Distances</title>
    <script src="js/jquery.min.js"></script>
    </head>
    <body>
        <input type="text" id="city1" value="Atlanta"><br/>
        <input type="text" id="city2" value="Orlando"><br/>
        <button type="submit" id="btn">Submit</button>
    
    <script>
    
    var city1 = document.getElementById('city1');
    var city2 = document.getElementById('city2');
    var btn = document.getElementById('btn');
    var valCities = [];
    
    function getCities () {
        valCities[0] = city1.value;
        valCities[1] = city2.value;
    
    var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false";
    
        // I'm confused about what $.getJSON is supposed to get. 
    
        //  Here's why I was trying to get the JSON data. I never saw how this would work; no idea.
        var b = $.getJSON(gMap);
        // Is the data I'm looking for in here, somewhere?
        // I thought there'd be something like the c['responseText'], below.
        // (I numbered each element (g), b/c I thought I could access with [#] bracket notation).
        var g = 0;
        for (var i in b) {
                console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]);
                g += 1;
        };
    
        // jQuery method (I found more examples that used this method, so I tried this, too.)
        // I'm confused by the example showing the argument 'json' being passed in, b/c I didn't        
        // use it.
        // But c['responseText'] seemed to have the "distance" data I needed.
    
        var c = $.ajax({
            type:    "GET",
            url:     gMap,
            dataType: "json",
            success: function(json) {
    
                    // I'm trying to see what was gotten. Added counter for the elements; I 
                    // thought maybe I could access with bracket notation using the number of
                    // the element.
                    // The relevant output is listed, below, in comment at end of script.
    
                console.log("\n $.ajax success: \n")
                var h = 0;
                for (var j in c) {
                        console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]);
                    h += 1;
                }
    
    还是我应该

    总之,下面是其余部分,主要是最后的console.log输出:

                    // **And if this works, and prints out all the data:
                    var d = c['responseText'];  // (from above)
                    console.log("ddd: " + d);
    
                            /* This is what it prints to the console:
    
        ddd: {
           "routes" : [
              {
             "bounds" : {
                "northeast" : {
                   "lat" : 33.74932270,
                   "lng" : -81.37924350
                },
                "southwest" : {
                   "lat" : 28.47414120,
                   "lng" : -84.40452560
                }
             },
             "copyrights" : "Map data ©2013 Google",
             "legs" : [
                {
                   "distance" : {
                      "text" : "442 mi",
                      "value" : 710661
                   },
                            */
    
    
                    // **Then why doesn't this work? (It says routes is undefined.)
    
                    console.log(d.routes[0].legs[0].distance.text);
    
                }    
            });
        }
    
    
    
        // Event handler for the little form (which already has the two demo cities, pre-populated.
        btn.addEventListener("click", getCities, false);
    
    
    
        /*
        ** OUTPUT **
        This is the relevant JSON data returned from Google from the console.log, above.
    
        [Console output:]
    
        . . . 
    
        $.ajax: <18> c[responseText]: {
       "routes" : [
          {
             "bounds" : {
                "northeast" : {
                   "lat" : 33.74932270,
                   "lng" : -81.37924350
                },
                "southwest" : {
                   "lat" : 28.47414120,
                   "lng" : -84.40452560
                }
             },
             "copyrights" : "Map data ©2013 Google",
             "legs" : [
                {
                   "distance" : {
                      ** --- This is what I was trying to get --- **
                      **"text" : "442 mi",**
                      "value" : 710661
                   },
                   "duration" : {
                      "text" : "6 hours 13 mins",
                      "value" : 22360
                   },
                   "end_address" : "Orlando, FL, USA",
                   "end_location" : {
                      "lat" : 28.53831440,
                      "lng" : -81.37924350
                   },
                   "start_address" : "Atlanta, GA, USA",
                   "start_location" : {
                      "lat" : 33.74883970,
                      "lng" : -84.38750639999999
        */
    
    </script>
    </body>
    </html>
    
    //**如果这有效,并打印出所有数据:
    变量d=c['responseText'];//(从上面)
    控制台日志(“ddd:+d”);
    /*这是它打印到控制台的内容:
    ddd:{
    “路线”:[
    {
    “界限”:{
    “东北”:{
    “lat”:33.74932270,
    “液化天然气”:-81.37924350
    },
    “西南”:{
    “lat”:28.474120,
    “液化天然气”:-84.40452560
    }
    },
    “版权”:“地图数据©2013谷歌”,
    “腿”:[
    {
    “距离”:{
    “文本”:“442英里”,
    “价值”:710661
    },
    */
    //**那么为什么这不起作用呢?(它说路线是未定义的。)
    console.log(d.routes[0].legs[0].distance.text);
    }    
    });
    }
    //小表单的事件处理程序(已经有两个预填充的演示城市)。
    btn.addEventListener(“单击”,获取城市,错误);
    /*
    **输出**
    这是谷歌从上面的console.log返回的相关JSON数据。
    [控制台输出:]
    . . . 
    $.ajax:c[responseText]:{
    “路线”:[
    {
    “界限”:{
    “东北”:{
    “lat”:33.74932270,
    “液化天然气”:-81.37924350
    },
    “西南”:{
    “lat”:28.474120,
    “液化天然气”:-84.40452560
    }
    },
    “版权”:“地图数据©2013谷歌”,
    “腿”:[
    {
    “距离”:{
    **---这就是我想要得到的--**
    **“文本”:“442英里”**
    “价值”:710661
    },
    “期限”:{
    “文本”:“6小时13分钟”,
    “价值”:22360
    },
    “结束地址”:“美国佛罗里达州奥兰多”,
    “结束位置”:{
    “lat”:28.53831440,
    “液化天然气”:-81.37924350
    },
    “起始地址”:“美国佐治亚州亚特兰大”,
    “开始位置”:{
    “lat”:33.74883970,
    “液化天然气”:-84.3875063999999
    */
    
    这没有任何意义
    var b=$.getJSON(gMap);
    因为它是一个异步调用。您必须在done/success回调中进行结果处理。(
    $
    是jQuery,因此没有它就无法工作)。这里有很好的解释:您应该阅读关于Ajax的jQuery文档()为了对它的工作原理有一个基本的了解。还可以看一看。@FelixKling-在“我知道‘异步’是什么意思,但必须认真复习每一个单词,甚至要理解BalintB的前两句话”的阶段,你关于这个主题的长文章的链接非常有用-谢谢!@Balint Bako-谢谢你的具体链接!
                    // **And if this works, and prints out all the data:
                    var d = c['responseText'];  // (from above)
                    console.log("ddd: " + d);
    
                            /* This is what it prints to the console:
    
        ddd: {
           "routes" : [
              {
             "bounds" : {
                "northeast" : {
                   "lat" : 33.74932270,
                   "lng" : -81.37924350
                },
                "southwest" : {
                   "lat" : 28.47414120,
                   "lng" : -84.40452560
                }
             },
             "copyrights" : "Map data ©2013 Google",
             "legs" : [
                {
                   "distance" : {
                      "text" : "442 mi",
                      "value" : 710661
                   },
                            */
    
    
                    // **Then why doesn't this work? (It says routes is undefined.)
    
                    console.log(d.routes[0].legs[0].distance.text);
    
                }    
            });
        }
    
    
    
        // Event handler for the little form (which already has the two demo cities, pre-populated.
        btn.addEventListener("click", getCities, false);
    
    
    
        /*
        ** OUTPUT **
        This is the relevant JSON data returned from Google from the console.log, above.
    
        [Console output:]
    
        . . . 
    
        $.ajax: <18> c[responseText]: {
       "routes" : [
          {
             "bounds" : {
                "northeast" : {
                   "lat" : 33.74932270,
                   "lng" : -81.37924350
                },
                "southwest" : {
                   "lat" : 28.47414120,
                   "lng" : -84.40452560
                }
             },
             "copyrights" : "Map data ©2013 Google",
             "legs" : [
                {
                   "distance" : {
                      ** --- This is what I was trying to get --- **
                      **"text" : "442 mi",**
                      "value" : 710661
                   },
                   "duration" : {
                      "text" : "6 hours 13 mins",
                      "value" : 22360
                   },
                   "end_address" : "Orlando, FL, USA",
                   "end_location" : {
                      "lat" : 28.53831440,
                      "lng" : -81.37924350
                   },
                   "start_address" : "Atlanta, GA, USA",
                   "start_location" : {
                      "lat" : 33.74883970,
                      "lng" : -84.38750639999999
        */
    
    </script>
    </body>
    </html>