2015-08-16 36 views
2

這個時候,我會去切中要害:移動谷歌地圖API代碼,單獨的文件+ jQuery的

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

回答

11

更新:親愛的朋友們,這是一個可怕的答案。一個非常非常糟糕的答案。
那麼,解決方案是好的,解釋不是。這是恥辱:)

你並不需要設置一個 $(document).ready(),因爲這告訴瀏覽器調用 initMap();當文件已準備就緒,但你必須異步並在goolemaps腳本推遲,這意味着我的透當你嘗試執行你的啓蒙時,你錯過了一些東西。

更新答: 你需要在你的JavaScript文件只是initMap()功能。 如果將函數封裝在$(document).ready()函數中(閉包,閉包,閉包),那麼$(document).ready()之外的函數(initMap)不可用。

如: 這不起作用,並返回錯誤 '未捕獲的ReferenceError:MYFUNC沒有定義'

 $(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工作

+3

這是否意味着解決方案是從地圖腳本中移除'async'和'defer'? – waffl

+1

請詳細說明「缺少一些東西」可能是指 – AlleyOOP

+0

我更新了我的答案。感謝提醒我這個,所以我可以更新我的答案;) – codegaze

0
  1. 離開.....&callback=initMap" async defer></script>,因爲它是
  2. 把谷歌的<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