欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > cesium+vue3 DataSource学习笔记

cesium+vue3 DataSource学习笔记

2024/10/24 22:25:44 来源:https://blog.csdn.net/weixin_51983847/article/details/142854149  浏览:    关键词:cesium+vue3 DataSource学习笔记

官方文档链接:Cesium中文api文档 | Index - Cesium Documentation

官方示例链接:Cesium Sandcastle

vue for cesium:A Vue 3 based component library of CesiumJS for developers | Vue for Cesium (zouyaoji.top)

 package.js:

{"name": "demo","private": true,"version": "0.0.0","type": "module","scripts": {"dev": "vite","build": "vite build","preview": "vite preview"},"dependencies": {"cesium": "1.99","element-plus": "^2.8.1","vite-plugin-cesium": "^1.2.23","vue": "^3.4.35","vuex": "^4.0.2"},"devDependencies": {"@vitejs/plugin-vue": "^5.1.2","vite": "^5.4.0"}
}

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 { createApp } from 'vue'
// import './style.css'
import App from './App.vue'import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

App.vue:

1. Cesium Viewer 初始化

首先,您初始化了 Cesium 的 Viewer 组件,这是任何 Cesium 应用的基础。在 Vue3 中,您使用 onMounted 钩子确保在 DOM 挂载后初始化 Cesium。

onMounted(async() => {Cesium.Ion.defaultAccessToken = 'YOUR_ACCESS_TOKEN';// 初始化 Cesium Viewerviewer = new Cesium.Viewer('cesiumContainer', {shouldAnimate: true  // 场景动画设置为 true,使得场景可以流畅渲染动画效果});
});

Cesium.Ion.defaultAccessToken 用于设置 Cesium Ion 的访问令牌。Cesium Ion 提供了在线数据和服务;

shouldAnimate: true 启动场景的动画,允许动态数据(例如CZML数据源)以动画方式展现。

2.GeoJSON数据源加载
// GeoJson 数据的加载示例
const linestring1 = turf.lineString([[-24, 63],[-23, 60],[-25, 65],[-20, 69]
]);Cesium.GeoJsonDataSource.load(linestring1).then(res => {const entity = res.entities.values[0];  // 获取解析后的第一个实体viewer.entities.add(entity);  // 将实体添加到 Viewerviewer.zoomTo(entity);  // 缩放到该实体
});

turf.js:是一个处理 GeoJSON 数据的 JavaScript 库,这里您使用了 turf.lineString 来生成一条线。

Cesium.GeoJsonDataSource.load:加载 GeoJSON 数据后,会返回解析后的实体数据,您可以将其添加到 Cesium Viewer 中并自动缩放至该实体。

3. 多条线段加载(multiLineString)

多条线段的数据可以使用 turf.multiLineString 来生成,然后通过 Cesium 加载并显示。

const multiLine = turf.multiLineString([[[0, 0], [4, 4]],[[6, 6], [10, 10]]]
);Cesium.GeoJsonDataSource.load(multiLine).then(res => {viewer.dataSources.add(res);  // 添加到 Viewer 的数据源中data = res;
});

通过 turf.multiLineString 创建多条线段,并将其作为 GeoJSON 数据源加载到 Cesium Viewer 中。

4. Polygon(多边形)加载
const polygon = turf.polygon([[[-5, 52],[-4, 56],[-2, 51],[-7, 54],[-5, 52]]]
);const promise = Cesium.GeoJsonDataSource.load(polygon);
viewer.dataSources.add(promise);  // 将多边形加载到数据源
viewer.zoomTo(promise);  // 缩放至多边形区域
5. TopoJSON 数据加载

TopoJSON 是 GeoJSON 的扩展版本,优化了共享边界的处理方式。

Cesium.GeoJsonDataSource.load('/src/assets/usa.topojson').then((dataSources) => {promise = dataSources;viewer.dataSources.add(promise);  // 添加 TopoJSON 数据源viewer.zoomTo(promise);  // 自动缩放至数据
}).catch((error) => {console.error('failed to load topojson', error);
});

TopoJSON 是一种压缩的 GeoJSON 格式,适合处理大规模地理数据集。

6. KML 数据加载

KML 是 Google Earth 使用的一种基于 XML 的地理数据格式,可以通过 Cesium.KmlDataSource.load 方法加载.

const promise = Cesium.KmlDataSource.load('/src/assets/gdp2008.kmz');
viewer.dataSources.add(promise);  // 添加 KML 数据源
7. CZML 数据加载

CZML 是一种动态数据格式,用于处理需要随时间变化的场景(例如,飞行路径、卫星轨迹等)

try {const response = await fetch('/src/assets/Vehicle.czml');const data = await response.json();const dataSource = Cesium.CzmlDataSource.load(data);viewer.dataSources.add(dataSource);await dataSource.readyPromise;  // 确保数据加载完成const entity = dataSource.entities.getById('Vehicle');if (entity) {viewer.trackedEntity = entity;  // 自动跟踪 CZML 中的特定实体}
} catch (error) {console.error('Error loading the CZML data:', error);
}

