方法一
如下图所示,蓝色点为已知经纬度的给定两个点,现在需求是绘制出黑色边框矩形。实现思路是添加box实体,那么需要计算box的位置、方向和其中一条边长(另一边长已经指定大小)。
box的位置position也就是红色点,红色点坐标只需计算蓝色两点之间的中点坐标,边长l需要计算蓝色两点之间距离,方向orientation相对复杂,先调用getAngle(蓝1,蓝2)函数计算角度,再调用setModelDirection(position, angle)计算方向。所用的计算函数参考另一篇文章cesium一些计算函数
position = this.getPoint(
//取两点间中点作为面片中心position
coordinates[q][n][0],
coordinates[q][n][1],
coordinates[q][n + 1][0],
coordinates[q][n + 1][1]
);
angle = this.getAngle(
coordinates[q][n][0],
coordinates[q][n][1],
coordinates[q][n + 1][0],
coordinates[q][n + 1][1]
);
orientation = this.setModelDirection(position, angle);
let start = Cesium.Cartographic.fromDegrees(
//度转弧度
coordinates[q][n][0],
coordinates[q][n][1]
);
let end = Cesium.Cartographic.fromDegrees(
coordinates[q][n + 1][0],
coordinates[q][n + 1][1]
);
l = this.getDistance(start, end); //取两点间距离作为面片长
viewer.entities.add({
id: num++, // 为每一个矩形实体添加id
position: position, // 计算box位置
orientation: orientation, // 计算box方向
box: {
dimensions: new Cesium.Cartesian3(l, 3.75, 0), // l为计算出的矩形的一条边长
material: this.getColor(num / 300), // 为每一个矩形实体添加颜色
fill: true,
show: true,
},
});
方法二
方法一中存在缺陷,当cesium加入地形后,由于box高度在0以下,设置贴地后消失不可见。为满足需求,还是需要绘制polygon,求矩形四个角坐标。
调用getAngle(蓝1,蓝2)函数计算蓝色两点连线角度,将得到的angle±90可以算出上方下方红点角度,最后调用getPointByDirectionAndLen()计算红点坐标。所用的计算函数参考另一篇文章cesium一些计算函数
angle = this.getAngle(
coordinates[q][n][0],
coordinates[q][n][1],
coordinates[q][n + 1][0],
coordinates[q][n + 1][1]
);
let p1 = this.getPointByDirectionAndLen(
Cesium.Cartesian3.fromDegrees(coordinates[q][n][0], coordinates[q][n][1]),
angle - 90,
3.75 / 2
);
let p2 = this.getPointByDirectionAndLen(
Cesium.Cartesian3.fromDegrees(coordinates[q][n][0], coordinates[q][n][1]),
angle + 90,
3.75 / 2
);
let p3 = this.getPointByDirectionAndLen(
Cesium.Cartesian3.fromDegrees(coordinates[q][n + 1][0], coordinates[q][n + 1][1]),
angle - 90,
3.75 / 2
);
let p4 = this.getPointByDirectionAndLen(
Cesium.Cartesian3.fromDegrees(coordinates[q][n + 1][0], coordinates[q][n + 1][1]),
angle + 90,
3.75 / 2
);
viewer.entities.add({
id: num++, // 为每一个矩形实体添加id
polygon: {
hierarchy: { positions: [p1, p2, p4, p3] }, // p1-4为计算的四个角坐标
material: this.getColor(num / 300), // 为每一个矩形实体添加颜色
fill: true,
// 设置HeightReference高度参考类型为CLAMP_TO_GROUND贴地类型
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
show: true,
},
});