Google Maps API异步加载 [英] Google Maps API Async Loading

查看:43
本文介绍了Google Maps API异步加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在IE9中异步加载Google Maps API脚本:

I am loading the Google Maps API script Asynchronously in IE9 using the following code:

function initialize() {
  ...
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
  document.body.appendChild(script);
}

window.onload = loadScript;

现在的问题是,在脚本完全加载后,会自动调用 initialize()函数.但是,当有时超出用户配额时,不会调用 initialize()函数,我们会看到纯白色的屏幕,而不是map.

Now the thing is that when the script is fully loaded the initialize() function is called automatically. But when sometimes the user quota has been exceeded the initialize() function is not called and instead of map we see the plain white screen.

我想检测到这一点并启动我的自定义函数,该函数会显示一些警报,例如:错误!" .

I want to detect this and fire my custom function which displays some alert like: "Error!".

有人可以告诉我该怎么做吗?

Can anyone tell me to how to do this?

预先感谢...

推荐答案

正如安德鲁(Andrew)所述,没有直接的方法来处理此问题.但是,您至少可以考虑这种可能性.

As Andrew mentioned, there isn't a direct way to handle this. However, you can at least account for the possibility.

将超时设置为合理的时间范围(5秒?).在超时回调函数中,测试是否存在google和/或google.maps.如果不存在,则假定脚本加载失败.

Set a timeout for a reasonable time frame (5 secondes?). In the timeout callback function, test for the existence of google and/or google.maps. If it doesn't exist, assume the script load failed.

setTimeout(function() {
  if(!window.google || !window.google.maps) {
    //handle script not loaded
  }
}), 5000);
// Maps api asynchronous load code here.

这篇关于Google Maps API异步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