一直有關注 Cesium ,不過沒有進行實際行動。
昨天事情不多就想着展示一個示例看看。
一、Vue 集成
首先是安裝 cesium 包(創建 Vue 項目已經完成集成上):
npm install cesium
直接引入
import * as Cesium from 'cesium'
運行代碼發現會報錯:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | | function getWorker(options = {}) { > return new Worker(new URL(workerData.scripts[0], import.meta.url), options); | } |
經過查找,需要安裝以下 webpack 插件並配置:
1、copy-webpack-plugin
用於把一些 Cesium 文件拷貝到打包目錄下直接使用。
2、@open-wc/webpack-import-meta-loader(vue3 + vite 沒有此問題)
cesium 中使用到了 import.meta ,webpack 對此需要 loader 進行預處理。
在 vue.config.js 中對應的配置(webpack.config.js 中配置可對應):
const CopyWebpackPlugin = require('copy-webpack-plugin') const webpack = require('webpack') module.exports = { configureWebpack: { plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'node_modules/cesium/Build/Cesium/Workers', to: 'Workers' }, { from: 'node_modules/cesium/Build/Cesium/ThirdParty', to: 'ThirdParty' }, { from: 'node_modules/cesium/Build/Cesium/Assets', to: 'Assets' }, { from: 'node_modules/cesium/Build/Cesium/Widgets', to: 'Widgets' } ] }), new webpack.DefinePlugin({ CESIUM_BASE_URL: JSON.stringify('') }) ], module: { unknownContextCritical: false, rules: [ { test: /\.js$/, use: { loader: '@open-wc/webpack-import-meta-loader' } } ] } } }
按照上面操作后,你以為大功告成(有一部分走運的成功!)。
注意:
copy-webpack-plugin 版本問題,如果太高版本(建議 6.0左右及以下),會報錯:
compilation.getCache is not a function
如果有這個錯誤,卸載原先的 copy-webpack-plugin 安裝較低版本
二、基礎使用
准備工作就緒后,下面開始 Cesium 之旅。
下面是基本的代碼
初始化 viewer、設置 hoemView、設置默認 view、設置在線地圖等
<template> <div id="cesiumContainer" class="cesium-box" /> </template> <script> import 'cesium/Build/Cesium/Widgets/widgets.css' import * as Cesium from 'cesium' const googleMap = 'https://mt0.google.com/vt/lyrs=r&x={x}&y={y}&z={z}' // const gaodeMap = 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}' export default { name: 'App', data() { return { cesiumViewer: null, homeView: null } }, created() { this.homeView = { destination: Cesium.Cartesian3.fromDegrees(119.966746, 30.270928, 5000), orientation: { // 航向 heading: Cesium.Math.toRadians(0), // 俯仰 pitch: Cesium.Math.toRadians(-90), // 滾轉 roll: 0.0 } } }, mounted() { // this.cesiumViewer = new Cesium.Viewer('cesiumContainer') this.cesiumViewer = new Cesium.Viewer('cesiumContainer', { animation: false, timeline: false, // baseLayerPicker:false, imageryProvider: new Cesium.UrlTemplateImageryProvider({ url: googleMap }) }) // 初始化視角(飛行模式) this.cesiumViewer.camera.flyTo(this.homeView) // 初始化視角 // this.cesiumViewer.camera.setView(this.homeView) // 重寫 homeButton 事件 this.cesiumViewer.homeButton.viewModel.command.beforeExecute.addEventListener((e) => { // 阻止事件繼續傳遞 e.cancel = true this.cesiumViewer.camera.flyTo(this.homeView) }) } } </script>
這些是最基礎的用法,后續繼探索 Cesium。