Cesium1.132的polyline加label
时间: 2025-09-06 21:11:17 AIGC 浏览: 19
Cesium 1.132 是一个较新的版本,其 API 与之前的版本保持高度兼容性,`Entity` 和 `Label` 的使用方式基本没有变化。因此,为 `polyline` 添加 `label` 的方法与之前版本一致,但我们可以特别强调 Cesium 1.132 中的兼容性和新特性支持。
---
## ✅ 在 Cesium 1.132 中为 `polyline` 添加 label 的推荐方法
### ✅ 方法一:使用 `Entity` + `label`(推荐)
这是最常见、最易用的方式。
### 示例代码(适用于 Cesium 1.132):
```javascript
const viewer = new Cesium.Viewer('cesiumContainer');
// 定义 polyline 的两个点
const start = Cesium.Cartesian3.fromDegrees(-115.0, 32.0);
const end = Cesium.Cartesian3.fromDegrees(-85.0, 32.0);
// 创建 Entity,包含 polyline 和 label
const entity = viewer.entities.add({
polyline: {
positions: [start, end],
width: 5,
material: Cesium.Color.RED
},
label: {
text: 'My Polyline',
font: '16pt sans-serif',
color: Cesium.Color.WHITE,
backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20),
// 设置 label 位于 polyline 的中点
position: new Cesium.CallbackProperty(() => {
return Cesium.Rectangle.center(Cesium.Rectangle.fromDegrees(-115, 32, -85, 32));
}, false)
}
});
viewer.camera.flyTo({ entities: [entity] });
```
### 解释:
- **polyline**:创建了一条从 `-115,32` 到 `-85,32` 的红色折线;
- **label**:
- `text`:标签文本;
- `font`:字体大小和类型;
- `color`:字体颜色;
- `backgroundColor`:背景颜色,使用 `withAlpha` 设置透明度;
- `position`:使用 `CallbackProperty` 动态设置为 polyline 的中点;
- `pixelOffset`:向上偏移一点,防止遮挡折线。
---
### ✅ 方法二:使用 `LabelGraphics`(更灵活的 Entity 方式)
如果你希望 label 的位置可以跟随 polyline 的几何形状变化(比如动态变化的 polyline),你可以使用 `PositionProperty` 来动态计算中点。
```javascript
const viewer = new Cesium.Viewer('cesiumContainer');
const positions = [
Cesium.Cartesian3.fromDegrees(-115.0, 32.0),
Cesium.Cartesian3.fromDegrees(-85.0, 32.0)
];
const entity = viewer.entities.add({
polyline: {
positions: positions,
width: 5,
material: Cesium.Color.BLUE
},
label: {
text: 'Dynamic Label',
font: '16pt sans-serif',
color: Cesium.Color.YELLOW,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
position: new Cesium.PositionProperty() {
isConstant: false,
_definitionChanged: new Cesium.Event(),
getValue(time, result) {
if (!result) result = new Cesium.Cartesian3();
return Cesium.Cartesian3.midpoint(positions[0], positions[1], result);
}
}
}
});
viewer.camera.flyTo({ entities: [entity] });
```
---
## ✅ Cesium 1.132 的更新亮点(与 label 有关)
- **Label 支持更多样式**:如 `outlineColor`、`outlineWidth`、`showBackground` 等;
- **性能优化**:label 渲染效率提升;
- **支持动态 PositionProperty**:可以更灵活地绑定 label 到任意位置;
- **支持高 DPI 屏幕**:label 在高分辨率屏幕上显示更清晰。
---
## ✅ 总结
| 方法 | 是否推荐 | 说明 |
|------|----------|------|
| Entity + label | ✅ 推荐 | 简洁易用,适合大多数场景 |
| LabelGraphics + PositionProperty | ✅ 推荐 | 更灵活,适合动态 polyline |
| Primitive + LabelPrimitive | ⚠️ 一般 | 更底层,适合图形性能优化 |
| HTML Overlay | ❌ 不推荐 | 不属于 Cesium 渲染体系,维护困难 |
---
##
阅读全文
相关推荐



















