-
流程演示![在这里插入图片描述](https://img-blog.csdnimg.cn/f4c6fe4bfe7045f9b671f6eb6f5e0ace.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/266bf60d48614938a6043e3a058b8bd5.png)
2.外部引入turf
npm install @turf/turf
import { bearingToAzimuth, point } from "@turf/helpers";
import rhumbBearing from "@turf/rhumb-bearing";
import distance from "@turf/distance";
import destination from "@turf/destination";
3.实现流程
drawRectangle() {
var viewer = window.map.map3D;
this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
const points = [];
let shape = this.renderRect(points);
let step = 0;
this.handler.setInputAction((e) => {
let cartesian = viewer.scene.pickPosition(e.position);
if (!Cesium.defined(cartesian)) {
const ray = viewer.camera.getPickRay(e.position);
cartesian = viewer.scene.globe.pick(ray, viewer.scene);
}
points[step] = cartesian;
step++;
if (step === 3) {
this.handler.destroy();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
this.handler.setInputAction((e) => {
let cartesian = viewer.scene.pickPosition(e.startPosition);
if (!Cesium.defined(cartesian)) {
const ray = viewer.camera.getPickRay(e.startPosition);
cartesian = viewer.scene.globe.pick(ray, viewer.scene);
}
points[2] = cartesian;
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
},
renderRect(points) {
var viewer = window.map.map3D;
const shape = viewer.entities.add({
id: "Rectangle",
polygon: {
hierarchy: new Cesium.CallbackProperty(() => {
if (points[0] && points[1] && points[2]) {
const r0 = Cesium.Cartographic.fromCartesian(points[0]);
const r1 = Cesium.Cartographic.fromCartesian(points[1]);
const r2 = Cesium.Cartographic.fromCartesian(points[2]);
const p0 = point([
(r0.longitude * 180) / Math.PI,
(r0.latitude * 180) / Math.PI,
]);
const p1 = point([
(r1.longitude * 180) / Math.PI,
(r1.latitude * 180) / Math.PI,
]);
const p2 = point([
(r2.longitude * 180) / Math.PI,
(r2.latitude * 180) / Math.PI,
]);
this.rectanglePoint = p1;
const bearing1 = rhumbBearing(p0, p1);
const bearing2 = rhumbBearing(p0, p2);
const angle1 = bearing2 - bearing1;
const length = distance(p0, p2, { units: "miles" });
const len1 = Math.cos((angle1 / 180) * Math.PI) * length;
const dest1 = destination(p0, len1, bearing1, { units: "miles" });
const angle2 = 90 - angle1;
const len2 = Math.cos((angle2 / 180) * Math.PI) * length;
const dest2 = destination(p0, len2, 90 + bearing1, {
units: "miles",
});
const coordinates = [
points[0],
Cesium.Cartesian3.fromDegrees(...dest1.geometry.coordinates),
points[2],
Cesium.Cartesian3.fromDegrees(...dest2.geometry.coordinates),
];
return new Cesium.PolygonHierarchy(coordinates);
}
}, false),
},
});
return shape;
},