【问题标题】:Moving google maps api code to separate file + jquery将google maps api代码移动到单独的文件+ jquery
【发布时间】:2015-11-09 11:44:54
【问题描述】:

这一次,我直接进入正题:

HTML:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="code.js"></script>
</head>

<body>
    <div id="map"></div>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=*snip*&callback=initMap">
    </script>
</body>

</html>

Code.js:

$(document).ready(function () {
    var map;

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -34.397,
                lng: 150.644
            },
            zoom: 10
        });
    }
});

结果:

Uncaught TypeError: window.initMap is not a function.

提示?

另外,想知道这部分是否:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=*snip*&callback=initMap">

可以移动到同一个 code.js 文件中。

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    更新:亲爱的朋友们,这是一个糟糕的答案。一个非常糟糕的答案。
    好吧,解决方案很好,解释不是。这是我的耻辱:)

    您不需要设置$(document).ready(),因为这会告诉浏览器在文档准备好时调用initMap();,但您的 goolemaps 脚本中有 async 和 defer,这意味着当您尝试执行你的启动你错过了一些东西。

    更新答案: 您只需要 javascript 文件中的 initMap() 函数。 如果您将函数包装在 $(document).ready() 函数中(闭包、闭包、闭包人),则此函数 (initMap) 在 $(document).ready() 之外不可用。

    例如: 这不起作用并返回错误 'Uncaught ReferenceError: myfunc is not defined'

         $(document).ready(function(){
            myfunc = function(){
              console.log('myfunc');
            }
         })
         myfunc();
    

    这将起作用:

        $(document).ready(function(){
            myfunc = function(){
                console.log('myfunc');
            }
            myfunc();
        })
    

    这将起作用:

        myfunc = function(){
            console.log('myfunc');
        }
        $(document).ready(function(){
            myfunc();
        })
    

    你为什么这么说?因为 javascript scope and closures 当然是如何工作的 :)

    【讨论】:

    • 这是否意味着解决方案是从地图脚本中删除asyncdefer
    • 请详细说明“缺少一些东西”可能指的是什么
    • 我更新了我的答案。感谢您提醒我这一点,以便我可以更新我的答案;)
    【解决方案2】:
    1. 保持 .....&amp;callback=initMap" async defer&gt;&lt;/script&gt; 不变
    2. 将 google 的 &lt;script 标签放在尽可能高的位置
    3. 写在你的脚本中

      function initMap() {}; // now it IS a function, lol, and it is in global
      
      $(() => { // jquery on load
        initMap = function() {
          // your code like...
          var map = new google.maps.Map(document.getElementById('map'), {...});
          // and other stuff...
        }
      })
      

    我的复杂答案是here

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 2011-12-06
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多