Cesium + Vite 快速初始化项目


Cesium + Vite 快速初始化项目

一、环境准备

在开始之前,确保你已经安装了以下环境:

  • Node.js:v22.13.0 或更高版本
  • pnpm:10.5.0 或更高版本
  • Vue3:^3.5.13

二、安装依赖

首先,创建一个Vue3 + Vite项目:

1
2
npm create vite@latest my-cesium-project -- --template vue
cd my-cesium-project

然后安装Cesium和相关插件:

1
2
pnpm add cesium
pnpm add vite-plugin-cesium

依赖包说明

  • Cesium:一个开源的JavaScript 3D地理信息系统(GIS)库,主要用于创建高性能的三维地球和地图应用。

    • 提供高精度的地球模型,支持地形、影像和矢量数据
    • 支持点、线、面、3D模型等多种空间数据的展示
    • 支持时间序列数据的可视化,如卫星轨迹、气象变化等
    • 提供距离计算、地形分析等空间分析功能
    • 可在浏览器中运行,无需插件
  • vite-plugin-cesium:专门为Vite构建工具开发的插件,用于简化Cesium在Vite项目中的集成。

    • 自动处理Cesium的资源加载(如地形数据、影像数据、Worker脚本等)
    • 优化构建过程,提高开发和构建效率
    • 简化配置,无需手动设置Cesium的资源路径和构建选项
    • 支持热更新,提高开发体验

三、配置Vite

修改 vite.config.js 文件,添加Cesium插件:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import cesium from "vite-plugin-cesium";
import path from "path";

export default defineConfig({
plugins: [vue(), cesium()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
});

四、创建基础场景

在Vue组件中使用Cesium创建三维场景:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
<div class="cesium">
<div class="cesium-container" id="cesiumMap"></div>
</div>
</template>

<script setup>
import { onMounted } from "vue";
import { Viewer } from "cesium";

onMounted(() => {
const viewer = new Viewer("cesiumMap");
console.log("Cesium Viewer initialized:", viewer);
});
</script>

<style scoped>
.cesium {
position: relative;
height: 100%;
width: 100%;
display: flex;
}
.cesium-container {
position: relative;
height: calc(100vh - 64px);
width: 100%;
:deep(.cesium-viewer-bottom) {
display: none;
}
}
</style>

五、自定义配置

1. 移除默认控件

为了使场景更加干净,可以移除不需要的默认控件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
onMounted(() => {
const options = {
geocoder: false, // 地理编码控件
homeButton: false, // 默认相机位置控件
sceneModePicker: false, // 场景模式控件
baseLayerPicker: false, // 基础图层控件
navigationHelpButton: false, // 导航帮助控件
animation: false, // 动画控件
timeline: false, // 时间线控件
fullscreenButton: false, // 全屏控件
vrButton: false, // VR控件
infoBox: false, // 信息框控件
selectionIndicator: false, // 选择跟踪控件
};
const viewer = new Viewer("cesiumMap", options);
console.log("Cesium Viewer initialized with custom options:", viewer);
});

2. 其他常用配置

  • 设置初始视角

    1
    2
    3
    4
    5
    6
    7
    8
    viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.404, 39.915, 1000), // 北京位置
    orientation: {
    heading: Cesium.Math.toRadians(0),
    pitch: Cesium.Math.toRadians(-15),
    roll: 0,
    },
    });

六、运行项目

执行以下命令启动开发服务器:

1
pnpm dev

在浏览器中访问 http://localhost:5173,即可看到Cesium三维场景。


文章作者: 栖桐听雨声
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 栖桐听雨声 !
  目录