流星模板异步呈现 - 无法读取 null 的属性“偏移宽度”

Meteor template rendered asynchronously - Cannot read property 'offsetWidth' of null

本文关键字:属性 偏移宽度 null 读取 异步 流星      更新时间:2023-09-26

我想我在使用 gmaps api 时偶然发现了这个奇怪的问题。我随机收到一个问题,说绘制地图时无法读取空的属性'偏移宽度'。

主要.html

<div class="container-fluid">
   {{> mapPlaceHolders}}
   <div class="row">
      {{> dispMap}}
  </div>
</div>
<template name="mapPlaceHolders">
{{#if currentUser}}
    <div class = "row">
        <div class="google-map-canvas col-xs-9" id="map-canvas"></div>
        <div class="col-xs-3" id="directions-panel"></div>
    </div>
    <div id="outputDiv"></div>
{{/if}}
</template>

Template.dispMap.rendered = function(){
   gmap.initialize();
}

我的理解是,首先mapPlaceHolder会在gmap初始化之前将我的div map-canvas添加到窗口中。但是随机我看到错误

     Exception from Tracker afterFlush function: Cannot read property 'offsetWidth' of null
TypeError: Cannot read property 'offsetWidth' of null
    at aj (https://maps.gstatic.com/cat_js/maps-api-v3/api/js/19/1/%7Bmain,geometry,places%7D.js:40:1854)
    at new Jj (https://maps.gstatic.com/cat_js/maps-api-v3/api/js/19/1/%7Bmain,geometry,places%7D.js:46:992)
    at Object.gmap.initialize (http://localhost:3000/client/helpers/gmap_helpers.js?05a616018d24094e049effd64aa94b374364fbe2:118:14)
    at Template.dispMap.rendered (http://localhost:3000/client/helpers/gmap_helpers.js?05a616018d24094e049effd64aa94b374364fbe2:251:8)
    at null.<anonymous> (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2970:21)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1720:14
    at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2029:12)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1719:15
    at Tracker.flush (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:438:11)

我找到了一种解决方法来硬编码等待时间,直到创建 map-canvas 元素,这似乎没有其他办法

Template.dispMap.rendered = function(){
function drawCanvas(){
            if($('#map-canvas').length){
                console.info("map-canvas added to the dom");
                $('#map-canvas').ready(gmap.initialize());
            }else
            {
                console.info("wait for map-canvas to be ready");
                setTimeout(drawCanvas, 500);
            }
        }
        drawCanvas();
}

改用googlemaps-mateor包,并从页眉或页脚中删除google地图脚本行。它对我有用。