如何检查Google Maps API(v3)是否已加载?
如果由于网络连接问题(网页本地托管)API未加载,我不想执行映射脚本。
如何检查Google Maps API(v3)是否已加载?
如果由于网络连接问题(网页本地托管)API未加载,我不想执行映射脚本。
if (google.maps) {...}
如果未定义Google(即API未加载),则会导致引用错误。
相反,使用 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:
<!-- "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.
};
在异步加载中,这个方法对我有效(感谢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.load("maps", "3", {callback: myFn});
optionalSettings
参数中指定的回调函数。google.load
将抛出引用错误。尽管如此,还是感谢你的回复。 - Nirmal编辑:
如果您不介意“不明确”,则可以使用以下内容;否则,如果您不确定是否只会有一个google
变量的实例,则请使用DaveS的答案。
检查是否加载了Google Maps V3 API:
if(google && google.maps){
console.log('Google maps loaded');
}
google
将使用JavaScript的真值,因此如果它是函数、对象或字符串,它将变为true,然后尝试访问该对象内部的maps
。if(!google || !google.maps){
console.log('Not loaded yet');
}
请注意,已接受的答案存在一个问题。
如果脚本已加载,则它将返回true,否则'typeof google'可能会返回未定义并抛出错误。解决方法如下:
if ('google' in window && typeof google === 'object' && typeof google.maps === 'object') {...}
这样可以确保始终返回一个布尔值。
(google && 'maps' in google)?true:false
or
if(google && 'maps' in google){
//true
}
else{
//false
}
自从我在移动设备上遇到以下问题:
if (typeof google === 'object' && typeof google.maps === 'object') {...}
一个简单的if(google && google.maps)
检查对我没有起作用;当我尝试访问API时仍然会出现错误:
TypeError: google.maps.LatLng不是构造函数
在我的情况下,这可能是由于我的鼠标事件处理程序在地图API甚至完成下载之前就被触发了。在这种情况下,为了可靠地检查地图是否已加载,我创建了一个“gmaps”别名,并在dom ready时初始化它(使用JQuery):
var gmaps;
$(function () {
gmaps = google.maps;
});
if(gmaps) {
// do stuff with maps
}
if (typeof google === 'object' && typeof google.maps === 'object') {
gmapInit();
} else {
$.getScript('https://maps.googleapis.com/maps/api/js?key='+gApiKey+'&language=en', function(){
gmapInit();
});
}
这类似于answer-17702802
google
并不能使用,我必须使用window.google
。 - Jongoogle.maps
可能在地图 API 完全加载完成之前就被定义了,导致地图无法稳定运行。如果还有人遇到同样的问题,可以尝试我的以下解决方案,使用回调函数。 - Don McCurdy