我正在使用meteorjs,我想使用cesiumjs。我的代码如下:

在启动js文件的客户端代码中:

Meteor.startup(function() {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');  // optional
  script.setAttribute('src', 'http://cesiumjs.org/releases/1.18/Build/Cesium/Cesium.js');
  document.getElementsByTagName('head')[0].appendChild(script);
});


在我拥有的模板中,我包括“ cesiumContainer”的div,并且在mytemplate.js中:

Template.mytemplate.rendered = function() {
    var viewer = new Cesium.Viewer('cesiumContainer');
};


我得到的错误是:

Exception from Tracker afterFlush function:
debug.js:41 ReferenceError: Cesium is not defined
    at Template.mytemplate.rendered (mytemplate.js:4)


对于我的CSS,我只将其包含在“ head”标签的“ client”目录中的index.html页面中(这样做不对吗?):

  <style>
    @import url(http://cesiumjs.org/releases/1.18/Build/Cesium/Widgets/widgets.css);
    #cesiumContainer {
      width: 100%; height: 300px; margin: 0; padding: 0; overflow: hidden;
    }
  </style>


我如何正确地将此外部库包含到我的meteorjs应用程序中?此外,如果我的mytemplate2显示在同一页面上(我正在使用FlowLayout),如何正确访问“查看器”变量?通常将其设置为“全局” VIEWER变量吗?

最佳答案

我不是流星专家,但我要指出,您的脚本加载是异步的。在尝试访问Cesium之前,您需要等待添加的onload标签触发script事件。另外,请使用document.head而不是查找标签。

我希望您发布的样式内容能正常工作。如果更熟悉,也可以使用经典的link rel="stylesheet"



var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://cesiumjs.org/releases/1.18/Build/Cesium/Cesium.js');
document.head.appendChild(script);

script.onload = function() {
  document.getElementById('msg').innerHTML = 'Cesium version: ' + Cesium.VERSION;
}

// Cesium is undefined here.  Call your code from the onload handler above.

<p id="msg">Loading...</p>

09-25 18:26