Cesium有很多很强大的功能,可以在地球上实现很多炫酷的3D效果。今天给大家分享一个可自定义的火灾疏散人群的功能。

1.话不多说,先展示

【Cesium开发实战】火灾疏散功能的实现,可设置火源点、疏散路径、疏散人数_VUE3

视频:Cesium火灾疏散模拟

2.设计思路

根据项目需求要求,可设置火源点、绘制逃生路线、可设置逃生人数。所以点击火灾点绘制后,在地图点击可看到火光的粒子效果。点击疏散路径绘制后,在地图上点击可以绘制路径,双击结束绘制,一个火灾点会有多条疏散路径,可再次同样步骤操作绘制路径,点击保存可编辑名称和设定每条路径疏散的人数数量形成列表数据,点击开始疏散,通过czml数据格式实现疏散动画效果。

3.具体代码

<template>
	<div class="page">
		<el-button @click="drawStartPosition">火灾点绘制</el-button>
		<el-button @click="drawLineRoad">疏散路径绘制</el-button>
		<el-button @click="save">保存</el-button>
		<div style="margin-top: 10px">
			<el-table :data="dataList" border @row-click="rowClick">
				<el-table-column prop="name" label="名称" align="center" />

				<el-table-column label="操作" align="center">
					<template #default="scope">
						<el-button type="primary" style="width: 50px;"
							@click="startShus(scope.row, scope.$index)">开始疏散</el-button>
						<el-button link type="primary" size="small" @click="delEntity(scope.row, scope.$index)"><el-icon
								:size="16"><ele-Delete /> </el-icon></el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<el-dialog v-model="dialogFormVisible" title="配置" width="500" :close-on-press-escape="false"
			:close-on-click-modal="false" :show-close="false">
			<el-form ref="formRef" :model="form" label-width="auto" class="demo-dynamic" :rules="rules">
				<el-form-item label="疏散名称" prop="title">
					<el-input v-model="form.title" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="疏散路线人数">
				<el-input-number :min="0" v-model="form.people" placeholder="请输入" />
			</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm(formRef)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { Cesium } from '/@/utils/cesium';
const props = defineProps(['viewer']);


//是否显示弹框
const dialogFormVisible = ref(false);

const formRef = ref();

var entities: any = {};

const rules = {
	title: { required: true, message: '请输入疏散名称', trigger: 'blur' },
};

// 视图名称
const form = reactive({
	title: '',
	people: 20,
});

// 视点列表数据
const dataList: any = reactive([]);

/**
 * 点击表格一行
 */
const rowClick = (row: any, column: any, event: Event) => {
	if (column && column.property) {
		let index = dataList.findIndex((v: any) => v.id === row.id);
		if (index !== -1) {
			props.viewer.flyTo(listEntities[index].entities[0].pointEntities[0], {
				offset: {
					heading: Cesium.Math.toRadians(10.0114629015290062),
					pitch: Cesium.Math.toRadians(-23.53661660731824),
					roll: Cesium.Math.toRadians(0.00324596311071617),
				},
			});
		}
	}
};

