1.背景
有需求写一个方法cesium 提供一个代码方法接收参数为function aaa(point1,point2,radius,num)其中点1和点2是经度纬度高度对象, 以point2为圆心,radius为半径生成一个圆弧,并创建一个数组在圆弧上均匀生成 num个点,点需要包含经纬高, 返回圆弧上的点数组 和点数组内距离point1最近的一个点。
2.结果
point1:蓝色点;
point 2:圆心 绿色点 ;
radius:半径 米;
num:返回的圆上的点的个数;
closestpoint:离点1 最近的数组里的点 黄色;
3.方法如下:
function aaa(point1, point2, radius, num) {
// 计算点1到点2的距离和方位角
var dist = Cesium.Cartesian3.distance(Cesium.Cartesian3.fromDegrees(point1.longitude, point1.latitude, point1.height),
Cesium.Cartesian3.fromDegrees(point2.longitude, point2.latitude, point2.height));
var heading = Cesium.Math.heading(
Cesium.Cartesian3.fromDegrees(point1.longitude, point1.latitude),
Cesium.Cartesian3.fromDegrees(point2.longitude, point2.latitude));
// 以点2为圆心创建圆弧并生成点数组
var positions = [];
for (var i = 0; i < num; i++) {
var angle = heading + i * Cesium.Math.toRadians(360.0 / num);
var latlon = Cesium.Ellipsoid.WGS84.cartographicToCartesian(
new Cesium.Cartographic(
Cesium.Math.toRadians(point2.longitude) + Math.cos(angle) * radius / dist,
Cesium.Math.toRadians(point2.latitude) + Math.sin(angle) * radius / dist,
point2.height
)
);
positions.push(latlon.x, latlon.y, latlon.z);
}
// 将数组转换为经纬高度对象
var result = [];
for (var j = 0; j < positions.length; j += 3) {
var carto = Cesium.Cartographic.fromCartesian(new Cesium.Cartesian3(positions[j], positions[j + 1], positions[j + 2]));
result.push({
longitude: Cesium.Math.toDegrees(carto.longitude),
latitude: Cesium.Math.toDegrees(carto.latitude),
height: carto.height
});
}
// 计算距离point1最近的点
var closestDistance = Number.MAX_VALUE;
var closestPoint = null;
for (var k = 0; k < result.length; k++) {
var distance = Cesium.Cartesian3.distance(Cesium.Cartesian3.fromDegrees(point1.longitude, point1.latitude, point1.height),
Cesium.Cartesian3.fromDegrees(result[k].longitude, result[k].latitude, result[k].height));
if (distance < closestDistance) {
closestDistance = distance;
closestPoint = result[k];
}
}
return {point1:point1,closestPoint: closestPoint,points: result };
}
=================================================
// 调用 aaa 函数生成圆弧点数组
var result = aaa(point1, point2, radius, num);
var point1=result.point1,closestPoint=point2;
// 将点1和最近的点转换为 Cesium.Entity 实体
var entity1 = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(point1.longitude, point1.latitude, point1.height),
point: {
pixelSize: 10,
color: Cesium.Color.BLUE
}
});
var entity2 = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(closestPoint.longitude, closestPoint.latitude, closestPoint.height),
point: {
pixelSize: 10,
color: Cesium.Color.BLUE
}
});
// 将圆弧点数组转换为 Cesium.Cartesian3 数组
var positions = [];
for (var i = 0; i < result.points.length; i++) {
var position = Cesium.Cartesian3.fromDegrees(result.points[i].longitude, result.points[i].latitude, result.points[i].height);
positions.push(position);
}
// 创建圆弧实体
var entity3 = viewer.entities.add({
polyline: {
positions: positions,
width: 3,
material: Cesium.Color.RED
}
});