【问题标题】:How to wait till the google maps API has loaded before loading a google.maps.OverlayView derived class如何在加载 google.maps.OverlayView 派生类之前等待加载 google maps API
【发布时间】:2015-09-27 13:49:51
【问题描述】:

我有一个单独的 label.js 文件,我在其中定义了一个自定义叠加层。它使用 google.maps.OverlayView 作为原型:

Label.prototype = new google.maps.OverlayView();

我不确定在我的 index.html 文件中将此 js 文件的脚本标记放在何处。如果我将脚本标签放在谷歌地图加载标签下方,如下所示:

....
        <script async defer
            src="https://maps.googleapis.com/maps/api/js?...
        </script>
        <script src="js/label.js"></script>
    </body>
</html>

label.js 文件在 maps api 尚未加载时立即加载,导致错误。

我目前通过在我的地图加载回调中手动加载 JS 来解决这个问题:

function initMap() {
    gMap = new google.maps.Map(document.getElementById(strMapDivName), {
        center: {lat: 21, lng: 78},
        mapTypeId: google.maps.MapTypeId.HYBRID,
        zoom: 6,
        heading: 90,
        tilt: 0
    });

    // Load label.js afterwards so we can be sure that the google maps api has loaded
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", "js/label.js")

    document.getElementsByTagName("head")[0].appendChild(fileref)

}

这是解决这个问题的最佳方法吗?

【问题讨论】:

  • 我会说这是异步加载 maps-API 的最佳方式

标签: javascript google-maps google-maps-api-3


【解决方案1】:

您应该在 API 调用中包含一个回调函数。

<script async defer src="https://maps.googleapis.com/maps/api/js?callback=myFunction"></script>

然后您可以在回调函数中包含任何与地图相关的代码:

function myFunction() {
  // Your code here
}

如果您需要等到地图“准备就绪”,即显示地图时显示地图选项和“空闲”,您可以使用:

google.maps.event.addListenerOnce(map, 'idle', function () {
    // map is ready
});

但您仍应将其包含在回调函数中。

【讨论】:

    【解决方案2】:

    我知道为时已晚,但我在下面使用此代码

    var mapWaitCount = 0;
    var mapWaitMax = 5;
    
    function map_load(param1, param2, ...) { // if you need any param
        mapWaitCount++;
        // if api is loaded
        if(typeof google != 'undefined') {
            // your code here 
        }
        // try again if until maximum allowed attempt
        else if(mapWaitCount < mapWaitMax) {
            console.log('Waiting attempt #' + mapWaitCount); // just log
            setTimeout(function() { map_load(); }, 1000);
        }
        // if failed after maximum attempt, not mandatory
        else if(mapWaitCount >= mapWaitMax) {
            console.log('Failed to load google api');
        }
    }
    
    map_load(param1, param2, ...) { // if you need any param
    

    它使用超时等待加载,多次尝试后它会停止

    【讨论】:

    • 我认为你的解决方案是最可靠的解决方案,但是我会在 else if(mapWaitCount &lt;= mapWaitMax) 中更改 else if(mapWaitCount &lt; mapWaitMax) 并将最后一个 else 更改为 &gt; 而不是 &gt;=,因为如果你在开始时增加计数器,它只会尝试 4 次,而不是 5 次 :)
    【解决方案3】:

    这是我制作并为我工作的泛型。

    1) 定义谷歌地图加载后要执行的功能

    function ToExecuteAfterLoaded()
      {
      // Doing something here ///
      console.log("Executing this function"); // per example //
      }
    

    2) 等待函数

    function WhenGoogleLoadedDo(fnt)
       {
       if(typeof google != 'undefined')
          fnt();
       else
          setTimeout(function()
             {(function(fnt)
                {
                WhenGoogleLoadedDo(fnt)
                })(fnt)}, 500); // You can set timer as you wish //
       }
    

    3) 在你的脚本中像这样调用 ToExecuteAfterLoaded

    WhenGoogleLoadedDo(ToExecuteAfterLoaded);
    

    【讨论】:

      【解决方案4】:

      用 DOMContentLoaded 包裹您的自定义标签怎么样?

            document.addEventListener("DOMContentLoaded", function(event) {
                  Label.prototype = new google.maps.OverlayView();
            });
      

      参考: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

      【讨论】:

      • 不好。不保证异步在 domcontentloaded 之前运行。只有 defer 是。
      【解决方案5】:

      更新一个老问题;在 React 中我使用了 NPM 模块:load-google-maps-api

      在意识到这存在并且可以节省一些时间之前,我开始自己创造它。

      它将以承诺格式加载地图 API,因此您可以为加载后提供回调函数。

      loadGoogleMapsApi().then(function (googleMaps) {
        new googleMaps.Map(document.querySelector('.map'), {
          center: {
            lat: 40.7484405,
            lng: -73.9944191
          },
          zoom: 12
        })
      }).catch(function (error) {
        console.error(error)
      })
      

      【讨论】:

        猜你喜欢
        • 2021-06-25
        • 2019-10-28
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多