/**
|
* 标签管理器
|
* 职责:统一创建/移除地图上的文本标签,并提供距离格式化工具方法
|
*/
|
export class LabelManager {
|
/**
|
* 构造函数
|
* @param {Cesium.Viewer} viewer Cesium Viewer 实例
|
*/
|
constructor(viewer) { this.viewer = viewer }
|
|
/**
|
* 距离格式化(米/公里自动切换)
|
* @param {number} m 距离(米)
|
* @returns {string} 形如 "12.34 m" 或 "1.23 km"
|
*/
|
formatDistance (m) { return m < 1000 ? `${m.toFixed(2)} m` : `${(m / 1000).toFixed(2)} km` }
|
|
/**
|
* 创建标签实体
|
* @param {Cesium.Cartesian3} position 标签位置
|
* @param {string|Cesium.CallbackProperty} text 标签文本
|
* @param {boolean} [isAngle=false] 是否为角度标签(样式不同)
|
* @param {string} id 标签实体ID(用于后续获取/移除)
|
* @returns {Cesium.Entity} 新建的实体
|
*/
|
createLabel (position, text, isAngle = false, id) {
|
return this.viewer.entities.add({
|
id,
|
position: new Cesium.CallbackProperty(() => position, false),
|
label: {
|
text,
|
font: isAngle ? '18px sans-serif' : '14px sans-serif',
|
fillColor: isAngle ? Cesium.Color.fromCssColorString('#b8e065') : Cesium.Color.WHITE,
|
verticalOrigin: isAngle ? Cesium.VerticalOrigin.TOP : Cesium.VerticalOrigin.BOTTOM,
|
pixelOffset: new Cesium.Cartesian2(0, isAngle ? 20 : -10),
|
backgroundColor: isAngle ? Cesium.Color.WHITE.withAlpha(0) : Cesium.Color.fromCssColorString('#171719'),
|
showBackground: !isAngle
|
}
|
})
|
}
|
|
/**
|
* 按ID移除标签实体(安全移除)
|
* @param {string} id 已创建的实体ID
|
*/
|
removeLabelById (id) {
|
const ent = this.viewer.entities.getById(id)
|
if (ent) this.viewer.entities.remove(ent)
|
}
|
}
|