<!-- "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.
};
1
在异步加载这个适合我(感谢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);
}
10 回答
如果谷歌未定义(即如果API未加载),
if (google.maps) {...}
将给出参考错误 .而是使用
if (typeof google === 'object' && typeof google.maps === 'object') {...}
检查它是否成功加载 .目前的答案都没有为我提供100%的一致性(不包括Google Loader,我认为检查
google.maps
的存在是否足以确保库已完成加载 . 以下是我看到的网络请求请求Maps API和可选的Places库:第一个脚本定义了
google.maps
,但是您可能需要的代码(google.maps.Map
,google.maps.places
)将不会出现,直到其他一些脚本加载完毕 .在加载Maps API时定义回调会更安全 . @verti的答案几乎是正确的,但仍然依赖于不安全地检查
google.maps
.相反,这样做:
HTML:
JS:
在异步加载这个适合我(感谢DaveS):
您可以考虑使用Google Loader
它将加载您指定的javascript文件,然后执行
optionalSettings
参数中指定的回调 .编辑:如果你不害怕"not explicit"那么你可以使用以下,否则如果你不确定是否只有一个
google
变量的实例,那么使用DaveS答案 .检查google maps v3 api是否已加载:
在这个条件变量
google
将使用javascript事实,所以如果它将是函数或对象或字符串,它将成为真,然后将尝试访问该对象内的maps
.反之:
一个简单的
if(google && google.maps)
检查对我不起作用;我尝试访问API时仍然出错:在我的情况下,这可能是由于我的鼠标事件处理程序在map API甚至完成下载之前被触发 . 在这种情况下,为了可靠地检查是否加载了map,我创建了一个“gmaps”别名并在dom ready上初始化它(使用JQuery):
然后在我的事件处理程序中我可以简单地使用:
try
or
since 我在手机上有 problem 以下内容:
你知道,接受的答案存在问题 . 如果脚本加载了 'typeof google' may return undefined and throw an error ,它将返回true . 解决方法是:
if ('google' in window && typeof google === 'object' && typeof google.maps === 'object') {...}
这可确保始终返回布尔值 .
我相信你可以使用
if(google && google.maps){ … }
执行此操作,除非你的意思是this post,这是关于Maps API V2的,但有人为v3 here更新了它 .如果你使用
jQuery
,我有个好消息:它类似于answer-17702802