cesium 画Polyline
时间: 2025-07-04 09:13:33 浏览: 7
在 Cesium 中绘制折线(Polyline)可以通过 `PolylineCollection` 或者使用封装好的绘图工具实现。以下是两种方式的示例代码。
### 使用 PolylineCollection 绘制静态折线
下面是一个基本的示例,展示如何使用 `PolylineCollection` 来绘制一条静态折线:
```javascript
// 添加一个 PolylineCollection 到场景中
const polylines = viewer.scene.primitives.add(new Cesium.PolylineCollection());
// 定义折线的两个点位(经纬度转换为笛卡尔坐标)
const positions = Cesium.Cartesian3.fromDegreesArray([
-120.0, 40.0,
-110.0, 30.0
]);
// 添加折线到集合中
polylines.add({
positions: positions,
material: Cesium.Material.fromType("Color", {
color: new Cesium.Color(1.0, 0.0, 0.0, 1.0) // 设置颜色为红色
}),
width: 5 // 折线宽度
});
```
### 动态绘制折线并获取坐标信息
如果需要动态绘制折线,并在绘制完成后获取其坐标信息,可以参考以下封装方法:
```javascript
class DrawHelper {
constructor(viewer) {
this.viewer = viewer;
this.polylines = this.viewer.scene.primitives.add(new Cesium.PolylineCollection());
}
drawPolyline(callback) {
const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
let positions = [];
handler.setInputAction((click) => {
const cartesian = this.viewer.camera.pickEllipsoid(click.position, this.viewer.scene.globe.ellipsoid);
if (cartesian) {
positions.push(cartesian);
// 实时更新折线
this.polylines.removeAll();
this.polylines.add({
positions: positions,
material: Cesium.Material.fromType("Color", {
color: new Cesium.Color(0.0, 1.0, 0.0, 1.0)
}),
width: 3
});
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
handler.setInputAction((click) => {
const cartesian = this.viewer.camera.pickEllipsoid(click.position, this.viewer.scene.globe.ellipsoid);
if (cartesian && positions.length > 0) {
positions.push(cartesian);
this.polylines.removeAll();
const polyline = this.polylines.add({
positions: positions,
material: Cesium.Material.fromType("Color", {
color: new Cesium.Color(0.0, 1.0, 0.0, 1.0)
}),
width: 3
});
// 结束绘制并回调返回折线数据
callback({
positions: positions
});
handler.destroy(); // 清除事件监听
}
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}
}
// 使用方式
const drawHelper = new DrawHelper(viewer);
drawHelper.drawPolyline((result) => {
console.log('绘制完成的折线坐标:', result.positions);
});
```
以上代码展示了如何通过点击鼠标左键添加点来动态绘制折线,并通过右键结束绘制过程[^2]。
阅读全文
相关推荐


















