项目地址
https://github.com/zhengjie9510/webgis-demo
实现效果
实现方法
1、构建 DrawPolygon 类
class DrawPolygons {
constructor(options) {
this.layer = new Cesium.CustomDataSource('MyLines')
this.activeShapePoints = []
this.activeShape = undefined
this.handler = undefined
}
/**
* 添加鼠标点击事件
* @param {Cesium.Viewer} viewer 目标地图
*/
bindAction(viewer) {
if (!this.handler) {
this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
}
// 鼠标左键单击画点
this.handler.setInputAction((click) => {
const earthPosition = this.getPosition(viewer, click.position)
if (Cesium.defined(earthPosition)) {
if (this.activeShapePoints.length === 0) {
this.activeShapePoints.push(earthPosition)
const dynamicPositions = new Cesium.CallbackProperty(() => {
return new Cesium.PolygonHierarchy(this.activeShapePoints);
}, false);
this.activeShape = this.drawPolygon(dynamicPositions)
}
this.activeShapePoints.push(earthPosition)
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK)
// 鼠标移动
this.handler.setInputAction((move) => {
if (this.activeShapePoints.length >= 2) {
const earthPosition = this.getPosition(viewer, move.endPosition)
if (Cesium.defined(earthPosition)) {
this.activeShapePoints.pop()
this.activeShapePoints.push(earthPosition)
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
// 单击鼠标右键结束画面
this.handler.setInputAction((click) => {
this.activeShapePoints.pop();
this.layer.entities.remove(this.activeShape)
this.drawPolygon(this.activeShapePoints)
this.activeShapePoints = []
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}
/**
* 添加鼠标点击事件的位置
* @param {Cesium.Viewer} viewer 目标地图
* @param {Cesium.Cartesian2} position 鼠标位置
* @return {Cesium.Cartesian3} 鼠标点击位置的坐标
*/
getPosition(viewer, position) {
let earthPosition = undefined
// 球面
if (viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider) {
earthPosition = viewer.scene.camera.pickEllipsoid(position);
}
// 地形
else {
const ray = viewer.camera.getPickRay(position);
earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
}
return earthPosition
}
/**
* 画面
* @param {array<Cesium.Cartesian3>} positionData 面边界坐标
*/
drawPolygon(positionData) {
return this.layer.entities.add({
polygon: {
hierarchy: positionData,
material: new Cesium.ColorMaterialProperty(
Cesium.Color.WHITE.withAlpha(0.7)
),
},
});
}
/**
* 添加图层
* @param {Cesium.Viewer} viewer 目标地图
*/
addToMap(viewer) {
viewer.dataSources.add(this.layer);
}
}
2、使用 DrawPolygon 类
const drawPolygons = new DrawPolygons()
drawPolygons.bindAction(viewer)
drawPolygons.addToMap(viewer)