cesium动态绘制矩形
时间: 2023-07-05 09:22:07 浏览: 316
cesium绘制工具
要实现cesium动态绘制矩形,可以使用Cesium的Primitive API和MouseEvents。具体步骤如下:
1. 创建矩形entity并添加到场景中。
```
var entity = viewer.entities.add({
rectangle: {
coordinates: Cesium.Rectangle.fromDegrees(-100.0, 20.0, -90.0, 30.0),
material: Cesium.Color.RED.withAlpha(0.5),
outline: true,
outlineColor: Cesium.Color.BLACK
}
});
```
2. 获取鼠标左键按下和移动事件,并更新矩形的坐标。
```
var startPosition;
var mouseHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
mouseHandler.setInputAction(function(movement) {
startPosition = movement.position;
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
mouseHandler.setInputAction(function(movement) {
if (Cesium.defined(startPosition)) {
var endPosition = movement.position;
var startCartesian = viewer.scene.camera.pickEllipsoid(startPosition, viewer.scene.globe.ellipsoid);
var endCartesian = viewer.scene.camera.pickEllipsoid(endPosition, viewer.scene.globe.ellipsoid);
if (Cesium.defined(startCartesian) && Cesium.defined(endCartesian)) {
var startCartographic = Cesium.Cartographic.fromCartesian(startCartesian);
var endCartographic = Cesium.Cartographic.fromCartesian(endCartesian);
var west = Math.min(startCartographic.longitude, endCartographic.longitude);
var east = Math.max(startCartographic.longitude, endCartographic.longitude);
var south = Math.min(startCartographic.latitude, endCartographic.latitude);
var north = Math.max(startCartographic.latitude, endCartographic.latitude);
entity.rectangle.coordinates = Cesium.Rectangle.fromDegrees(west, south, east, north);
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
```
3. 获取鼠标左键松开事件,结束矩形绘制。
```
mouseHandler.setInputAction(function(movement) {
startPosition = undefined;
}, Cesium.ScreenSpaceEventType.LEFT_UP);
```
这样,当用户按下鼠标左键并移动时,就可以动态绘制矩形。
阅读全文