google.load never calls callback

送分小仙女□ 提交于 2019-12-10 18:45:23

问题


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.

What's going on?

<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>

回答1:


This is a timing problem.

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

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

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);

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).



来源:https://stackoverflow.com/questions/15575354/google-load-never-calls-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!