首先和加载天地图一样,还是需要在Cesium官网注册个账号 ,需要token才可以加载三维地球。如果不想申请账号,在官网例子中有个token也可以直接拿来用。
Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlODhhYTdhMC1lZmE3LTQzYzQtODY2MS01MDI0ZjQ3Y2EzMjYiLCJpZCI6MTg2NzI4LCJpYXQiOjE3MDM3MzEzMzV9.yki8P_tt3utNV9imqphGEvR0NIJi0mUr5elAnZ6YavE';
npm安装cesium js包
npm install cesium
在Vue中引入Cesium依赖包
import { Cartesian3, Ion, Terrain, Viewer } from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
在mounted方法中设置token,初始化三维地球并定义初始位置等信息。
<template>
<div
id="earthDiv"
style="width: 880px; height: 600px; margin-right: 10px"
></div>
</template>
<script>
import { Cartesian3, Ion, Terrain, Viewer } from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
export default {
name: "HelloWorld",
props: {
msg: String,
},
mounted() {
Ion.defaultAccessToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlODhhYTdhMC1lZmE3LTQzYzQtODY2MS01MDI0ZjQ3Y2EzMjYiLCJpZCI6MTg2NzI4LCJpYXQiOjE3MDM3MzEzMzV9.yki8P_tt3utNV9imqphGEvR0NIJi0mUr5elAnZ6YavE";
const viewer = new Viewer("earthDiv", {
terrain: Terrain.fromWorldTerrain(),
});
viewer.camera.flyTo({
destination: Cartesian3.fromDegrees(108.93, 34.26, 8000),//经纬度,高度
duration: 10,//镜头飞到指定位置的时间(秒)
});
},
};
</script>
从Vue项目文件夹中的\node_modules\cesium\Build\Cesium路径下找到下面这四个文件夹,Copy到Vue项目中。
在App.vue中定义一个全局变量“window.CESIUM_BASE_URL”指向上面这四个文件夹的存放位置,我这里放到了cesium文件夹下,所以就写上“/cesium/”,不需要加前面的“public”。
window.CESIUM_BASE_URL = "/cesium/";
运行npm run serve启动项目,发现报了这个错误。
ERROR in ./node_modules/@cesium/engine/Source/Core/Resource.js 1874:57-71
Module not found: Error: Can't resolve 'http' in 'D:\xxxx\xxxx\node_modules\@cesium\engine\Source\Core'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
- install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "http": false }
解决方法是需要安装node-polyfill-webpack-plugin,在vue.config.js中添加以下配置。
npm install node-polyfill-webpack-plugin
const { defineConfig } = require('@vue/cli-service')
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [new NodePolyfillPlugin()],
}
})
这样我们再运行npm run serve启动项目,三维地球即可成功加载,并在设定时间内慢慢飞向指定位置。