如何检查Google Maps API是否已加载?
如何检查Google Maps API(v3)是否已加载?
我不想执行映射脚本,如果由于互联网连接问题(网页托pipe在本地)API不加载。
谢谢。
 if (google.maps) {...}会给你一个参考错误,如果谷歌是未定义的(即如果API没有加载)。 
 相反,使用if (typeof google === 'object' && typeof google.maps === 'object') {...}来检查它是否成功加载。 
 目前的答案都没有100%的一致性为我(不包括谷歌装载机,我没有尝试过)。 我不认为检查google.maps的存在就足以确保库已经完成加载。 以下是我在看到Maps API和可选的Places库被请求时看到的networking请求: 
  
 
 那第一个脚本定义了google.maps ,但是您可能需要的代码( google.maps.Map , google.maps.places )在其他一些脚本加载之前不会执行。 
 加载Maps API时定义callback要安全得多。  @ verti的答案几乎是正确的,但仍然依赖检查google.maps unsafely。 
相反,这样做:
HTML:
 <!-- "async" and "defer" are optional, but help the page load faster. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=mapsCallback"> </script> 
JS:
 var isMapsApiLoaded = false; window.mapsCallback = function () { isMapsApiLoaded = true; // initialize map, etc. }; 
在asynchronous加载这一个为我工作(感谢DaveS):
  function appendBootstrap() { if (typeof google === 'object' && typeof google.maps === 'object') { handleApiReady(); } else { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=handleApiReady"; document.body.appendChild(script); } } function handleApiReady() { var myLatlng = new google.maps.LatLng(39.51728, 34.765211); var myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } 
您可以考虑使用Google Loader
 google.load("maps", "3", {callback: myFn}); 
 它将加载您指定的JavaScript文件,然后执行在optionalSettings参数中指定的callback。 
 编辑:如果你不害怕“不明确”,那么你可以使用下面,否则如果你不确定是否只有一个googlevariables的实例,然后使用DaveS的答案。 
检查谷歌地图加载v3 api:
 if(google && google.maps){ console.log('Google maps loaded'); } 
 在这个条件variablesgoogle将使用JavaScript的真相,所以如果它将是函数或对象或string它将成为真正的,然后将尝试访问该对象内的maps 。 
和逆:
 if(!google || !google.maps){ console.log('Not loaded yet'); } 
 一个简单的if(google && google.maps)检查不适用于我; 我尝试访问API时仍然出现错误: 
TypeError:google.maps.LatLng不是一个构造函数
在我的情况下,这可能是由于我的鼠标事件处理程序在地图API甚至完成下载之前被触发。 在这种情况下,为了可靠地检查地图是否加载,我创build了一个“gmaps”别名,并在dom就绪(使用JQuery)上初始化它:
 var gmaps; $(function () { gmaps = google.maps; }); 
那么在我的事件处理程序,我可以简单地使用:
 if(gmaps) { // do stuff with maps } 
尝试
 (google && 'maps' in google)?true:false 
要么
 if(google && 'maps' in google){ //true } else{ //false } 
因为我在手机上遇到以下问题 :
 if (typeof google === 'object' && typeof google.maps === 'object') {...} 
 我相信你可以用if(google && google.maps){ … }来做到这一点,除非你指的是这个post里的内容 ,关于Maps API V2,但有人在这里更新了v3。