2016-11-06 143 views
1

我不明白是什么问题?我使用谷歌地图API的这个例子:Simple MapinitMap不是函数

<body> 
    <!-- Map Section --> 
    <section id="map"></section> 

    <script src="js/jquery.min.js"></script> 
    <script src="js/main.js"></script> 
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5Y8CqFe-4Egzl5TlPqlFvjRGcuCfHGvY&callback=initMap" async defer></script> 

</body> 

main.js:

//-------------------------------------------------- 
// Contact Map 
//-------------------------------------------------- 
function initMap() {  
    if ($("#map").length > 0) 
    { 
     var map; 
     map = new google.maps.Map(document.getElementById('map'),{ 
      center: {lat: 44.4297538, lng: 26.0649221}, 
      zoom: 16, 
      scrollwheel: false, 
      zoomControl: false, 
      panControl: false, 
      streetViewControl: false, 
      mapTypeControl: false, 
      overviewMapControl: false, 
      clickable: false 
     }); 

    } 
} 

错误:在头

message: "initMap is not a function"

name: "InvalidValueError"

回答

1

尝试移动加载脚本

<html> 
    <head> 
    <title>Simple Map</title> 
    <meta name="viewport" content="initial-scale=1.0"> 
    <meta charset="utf-8"> 

    <script src="js/jquery.min.js"></script> 
    <script src="js/main.js"></script> 
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5Y8CqFe-4Egzl5TlPqlFvjRGcuCfHGvY&callback=initMap" async defer></script> 

并确保对于正确的路径

 <script src="js/jquery.min.js"></script> 
    <script src="js/main.js"></script> 

最终尝试使用

 <script src="./js/jquery.min.js"></script> 
    <script src="./js/main.js"></script> 
+1

感谢您的回复!但我仍然有同样的错误。 – DenysM

+0

然后检查相对(或正确的脚本路径) – scaisEdge

+0

当然,我检查了它。 index.html和contact.html位于根目录中。所以,我不需要使用./ – DenysM

1

我有同样的问题与贤者(一个WordPress主题首发)WordPress模板工作相对路径。

我的JS与

(function($) { 

// all the functions to create map, center markers, etc. 

} 

包裹之后,在地图中$(document).ready

被初始化我删除(function($) { }和刚才添加的功能,而不$(document).ready那么也没关系。

此外,一定的API谷歌地图之前加载自定义的js文件:

<script src="custom-js-google-map.js"></script> 

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

有同样的问题,我个人删除&callback=initMap,使其工作。 其他线程表明initMap是你应该自己构建的函数。

+0

我有同样的问题...您的解决方案工作...从脚本调用中删除了initMap,它工作。具有讽刺意味的是,通过我相当长的一段时间,我甚至都没有在脚本行中看到这一点,因为我在另一个custom.js文件中有一个单独的'initMap()' - 所以我一直在看着它,问题是。 &callback = initMap正在调用尚未加载的函数。我的custom.js文件在地图脚本之后加载 - 故意......因此initMap尚未定义。 – rolinger