效果图:
![](https://i-blog.csdnimg.cn/blog_migrate/59e022ed3c843f10d6ae3f22859700fe.gif)
实现代码:
<template>
<div id="cesiumContainer"></div>
</template>
<script setup>
import * as Cesium from "cesium";
import { onMounted } from "vue";
onMounted(() => {
const viewer = new Cesium.Viewer("cesiumContainer", {
infoBox: false, // 禁用沙箱,解决控制台报错
});
//cesium默认右键为放大缩小,此处给zoomEventTypes设置新值
viewer.scene.screenSpaceCameraController.zoomEventTypes = [
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
];
//earthsdk默认右键为改变视角,此处禁止。
viewer.scene.screenSpaceCameraController.lookEventTypes = [];
//右键按下标识
var flag = false;
//起点终点x,y
var startX = null;
var startY = null;
var endX = null;
var endY = null;
//创建框选元素
var selDiv = document.createElement("div");
var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
//右键按下事件,设置起点,div设置样式和位置,添加到页面
handler.setInputAction(function (event) {
flag = true;
startX = event.position.x;
startY = event.position.y;
selDiv.style.cssText =
"position:absolute;width:0;height:0;font-size:0;margin:0;padding:0;border:1px dashed #0099FF;background-color:#C3D5ED;z-index:1000;filter:alpha(opacity:60);opacity:0.6;";
selDiv.id = "selectDiv";
selDiv.style.left = startX + "px";
selDiv.style.top = startY + "px";
document.body.appendChild(selDiv);
}, Cesium.ScreenSpaceEventType.RIGHT_DOWN);
//鼠标抬起事件,获取div坐上和右下的x,y 转为经纬度坐标
handler.setInputAction(function (event) {
flag = false;
var l = parseInt(selDiv.style.left);
var t = parseInt(selDiv.style.top);
var w = parseInt(selDiv.style.width);
var h = parseInt(selDiv.style.height);
var earthPosition = viewer.camera.pickEllipsoid(
{ x: l, y: t },
viewer.scene.globe.ellipsoid
);
var cartographic = Cesium.Cartographic.fromCartesian(
earthPosition,
viewer.scene.globe.ellipsoid,
new Cesium.Cartographic()
);
console.log(
"左上坐标为:" +
[
Cesium.Math.toDegrees(cartographic.longitude),
Cesium.Math.toDegrees(cartographic.latitude),
]
);
earthPosition = viewer.camera.pickEllipsoid(
{ x: l + w, y: t + h },
viewer.scene.globe.ellipsoid
);
cartographic = Cesium.Cartographic.fromCartesian(
earthPosition,
viewer.scene.globe.ellipsoid,
new Cesium.Cartographic()
);
console.log(
"右下坐标为:" +
[
Cesium.Math.toDegrees(cartographic.longitude),
Cesium.Math.toDegrees(cartographic.latitude),
]
);
//根据业务确定是否删除框选div
document
.getElementById("selectDiv")
.parentNode.removeChild(document.getElementById("selectDiv"));
}, Cesium.ScreenSpaceEventType.RIGHT_UP);
//鼠标移动事件,处理位置css
handler.setInputAction(function (event) {
if (flag) {
endX = event.endPosition.x;
endY = event.endPosition.y;
selDiv.style.left = Math.min(endX, startX) + "px";
selDiv.style.top = Math.min(endY, startY) + "px";
selDiv.style.width = Math.abs(endX - startX) + "px";
selDiv.style.height = Math.abs(endY - startY) + "px";
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
});
</script>
<style scoped>
#cesiumContainer {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>