class CesiumPopupClass {
constructor(viewer, options) {
this.viewer = viewer
this.position = options.position;
this.height = options.height || 0;
this.options = this.extend({}, options);
var popupContainer = document.createElement("div");
popupContainer.classList.add('popup');
var popupInner = options.content;
popupContainer.innerHTML = popupInner;
popupContainer.style.display = 'none';
viewer.cesiumWidget.container.appendChild(popupContainer);
popupContainer.style.cssText = "display: none;position: absolute;left: 0;top: 0;min-width: 200px;z-index:9999;";
this.popupContainer = popupContainer;
// 初始化
this.init();
}
init() {
if (!this.viewer) {
return
}
if (this.position) {
this.popupContainer.style.display = 'block'
this.renderListener = this.viewer.scene.postRender.addEventListener(this.render, this)
}
}
render() {
var ellipsoid = this.viewer.scene.globe.ellipsoid;
var geometry = Cesium.Cartesian3.fromDegrees(
this.position[0],
this.position[1],
this.height,
ellipsoid
);
if (!geometry) return
var position = Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, geometry)
if (!position) {
return
}
if (this.popupContainer) {
this.popupContainer.style.left = position.x - this.popupContainer.offsetWidth / 2 + 'px'
this.popupContainer.style.top = position.y - this.popupContainer.offsetHeight - 10 + 'px'
}
}
updatePosition(newPosition) {
// 更新内部存储的位置
this.position = newPosition;
// 如果弹窗容器存在并且已经显示
if (this.popupContainer && this.popupContainer.style.display === 'block') {
// 移除现有的渲染监听器(如果存在),以避免重复添加
if (this.renderListener) {
this.viewer.scene.postRender.removeEventListener(this.render, this);
this.renderListener = null;
}
// 重新初始化并渲染弹窗
this.init(); // 这将重新添加渲染监听器
// 如果需要立即渲染(而不是等待下一个渲染周期),可以调用 render 方法
// 但通常,让 postRender 监听器处理渲染就足够了
// this.render();
}
}
remove() {
if (this.popupContainer) {
this.popupContainer.parentNode.removeChild(this.popupContainer)
this.popupContainer = null
}
if (this.renderListener) {
this.renderListener()
this.renderListener = null
}
if (this.viewer) {
this.viewer = null
}
}
extend(obj, obj2) {
for (var k in obj2) {
obj[k] = obj2[k];
}
return obj;
}
}
function addPop(viewer, position, popId) {
let p1 = new CesiumPopupClass(viewer, {
position: position,
content: `<div class ="testCss">
<div class="popup-title">标题</div>
<div class="popup-body">
<div>${position.toString()}</div>
<button id="${popId}">
删除
</button>
</div>
</div>`
})
let i = 0
setInterval(() => {
i += 0.00001
p1.updatePosition([position[0] + i, position[1]])
}, 10);
document.querySelector(`#${popId}`).addEventListener("click", () => {
p1.remove()
})
}
let position1 = [112.57482863, 26.81853529]
let position2 = [112.58524924, 26.81874033]
addPop(viewer, position1, "popId01")
addPop(viewer, position2, "popId02")
for (let j = 1; j < 100; j++) {
addPop(viewer, [position2[0] + (j / 10000), position2[1]], "popId02" + j)
}
cesium 自定义气泡 类
于 2023-11-21 11:06:15 首次发布