2015-10-16 49 views
1

请帮我调试Chrome不认识谷歌的原因。 我得到这个错误:
未捕获的引用错误谷歌未定义

Uncaught ReferenceError: google is not defined

我提出API脚本顶部,失败。 我调整了自己的代码以匹配Google的文档,失败。 Chrome是否会导致我的问题?

<!DOCTYPE html> 
<html> 
<head> 
    <title>weather map</title> 
    <style type="text/css"> 
    html, body { 
     margin: 0; 
    } 
    #map-canvas { 
     width: 100%; 
     height: 100%; 
    } 
    </style> 
</head> 
<body> 
    <div id="container"> 
     <h1>Map Test</h1> 
     <div id="map-canvas"> 
     </div> 
    </div> 

    <script type="text/javascript" src="/js/jquery-2.1.4.min.js"></script> 

    <script type="text/javascript"> 
     $(document).ready(function() { 
      google.maps.event.addDomListener(window, 'load', initMap); 
     }); 

     var map; 
     function initMap() {   
      map = new google.maps.Map(document.getElementById("map- canvas"), { 
       center: {lat: 29.423017, lng: -98.48527}, 
       zoom: 8, 
      }); 
     } 
    </script> 
    <script async defer 
     src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_WAS_HERE_&callback=initMap"> 
    </script> 
</body> 
</html> 
+0

控制台是否告诉你哪行代码引起了引用错误? –

+1

尝试从脚本标记中删除“延迟”。延迟阻止脚本标记执行,直到DOM被解析。由于你的$(document).ready函数出现在脚本标记之前,它首先尝试执行。或者,将$(document).ready函数上方的maps.googleapis的脚本标记移动。 –

+0

Vincent,它说这行是问题:
google.maps.event.addDomListener(window,'load',initMap); – Paula

回答

1

您正在异步加载Google Maps JavaScript API。在运行initMap(回调)函数之前,您不能使用它的任何方法。

working fiddle

代码片段:

var map; 
 

 
function initMap() { 
 
    map = new google.maps.Map(document.getElementById("map-canvas"), { 
 
    center: { 
 
     lat: 29.423017, 
 
     lng: -98.48527 
 
    }, 
 
    zoom: 8 
 
    }); 
 
}
html, 
 
body { 
 
    margin: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
} 
 
#map-canvas { 
 
    width: 100%; 
 
    height: 100%; 
 
}
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"> 
 
</script> 
 
<div id="container" style="height:100%; width:100%;"> 
 
    <h1>Map Test</h1> 
 
    <div id="map-canvas"></div> 
 
</div>

1

你不应该把你的谷歌地图事件$(document).ready();因为window.load已经注册了一个事件监听器,并应足够。

您的Google地图脚本标记也应该在您的JavaScript代码之上,并且事件侦听器也应该移到该函数的下方。

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

<script type="text/javascript"> 
    var map; 
    function initMap() {   
     map = new google.maps.Map(document.getElementById("map- canvas"), { 
      center: {lat: 29.423017, lng: -98.48527}, 
      zoom: 8, 
      }); 
     } 

    google.maps.event.addDomListener(window, 'load', initMap); 
</script> 

下次您应该仔细阅读文档。

相关问题