Google 地图 v3 与 MeteorJS 加载同步问题

2024-04-07

我的应用程序在 MeteorJS 框架上运行并使用谷歌地图(javascript api v3)。谷歌地图加载方案类似于此中解释的方案post https://stackoverflow.com/a/16797219/942899,和官方的很相似tutorial https://developers.google.com/maps/documentation/javascript/tutorial#HelloWorld。但有时加载应用程序会抛出重复的异常:

未捕获的类型错误:无法读取 null 的属性“lat”

下面的代码导致了这个问题(不幸的是,被缩小了):

function $H(a, b, c, d) {
    var e = c[B], f = new jB(d);
    f[p]("title", e);
    b[p]("draggableCursor", e, "cursor");
    var g = e.Nb;
    Q("click dblclick rightclick mouseover mouseout mousemove mousedown mouseup".split(" "), function(d) {
        S[z](b, d, function(e, q, s) {
            var v = a[Wp](e, !0);
            e = new U(v.lat(), v.lng()); //here, v is probably null 
        })
    })
}

我很确定这是加载同步问题:a)应用程序工作正常,并且仅在加载的第一秒内就抛出错误。 b) 这种情况在生产中经常发生,自然加载时间更长。

附:如果有帮助的话,我可以链接到我的应用程序。


我就是这样解决的google-maps v3在我的应用程序中加载,基本上它涉及声明一个反应性ready上的方法GoogleMaps一旦我们确定脚本已加载,该对象就会设置为 true。

client/lib/google-maps.js :

GoogleMaps={
  // public methods
  config:function(options){
    _.extend(this,options);
  },
  ready:function(){
    this._loadingDependency.depend();
    return this._ready;
  },
  // private methods
  _loaded:function(){
    this._ready=true;
    this._loadingDependency.changed();
  },
  // public members
  apiKey:"",
  // private members
  _ready:false,
  _loadingDependency:new Deps.Dependency()
};

_googleMapsLoaded=function(){
  GoogleMaps._loaded();
};

Meteor.startup(function(){
  if(!GoogleMaps.apiKey){
    throw new Meteor.Error(-1,"API key not set, use GoogleMaps.config({apiKey:YOUR_API_KEY});");
  }
  $.getScript("https://maps.googleapis.com/maps/api/js?key="+GoogleMaps.apiKey+"&callback=_googleMapsLoaded");
});

现在我们可以使用ready里面的方法GoogleMapsView模板rendered打回来 :

client/views/google-maps-view/google-maps-view.js :

<template name="GoogleMapsView">
  <div class="google-maps-view"></div>
</template>

Template.GoogleMapsView.rendered=function(){
  this.autorun(_.bind(function(){
    if(GoogleMaps.ready()){
      this.mapOptions={
        center:new google.maps.LatLng(48.8582,2.2945),
        zoom:15
      };
      this.map=new google.maps.Map(this.find(".google-maps-view"),this.mapOptions);
    }
  },this));
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google 地图 v3 与 MeteorJS 加载同步问题 的相关文章