首先引入包
pnpm i olcs;
pnpm i -D vite-plugin-cesium
pnpm i -S cesium
在vite.config.js中配置,参考这位大佬的笔记
添加链接描述
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import cesium from 'vite-plugin-cesium';
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),cesium()],
})
在main.js配置
import * as Cesium from 'cesium'
// window['CESIUM_BASE_URL'] = '/assets/cesium/';
window['Cesium'] = Cesium
写个案例,参考大佬的文章
添加链接描述
唯一的区别是我是直接从包里引入的,大佬是将包里的文件拿出来用的
<template><div class="main"><el-checkbox v-model="state.isShow3D" label="三维地球" size="large" @change="switchTo"style="position: absolute;z-index: 99;color: white;" /><div id="cesiumContainer"></div><div id="olContainer"></div></div></template><script setup>
import * as Cesium from 'cesium';
import { onMounted, reactive } from 'vue';
import { ElCheckbox } from 'element-plus';
import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from "ol/source/XYZ";
// import olcsCamera from "./lib/ol-cesium/Camera.js";
import olcsCamera from "olcs/Camera";
import OLCesium from "olcs";
const state = reactive({isShow3D: false,element2D: {},element3D: {},camera: {},
});
const switchTo = () => {state.camera.checkCameraChange();state.element2D.style.visibility = state.isShow3D? "hidden": "visible";state.element3D.style.visibility = state.isShow3D? "visible": "hidden";
}onMounted(() => {const cesiumViewer = new Cesium.Viewer("cesiumContainer", { infoBox: false });window.cesiumViewer = cesiumViewer;//挂载到window上
// console.log(new OLCesium,'new OLCesium');const olViewer = new Map({target: "olContainer",layers: [new TileLayer({source: new XYZ({url: "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=5a257cd2df1b3311723bd77b0de14baf",}),}),],view: new View({projection: "EPSG:4326", //使用这个坐标系center: [104.704968, 31.540962], //西南科技大学zoom: 5})});state.element2D = document.getElementById("olContainer");state.element3D = document.getElementById("cesiumContainer");state.camera = new olcsCamera(cesiumViewer.scene,olViewer);state.element3D.style.visibility = "hidden";})
</script>
<style lang="less" scoped>
.main {position: relative;height: 100vh;width: 100vw;#cesiumContainer {position: absolute;height: 100vh;width: 100vw;}#olContainer {position: absolute;height: 100vh;width: 100vw;}
}
</style>
放个图片