CesiumJS如何自定义浮框

html

<div id="map-container"></div>
<div id="map-infowindow1">
  ...
</div>
<div id="map-infowindow2">
  ...
</div>

js

// 地图浮框
class Infowindow {
  _element: HTMLElement; // 浮框DOM元素
  _offsetX: number; // X轴偏移量
  _offsetY: number; // Y轴偏移量
  _entityId: string;
  _viewer: Cesium.Viewer;

  constructor (viewer: Cesium.Viewer, element: HTMLElement, offsetX = 0, offsetY=0) {
    this._viewer = viewer;
    this._element = element;
    this._offsetX = offsetX;
    this._offsetY = offsetY;
  }
  
  set entityId (entityId: string) {
    this._entityId = entityId;
  }

  get viewer (): Cesium.Viewer {
    return this._viewer;
  }

  get entity (): Cesium.Entity {
    return this._viewer.entities.getById(this._entityId);
  }
}

// 初始化地图
const viewer = new Cesium.Viewer('map-container');

// 创建浮框实例
const infowindows = [];
infowindows.push(new Infowindow(viewer, document.getElementById('map-infowindow1')));
infowindows.push(new Infowindow(viewer, document.getElementById('map-infowindow2')));

// 根据点位每帧更新浮框位置
function updateInfowindowPosition () {
  infowindows.forEach((infowindow) => {
    const { element, offsetX, offsetY } = infowindow;
    if (infowindow.entity) {
      // 更新位置
      const cartesian3 = infowindow.entity.position.getValue(Cesium.JulianDate.now());
      const xy = Cesium.SceneTransforms.wgs84ToWindowCoordinates(infowindow.viewer.scene, cartesian3);
      const { width, height } = getDomSize(element);
      element.style.top = `${Math.round(xy.y - height - (offsetY || 0))}px`;
      element.style.left = `${Math.round(xy.x - width / 2 - (offsetX || 0))}px`;
      element.style.visibility = 'visible';
    } else {
      element.style.visibility = 'hidden';
    }
  });
  requestAnimationFrame(updateInfowindowPosition);
}

// 启动实时更新
updateInfowindowPosition();

以上为实现自定义浮框的简单示意,需根据实际需求修改方法updateInfowindowPosition。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容