如何在特定事件触发时停止Cesium地图中已启用的地球自转效果
Cesium停止地球自转实现方案
核心原理:Cesium的Scene.postRender事件移除监听时,必须传入和注册时完全一致的函数实例,你当前的代码未保存回调函数的引用,因此无法直接移除,需要调整自转实现逻辑:
1. 修改自转注册逻辑,保存回调引用
同时修复原代码中回调内部this指向错误的潜在问题:
// 在实例上新增属性存储自转回调 this._spinCallback = null; spinGlobe(dynamicRate) { // 先移除已存在的自转监听,避免重复注册导致转速异常 this.stopGlobeSpin(); let previousTime = Date.now(); // 把回调函数存到实例属性上,后续移除监听需要用到 this._spinCallback = (scene, time) => { const spinRate = dynamicRate; const currentTime = Date.now(); const delta = (currentTime - previousTime) / 1000; previousTime = currentTime; // 箭头函数自动继承外部this,可直接访问viewer实例 this.viewer.scene.camera.rotate(Cesium.Cartesian3.UNIT_Z, -spinRate * delta); }; this.viewer.scene.postRender.addEventListener(this._spinCallback); }
2. 实现停止自转的方法
stopGlobeSpin() { // 仅当存在自转回调时执行移除逻辑 if (this._spinCallback) { this.viewer.scene.postRender.removeEventListener(this._spinCallback); this._spinCallback = null; } }
3. 触发停止逻辑
在你需要的特定事件触发位置,直接调用stopGlobeSpin()方法即可停止地球自转。
注意事项
- 重复调用
spinGlobe前如果不清理旧回调,会导致多个自转逻辑同时执行,转速异常,因此上述实现中在spinGlobe开头先执行停止逻辑 - 页面/组件销毁时建议主动调用
stopGlobeSpin清理事件监听,避免内存泄漏
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

