移动谷歌地图api代码到单独的文件+ jquery

Moving google maps api code to separate file + jquery

本文关键字:文件 jquery 单独 谷歌地图 api 代码 移动      更新时间:2023-09-26

这一次,我将直接进入主题:

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文件

更新:亲爱的朋友们,这是一个糟糕的回答。一个非常糟糕的答案。
解决办法还不错,但解释却不行。这是我的耻辱:)

你不需要设置$(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的作用域和闭包的工作方式:)

  1. 保持.....&callback=initMap" async defer></script>不变
  2. 把google的<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...
      }
    })
    

我的复杂答案在这里