在地图上添加几何图形
在 Cesium
的实体集合中添加一个新的实体,需要调用viewer.entities.add
方法
添加一个矩形
js
var west = -90.0; // 矩形西边的经度为-90.0度
var south = 38.0;
var east = -87.0;
var north = 40.0;
// 调用 viewer.entities.add 方法,向 Cesium 的实体集合中添加一个新的实体
viewer.entities.add({
rectangle: { // 声明添加的是一个矩形
coordinates: Cesium.Rectangle.fromDegrees(west, south, east, north),
},
});
添加一条线
js
const orangeOutlined = viewer.entities.add({
name:
"Orange line with black outline at height and following the surface",
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights([
-180,
0,
2500000,
10,
0,
2500000,
]),
width: 5,
material: new Cesium.PolylineOutlineMaterialProperty({
color: Cesium.Color.ORANGE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
}),
},
});
绘制点
js
async function drawPoints() {
if (!viewer.value) {
console.error('Viewer is not initialized');
return;
}
const drawnPoints = await DrawPoints();
console.log(drawnPoints);
}
// 通过鼠标事件绘制点
async function DrawPoints() {
return new Promise((resolve, reject) => {
let viewerInstance = viewer.value;
let drawnPoints = [];
// 创建一个事件处理器
let handler = new Cesium.ScreenSpaceEventHandler(viewerInstance.canvas);
// 注册鼠标左键点击事件,用于绘制点
handler.setInputAction(event => {
// 获取鼠标点击的笛卡尔坐标(鼠标点击位置->笛卡尔坐标)
var cartesian = viewerInstance.camera.pickEllipsoid(event.position, viewerInstance.scene.globe.ellipsoid);
// 确保坐标有效
if (cartesian) {
// 添加点实体
viewerInstance.entities.add({
position: cartesian,
point: {
color: Cesium.Color.RED,
pixelSize: 10
}
});
// 获取地理坐标(经纬度)
let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
let longitude = Cesium.Math.toDegrees(cartographic.longitude);
let latitude = Cesium.Math.toDegrees(cartographic.latitude);
let height = cartographic.height; // Height is already in meters, no need to convert
// 将绘制的点添加到数组中
drawnPoints.push({ lng: longitude, lat: latitude, height: height });
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 注册鼠标右键点击事件,用于结束绘制,并打印绘制的点
handler.setInputAction(() => {
// 销毁事件处理器
handler.destroy();
// 返回所有绘制的点
resolve(drawnPoints);
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
});
}