效果图如下:
完整代码如下:
<template>
<div>
<CesiumViewer />
</div>
</template>
<script setup>
// !项目中出现【Failed to execute 'postMessage' on 'Worker': [object Array] could not be cloned】解决方式
// ? 【https://blog.csdn.net/m0_49239918/article/details/123379640】
import * as Cesium from "cesium";
import { reactive, onMounted, onBeforeUnmount } from "vue";
import CesiumViewer from "@/components/cesiumViewer.vue";
const viewerData = reactive({
viewer: null,
dataSource: null,
highlightEntity: null,
});
onMounted(() => {
viewerData.viewer = window.cesiumViewer;
viewerData.dataSource = new Cesium.GeoJsonDataSource();
viewerData.viewer.dataSources.add(viewerData.dataSource);
// 加载行政区域的边界数据
const geojsonUrl =
"https://geo.datav.aliyun.com/areas_v3/bound/540000_full.json";
/* const geojsonOptions = {
stroke: Cesium.Color.fromCssColorString("#f4d32b"),
fill: Cesium.Color.fromCssColorString("#3df"),
strokeWidth: 6,
markerSymbol: "?",
clampToGround: true,
};
// 从 GeoJson 文件加载邻域边界
const neighborhoodsPromise = Cesium.GeoJsonDataSource.load(
"./assets/SampleData/full.geojson",
geojsonOptions
); */
viewerData.dataSource.load(geojsonUrl).then(() => {
// 设置行政区域的样式
const entities = viewerData.dataSource.entities.values;
for (let i = 0; i < entities.length; i++) {
const entity = entities[i];
entity.polygon.material = Cesium.Color.RED.withAlpha(0.5);
entity.polygon.outline = true;
entity.polygon.outlineColor = Cesium.Color.BLACK;
}
});
// 监听鼠标移动事件
viewerData.viewer.screenSpaceEventHandler.setInputAction((event) => {
const pickedObject = viewerData.viewer.scene.pick(event.endPosition);
if (
Cesium.defined(pickedObject) &&
pickedObject.id instanceof Cesium.Entity
) {
removeHighlight();
// 高亮显示行政区域
viewerData.highlightEntity = pickedObject.id;
viewerData.highlightEntity.polygon.material =
Cesium.Color.YELLOW.withAlpha(0.5);
} else {
removeHighlight();
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
});
// 移除高亮显示
const removeHighlight = () => {
if (Cesium.defined(viewerData.highlightEntity)) {
viewerData.highlightEntity.polygon.material =
Cesium.Color.RED.withAlpha(0.5);
viewerData.highlightEntity = null;
}
};
onBeforeUnmount(() => {
// 移除事件监听和高亮显示
viewerData.viewer.screenSpaceEventHandler.removeInputAction(
Cesium.ScreenSpaceEventType.MOUSE_MOVE
);
removeHighlight();
});
</script>
其中的CesiumViewer组件是初始化地图及设置底图,详细内容可以看之前的文章,