google.load从不调用回调 [英] google.load never calls callback

查看:215
本文介绍了google.load从不调用回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Google地球插件,并发现它是如何调用的相当特别:如果在JavaScript执行的主流之外调用(例如通过setTimeout),它只是拒绝调用load回调。下面的示例是自包含插图。

I am trying to use the Google Earth plug-in, and have found that it's rather particular about how it is called: if called outside the main flow of the Javascript execution (via setTimeout, for example), it simply refuses to call the load callback. The example below is self-contained illustration. Change change which of the last two lines is commented out to see it work or not.

发生了什么事?

<html>
<head>
  <title>Sample</title>
  <script type="text/javascript" src="https://www.google.com/jsapi"> </script>
  <script type="text/javascript">
      var ge;
      function init() {
        console.log('Initing');
        function cb(instance) {
          ge = instance;
          ge.getWindow().setVisibility(true);
          console.log('Ok');
        };
        function fail() {}
        google.earth.createInstance('map3d', cb, fail);
      }
      function loadTheMap() {
        google.load("earth", "1.x");
        google.setOnLoadCallback(init);
        console.log('Callback is set');
      }
      //loadTheMap(); // works
      setTimeout(loadTheMap, 200); // Does not work
  </script>

</head>
<body>
  <div id="map3d" style="height: 400px; width: 600px;"></div>
</body>
</html>


推荐答案

这是一个时间问题。

google.setOnLoadCallback()可让您指定在网页加载时调用的函数。

google.setOnLoadCallback() lets you specify a function that is called when the page loads.

如果你使用 setTimeout(),就会调用 setOnLoadCallback / code> 之后网页已加载,因此它从不调用您的函数。

When you use setTimeout() like that, it is calling setOnLoadCallback() after the page has already loaded, so it never calls your function.

而不是使用 google.setOnLoadCallback()您可以这样做:

Instead of using google.setOnLoadCallback() you could do this:

  function loadTheMap() {
    google.load("earth", "1.x", {"callback" : init});
    console.log('Callback is set');
  }

  setTimeout(loadTheMap, 200);

我有点困惑,因为Google文档表示地球不支持动态加载,但我看到它在api示例中完成,它适用于我(在Chrome中)。

I'm a little confused though, because the Google docs say that dynamic loading is not supported for Earth, but I've seen it done in the api samples, and it works for me (in Chrome).

这篇关于google.load从不调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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