//是否开始绘制火灾点
const drawing = ref(false);
var firePointEntity: any = [];
var firePrimitiveEntity: any = [];
//绘制火灾起点
const drawStartPosition = () => {
	drawing.value = true;
	var handler2 = new Cesium.ScreenSpaceEventHandler(props.viewer.scene.canvas);
	//鼠标左键
	handler2.setInputAction(function (event: any) {
		if (drawing.value) {
			var earthPosition = props.viewer.scene.pickPosition(event.position);
			if (Cesium.defined(earthPosition)) {
				//将笛卡尔坐标转化为经纬度坐标
				var cartographic = Cesium.Cartographic.fromCartesian(earthPosition);
				var longitude = Cesium.Math.toDegrees(cartographic.longitude);
				var latitude = Cesium.Math.toDegrees(cartographic.latitude);
				var height = cartographic.height;
				var entity44 = props.viewer.entities.add({
					position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
				});
				//存储火灾点点位对象到集合
				firePointEntity.push(entity44);
				var firePrimitive = new Cesium.ParticleSystem({
					image: '/src/assets/cesium/fire.png',
					startColor: Cesium.Color.RED.withAlpha(0.7),
					endColor: Cesium.Color.YELLOW.withAlpha(0.3),
					startScale: 0,
					endScale: 10,
					minimumParticleLife: 1,
					maximumParticleLife: 6,
					minimumSpeed: 1,
					maximumSpeed: 4,
					imageSize: new Cesium.Cartesian2(55, 55),
					// Particles per second.
					emissionRate: 4,
					lifetime: 160.0,
					emitter: new Cesium.CircleEmitter(5.0),
					modelMatrix: computeModelMatrix(entity44, Cesium.JulianDate.now()),
					emitterModelMatrix: computeEmitterModelMatrix()

				});
				props.viewer.scene.primitives.add(firePrimitive);
				//存储火灾点图像对象到集合
				firePrimitiveEntity.push(firePrimitive);

				//移除左键监听
				handler2.destroy();
				// 确保视角没有被锁定  
				props.viewer.trackedEntity = undefined;
			}
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

const computeModelMatrix = (entity: any, time: any) => {
	var position = entity.position.getValue(Cesium.JulianDate.now());
	let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
	return modelMatrix;
}
const computeEmitterModelMatrix = () => {
	let hpr = Cesium.HeadingPitchRoll.fromDegrees(0, 0, 0);
	let trs = new Cesium.TranslationRotationScale();
	trs.translation = Cesium.Cartesian3.fromElements(2.5, 4, 1);
	trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr);
	let result = Cesium.Matrix4.fromTranslationRotationScale(trs);
	return result
}

// 弧度转角度
const toDegrees = (radians: any) => {
	return (radians * 180) / Math.PI;
};

//是否开始绘制火灾点
const drawingLine = ref(false);
var listEntities: any = [];
//绘制的所有地面的点线实体集合
var entities: any = [];
//临时一条数据的point实体列表
var pointEntities: any = [];
//临时一条数据的线实体列表
var linesEntities: any = [];
var activeShapePoints: any = [];
var floatingPoint: any = undefined;
var activeShape: any = undefined;
//绘制线路
const drawLineRoad = () => {

	drawingLine.value = true;
	var handler = new Cesium.ScreenSpaceEventHandler(props.viewer.scene.canvas);
	//鼠标左键
	handler.setInputAction(function (event: any) {
		if (drawingLine.value) {
			var earthPosition = props.viewer.scene.pickPosition(event.position);
			if (Cesium.defined(earthPosition)) {
				if (activeShapePoints.length === 0) {
					floatingPoint = createPoint(earthPosition);
					activeShapePoints.push(earthPosition);
					var dynamicPositions = new Cesium.CallbackProperty(function () {
						return activeShapePoints;
					}, false);
					activeShape = drawShape(dynamicPositions); //绘制动态图
					//线实体集合
					linesEntities.push(activeShape);
				}
				activeShapePoints.push(earthPosition);
				//点实体集合
				pointEntities.push(createPoint(earthPosition));
			}
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	//鼠标移动
	handler.setInputAction(function (event: any) {
		if (Cesium.defined(floatingPoint)) {
			var newPosition = props.viewer.scene.pickPosition(event.endPosition);
			if (Cesium.defined(newPosition)) {
				floatingPoint.position.setValue(newPosition);
				activeShapePoints.pop();
				activeShapePoints.push(newPosition);
			}
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	handler.setInputAction(function () {
		if (drawingLine.value) {
			drawingLine.value = false;
			terminateShape();
		}
		//移除监听
		handler.destroy();
		// 确保视角没有被锁定  
		props.viewer.trackedEntity = undefined;
	}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
};

//绘制点
const createPoint = (worldPosition: any) => {
	var point = props.viewer.entities.add({
		position: worldPosition,
		point: {
			color: Cesium.Color.RED,
			pixelSize: 10,
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
		},
	});
	return point;
};

//绘制线
const drawShape = (positionData: any) => {
	var shape = props.viewer.entities.add({
		polyline: {
			with: 10,
			color: Cesium.Color.RED,
			positions: positionData,
			clampToGround: true,
		},
	});
	return shape;
};

//双击后处理数据
const terminateShape = () => {
	linesEntities.push(drawShape(activeShapePoints)); //绘制最终图

	//因双击会触发俩次单机事件,去除最后一个点重复绘制,并删除多余的点
	props.viewer.entities.remove(pointEntities[pointEntities.length - 1]);
	pointEntities.pop();

	props.viewer.entities.remove(floatingPoint); //去除动态点图形(当前鼠标点)
	props.viewer.entities.remove(activeShape); //去除动态图形
	floatingPoint = undefined;
	activeShape = undefined;
	activeShapePoints = [];


	//点实体和线实体的集合
	entities.push({
		pointEntities: pointEntities,
		linesEntities: linesEntities,
	});

	pointEntities = [];
	linesEntities = [];
};

//保存火灾点和疏散路径
var customMarks: any = [];
const save = () => {
	dialogFormVisible.value = true; //弹出对话框
}

/**
 * 点击确定绘制
 */
const submitForm = async (formEl: any) => {
	const valid = await formEl.validate();
	if (valid) {

		listEntities.push({
			firePointEntity: firePointEntity,
			firePrimitiveEntity: firePrimitiveEntity,
			entities: entities
		});
		dataList.push({
			id: new Date().getTime(),
			name: form.title,
			people:form.people
		});
		//设置为空对象以便创建新的列表数据
		firePointEntity = [];
		firePrimitiveEntity = [];
		entities = [];
		dialogFormVisible.value = false;
		form.title = '';
	}
};

/**
 * 删除列表数据
 */
const delEntity = (item: any, index: number) => {
	for (const item of listEntities[index].firePointEntity) {
		props.viewer.entities.remove(item);
	}
	for (const item of listEntities[index].firePrimitiveEntity) {
		props.viewer.scene.primitives.remove(item);
	}
	for (const iterator of listEntities[index].entities) {
		for (const item of iterator.pointEntities) {
			props.viewer.entities.remove(item);
		}
		for (const item of iterator.linesEntities) {
			props.viewer.entities.remove(item);
		}
	}

	dataList.splice(index, 1);
	listEntities.splice(index, 1);

	if (obj) {
		props.viewer.dataSources.remove(obj);
		obj = null;
	}

};

var obj: any;

//开始疏散
const startShus = (item: any, index: number) => {
	var czml: any = [];
	czml.push({
		"id": "document",
		"name": "CZML Path",
		"version": "1.0"
	});

	var entities = listEntities[index].entities;
	var peopleNum = item.people;
	if (entities.length) {
		for (const [index2, item2] of entities.entries()) {

			customMarks = [];
			for (const [index, item] of item2.pointEntities.entries()) {

				const latitude = toDegrees(Cesium.Cartographic.fromCartesian(item.position._value).latitude);
				const longitude = toDegrees(Cesium.Cartographic.fromCartesian(item.position._value).longitude);

				customMarks.push((1 * index));
				customMarks.push(longitude);
				customMarks.push(latitude);
				customMarks.push(2);
			}



			for (let i = 0; i < peopleNum; ++i) {
				var iso8601DateString = '2024-07-04T10:00:00Z';
				var julianDate = Cesium.JulianDate.fromIso8601(iso8601DateString);

				if (Cesium.defined(julianDate)) {
					var newJulianDate = Cesium.JulianDate.addSeconds(julianDate, i * 0.5, new Cesium.JulianDate());
					// 如果你需要将 JulianDate 转换为 Date 对象  
					var date = Cesium.JulianDate.toDate(newJulianDate);

					czml.push({
						"id": "path" + index2 + i,
						"name": "路径" + index2 + i,
						"availability": "2024-07-04T10:00:00.000Z/2024-07-04T10:01:00.000Z",
						"model": {
							id: 'man',
							gltf: '/src/assets/cesium/Cesium_Man.glb',
							scale: 10
						},
						"position": {
							"epoch": date.toISOString(),
							"cartographicDegrees": customMarks
						}
					});
				} else {
					console.error('无法从 ISO 8601 字符串解析日期');
				}
			}
		}
	}
	//清除上次数据
	props.viewer.dataSources.remove(obj);
	obj = null;
	//加载本次疏散czml
	props.viewer.dataSources.add(Cesium.CzmlDataSource.load(czml)).then(function (loadedDataSource) {
		obj = loadedDataSource;
		var entities = loadedDataSource.entities.values;
		for (var i = 0; i < entities.length; i++) {
			var s = entities[i];
			s.orientation = new Cesium.VelocityOrientationProperty(s.position);
		}
	})

}


onMounted(() => {
});

onUnmounted(() => {
	//清除绘制的内容
	props.viewer.entities.removeAll();

	//绘制了火灾点切换的时候需要先清除
	if (firePrimitiveEntity.length) {
		for (const item of firePrimitiveEntity) {
			props.viewer.scene.primitives.remove(item);
		}
	}
	//绘制了多个火灾点并保存到了列表上离开时清除
	for (const iterator of listEntities) {
		for (const item of iterator.firePrimitiveEntity) {
			props.viewer.scene.primitives.remove(item);
		}
	}

	if (obj) {
		props.viewer.dataSources.remove(obj);
		obj = null;
	}

});
</script>

<style scoped>
.page {
	position: absolute;
	right: 10px;
	top: 10px;
	color: #fff;
	background: #fff;
	padding: 10px;
	border-radius: 5px;
	width: 400px;
}
</style>