有一个业务需要用到cesium图层请求完成的回调,翻了好久的文档终于给我找到🌶️。
是Cesium.ImageryProvider
类的一个属性readyPromise
效果如下:
Cesium图层请求完成的回调
完整代码如下:
html
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Include the CesiumJS JavaScript and CSS files -->
<script src="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js"></script>
<link href="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
<style>
.button {
width: 80px;
height: 30px;
background-color: rgba(92, 38, 116, 0.818);
cursor: pointer;
padding: 10px;
color: #fff;
text-align: center;
line-height: 50px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="cesiumContainer">
<span id="addLayer" class="button">添加图层</span>
<span id="removeLayer" class="button">移除图层</span>
</div>
<script type="module">
Cesium.Ion.defaultAccessToken = ';
const viewer = new Cesium.Viewer('cesiumContainer', {
});
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(105, 35, 3456789),
orientation: {
heading: Cesium.Math.toRadians(360), //方向
pitch: Cesium.Math.toRadians(-90), //俯仰角
roll: Cesium.Math.toRadians(0),
},
});
let layer = null;
// 添加图层(async/await语法糖)
async function addLayer() {
let url = './assets/lyy.jpg';
let rectangleArr = [100.0, 30.0, 110.0, 40.0]
const singleTileImageryProvider = new Cesium.SingleTileImageryProvider({
url: url,
rectangle: new Cesium.Rectangle(
...rectangleArr.map(item => Cesium.Math.toRadians(item))
),
});
console.log("开始请求图层");
try {
// ⭐关键代码⭐
const res = await singleTileImageryProvider.readyPromise;
if (res) {
console.log("图层请求成功");
} else {
console.log("图层请求失败");
}
} catch (error) {
console.error("图层请求时发生错误:", error);
}
// 将imageryProvider添加到地图的图层列表中,使得图层可以在地图上显示
return viewer.imageryLayers.addImageryProvider(
singleTileImageryProvider
);
}
/*
// 添加图层(Promise)
function addLayer() {
return new Promise((resolve, reject) => {
let url = './assets/lyy.jpg';
let rectangleArr = [100.0, 30.0, 110.0, 40.0];
const singleTileImageryProvider = new Cesium.SingleTileImageryProvider({
url: url,
rectangle: new Cesium.Rectangle(
...rectangleArr.map(item => Cesium.Math.toRadians(item))
),
});
console.log("开始请求图层");
singleTileImageryProvider.readyPromise.then(res => {
if (res) {
console.log("图层请求成功");
resolve(viewer.imageryLayers.addImageryProvider(singleTileImageryProvider));
} else {
console.log("图层请求失败");
reject(new Error("图层请求失败"));
}
}).catch(error => {
console.error("图层请求时发生错误:", error);
reject(error);
});
});
}
*/
// 移除图层
function removeLayer() {
viewer.imageryLayers.remove(layer)
}
// 给按钮添加点击事件
document.getElementById("addLayer").onclick = async () => {
layer = await addLayer()
};
document.getElementById("removeLayer").onclick = () => {
removeLayer()
};
</script>
</div>
</body>
</html>