import * as Cesium from 'cesium';
export class CompassArrow {
constructor(viewer) {
this.arrow = this.createArrow();
// 双击归零
this.arrow.addEventListener('dblclick', () => {
viewer.scene.camera.flyTo({
destination: viewer.scene.camera.position,
orientation: {
heading: 0
},
// 动画时间 1s
duration: 1,
easingFunction: Cesium.EasingFunction.LINEAR_NONE
})
});
let oldHeading = viewer['camera']['heading'];
this.removeListener = viewer.scene.postRender.addEventListener(() => {
const heading = viewer['camera']['heading'];
if (heading === oldHeading) {
return;
}
this.arrow['style'].transform = `rotate(-${heading}rad)`;
oldHeading = heading;
})
}
destory() {
this.arrow.remove();
this.arrow = null;
this.removeListener();
this.removeListener = null;
}
createArrow() {
// 创建按钮元素
const button = document.createElement('button');
button.classList.add('ol-control-button');
// 创建内部的 span 元素
const span = document.createElement('span');
span.classList.add('ol-compass');
span.style.transform = 'rotate(0rad)';
span.textContent = '⇧';
// 将 span 元素添加到按钮中
button.appendChild(span);
// 设置按钮的样式和属性
button.style.background = 'rgba(0, 60, 136,.5)';
button.style.color = '#fff';
button.style.margin = '1px';
button.style.padding = '0';
button.style.fontWeight = '700';
button.style.textDecoration = 'none';
button.style.fontSize = '30px';
button.style.textAlign = 'center';
button.style.height = '50px';
button.style.width = '50px';
button.style.lineHeight = '50px';
button.style.border = 'none';
button.style.borderRadius = '2px';
button.style.userSelect = 'none';
button.style.position = 'fixed';
button.style.right = '50%';
button.style.top = '20px';
button.style.cursor = 'pointer';
// 将按钮添加到页面中
document.body.appendChild(button);
return button;
}
}
使用:
window.arrow = new CompassArrow(viewer);