小试Mars3d---vue2

1,301 阅读1分钟

一、安装相应插件

npm install mars3d --save //安装Mars3d主库
npm install mars3d-space --save //安装mars3d插件(按需安装)

二、vue-cli 技术栈时 的项目配置修改

修改文件:vue.config.js,可参考官网配置及项目,这里我使用的是vue2版本,可以参考vue2-template

关键代码及步骤:

  • 安装依赖库(注意copy-webpack-plugin与webpack版本的依赖,可能需要按webpack对应版本的相关版本安装)
npm install copy-webpack-plugin --save-dev
  • 修改 vue.config.js 配置文件
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  configureWebpack: (config) => {
    const cesiumSourcePath = 'node_modules/mars3d-cesium/Build/Cesium/' // cesium库安装目录
    const cesiumRunPath = './mars3d-cesium/' // cesium运行时路径

    const plugins = [
      // 标识cesium资源所在的主目录,cesium内部资源加载、多线程等处理时需要用到
      new webpack.DefinePlugin({
        CESIUM_BASE_URL: JSON.stringify(path.join(config.output.publicPath, cesiumRunPath))
      }),
      // Cesium相关资源目录需要拷贝到系统目录下面(部分CopyWebpackPlugin版本的语法可能没有patterns)
      new CopyWebpackPlugin({
        patterns: [
          { from: path.join(cesiumSourcePath, 'Workers'), to: path.join(config.output.path, cesiumRunPath, 'Workers') },
          { from: path.join(cesiumSourcePath, 'Assets'), to: path.join(config.output.path, cesiumRunPath, 'Assets') },
          { from: path.join(cesiumSourcePath, 'ThirdParty'), to: path.join(config.output.path, cesiumRunPath, 'ThirdParty') },
          { from: path.join(cesiumSourcePath, 'Widgets'), to: path.join(config.output.path, cesiumRunPath, 'Widgets') }
        ]
      })
    ]

    return {
      module: { unknownContextCritical: false }, // 配置加载的模块类型,cesium时必须配置
      plugins: plugins
    }
  }
}

三、新建 DIV容器 + 创建地图

在需要呈现地图的html页面或相关vue/react等组件中,加上 div 容器,并注意设置 div 的 css 高宽样式。

<div id="mars3dContainer" class="mars3d-container"></div>

在对应技术栈的相关代码出,使用Map 地图类 (opens new window)类创建三维地图场景,加入下面代码:

<template>
  <div id="mars3dContainer" class="mars3d-container"></div>
</template>
<script>
import Vue from "vue";

// 使用免费开源版本
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";

//为了方便使用, 将Mars3d绑在原型链上,在其他vue文件,直接 this.mars3d 来使用
Vue.prototype.mars3d = mars3d;
Vue.prototype.Cesium = mars3d.Cesium;
export default {
  name: "mars3dViewer",
  props: {},
  components: {},
  data() {
    return {};
  },
  computed: {},
  watch: {},
  methods: {
    mapTome() {
      var mapOptions = {
        basemaps: [{ name: "天地图", type: "tdt", layer: "img_d", show: true }],
      };
      var map = new mars3d.Map("mars3dContainer", mapOptions); //支持的参数请看API文档:http://mars3d.cn/api/Map.html
      console.log(map, "map");
    },
  },
  created() {
    this.mapTome();
  },
  mounted() {},
  beforeDestroy() {},
};
</script>
<style scoped></style>

详细信息可见官网

四、问题

这里出现了报错信息 :vue.runtime.esm.js?8642:4560 [Vue warn]: Error in created hook: "TypeError: Cannot read properties of null (reading 'appendChild')" found in---> at src/views/index.vue

image.png

解决办法:this.renderFunc();应该放到mounted生命周期里执行

image.png