这里您使用了 fetch 方法从本地加载 CZML 数据,解析后通过 Cesium.CzmlDataSource.load 加载到 Cesium Viewer 中。

8. 删除数据

通过 toDel 方法,您可以清除 Viewer 中加载的所有数据源或特定的实体。

const toDel = () => {viewer.entities.removeAll();  // 移除所有实体viewer.dataSources.removeAll();  // 移除所有数据源
};
9.整体代码:
<script setup>
import { onMounted, shallowReactive, toHandlerKey } from 'vue'
import * as Cesium from 'cesium'
import Cartographic from 'cesium/Source/Core/Cartographic';
import Viewer from 'cesium/Source/Widgets/Viewer/Viewer';
import ConstantPositionProperty from 'cesium/Source/DataSources/ConstantPositionProperty';
import InfoBox from 'cesium/Source/Widgets/InfoBox/InfoBox';
import SelectionIndicator from 'cesium/Source/Widgets/SelectionIndicator/SelectionIndicator';//提前申明
let viewer, data, promiseconst toDel = () => {// viewer.entities.removeAll()// viewer.dataSources.remove(data)//topojson// viewer.dataSources.remove(promise);}onMounted(async() => {Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlZjRiNDQyMi1mZDBhLTQxYTAtYWU4NC1hZDY4YzhjNWU3ZGEiLCJpZCI6MjMyMDI3LCJpYXQiOjE3MjI1MDEzMTd9.3lFzziTrt3ggC3pfiVmNRbSidI52EL4CsOqWKgYxHkM'// viewer是所有api的开始viewer = new Cesium.Viewer('cesiumContainer', {//开启场景动画shouldAnimate: true});//geoJson数据,geoJson是一种对各种地理数据结构进行编码的JSON数据格式。在index.html中引入turf// const linestring1 = turf.lineString(// [//   [-24, 63],//   [-23, 60],//   [-25, 65],//   [-20, 69]// ]);// console.log(linestring1)// Cesium.GeoJsonDataSource.load(linestring1).then(res => {//   const entity = res.entities.values[0]//   viewer.entities.add(entity)//   viewer.zoomTo(entity)// })// const multiLine = turf.multiLineString(//   [//     [//       [0, 0],//       [4, 4]],//       [[6, 6],//       [10, 10]//     ]//   ],//   {//     id: "inner"//   },//   {//     id: "outter"//   }// );// Cesium.GeoJsonDataSource.load(multiLine).then(res => {//   console.log(viewer.dataSources)//   viewer.dataSources.add(res)//   data = res// })// const polygon = turf.polygon(//   [//     [//       [-5, 52],//       [-4, 56],//       [-2, 51],//       [-7, 54],//       [-5, 52]//     ]//   ],//   { id: "poly1" }, // properties//   { id: "poly2" }// );// const promise = Cesium.GeoJsonDataSource.load(polygon)// viewer.dataSources.add(promise)// viewer.zoomTo(promise)//TopoJSON是GeoJSON按拓扑学编码后的拓展形式,相比GeoJSON直接使用Polygon,point之类的几何体来表示图形的方法,TopoJSON中的每一个几何体都是通过将共享边(arcs)整合后组成的。//加载topojson数据  记得提前申明promise// Cesium.GeoJsonDataSource.load('/src/assets/usa.topojson').then((dataSources) => {//   promise = dataSources;//   viewer.dataSources.add(promise);//   viewer.zoomTo(promise);// }).catch((error) => {//   console.error('failed to load topojson', error);// });//kml,基于XML语法标准的一种标记语言,采用标记结构,含有嵌套的元素和属性,应用于Google地球相关软件中,用于显示地理数据(点,线,面,多面形,多面体以及模型等)// const promise = Cesium.KmlDataSource.load('/src/assets/gdp2008.kmz')// console.log(promise)// viewer.dataSources.add(promise);//动态数据格式CZML,是JSON的子集,CZML文档包含一个JSON数组,其中数组中的每个对象字面量元素都是一个CZML Packet。//Cesium.CzmlDataSourcetry { const response = await fetch('/src/assets/Vehicle.czml')const data = await response.json(); // 如果服务器返回的是 JSON 格式的 CZML  // 注意:如果 CZML 是直接作为文本返回的,您可能需要使用 response.text() 而不是 response.json()  // 并且可能需要使用 Cesium.CzmlDataSource.load(czmlData) 来加载数据  // 假设 data 是 CZML 字符串或已经是解析后的对象  const dataSource = Cesium.CzmlDataSource.load(data);  viewer.dataSources.add(dataSource);  // 等待数据源加载完成  await dataSource.readyPromise; // 使用 readyPromise 而不是 promise  const entity = dataSource.entities.getById('Vehicle');  if (entity) {  viewer.trackedEntity = entity;  }  } catch (error) {  // 处理任何在 fetch 或 JSON 解析过程中发生的错误  console.error('Error loading the CZML data:', error);  }  
});
</script><template><div id="cesiumContainer"></div><button @click="toDel">删除</button>
</template><style scoped>
#cesiumContainer {width: 100vw;height: 100vh;overflow: hidden;
}
button{position: absolute;top: 50px;left: 50px;z-index: 999;
}
</style>


 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com