3733 lines
106 KiB
JavaScript
3733 lines
106 KiB
JavaScript
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
|
||
import carImg from '../assets/images/carplane.png';
|
||
import planeImg from '../assets/images/planeicon.png';
|
||
import cameraImg from '../assets/images/camera.png';
|
||
import droneInspectImg from '../assets/images/xunjiancar.png';
|
||
|
||
import iotImg from '../assets/images/iot.png';
|
||
import envConfig from '../../env';
|
||
import { TracePoint, TPAction, TPMode } from '../lib/TracePoint/tracePoint';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { useSelector } from 'react-redux';
|
||
import { getSiteMapInfo, getStationRegions } from '../api/stationManage';
|
||
|
||
|
||
import * as Cesium from 'cesium';
|
||
|
||
import 'cesium/Build/Cesium/Widgets/widgets.css';
|
||
|
||
const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer, activeType, overlayRefreshKey = 0, focusOverlay = null, onObstacleRadiusChange, obstacleShapes = [], onObstacleRectResize, siteMapInfoId, detectReportInfo }, ref) => {
|
||
const containerRef = useRef(null);
|
||
const viewerRef = useRef(null);
|
||
const tooltipRef = useRef(null);
|
||
const hasFlownRef = useRef(false);
|
||
const eventHandlerRef = useRef(null);
|
||
const entityMapRef = useRef(new Map());
|
||
const alarmMapRef = useRef(new Map());
|
||
const iotMapRef = useRef(new Map());
|
||
const planLineRef = useRef(null); // points 规划航线
|
||
const polygonRef = useRef(null); // coverage 区域多边形
|
||
const navLineRef = useRef(null); // 完成点实时轨迹
|
||
const markedPointsRef = useRef([]); // 标记点实体
|
||
const obstacleCirclesRef = useRef([]); // 障碍物点圆形实体
|
||
const markedLineRef = useRef(null); // 标记点连线实体
|
||
const lastMarkedPointsRef = useRef([]); // 上次渲染的标记点数据,用于增量更新
|
||
const onMarkPointRef = useRef(onMarkPoint); // 总是指向最新的 onMarkPoint,避免闭包滞后
|
||
const onCameraClickRef = useRef(onCameraClick); // 同样处理,避免闭包滞后
|
||
const lastHoverPositionRef = useRef(null);
|
||
const { t } = useTranslation();
|
||
|
||
// 场站已配置的返航点 / 分区叠加显示
|
||
const stationId = useSelector((state) => state?.station?.stationId || state?.station?.currentStation?.id);
|
||
const [stationOverlay, setStationOverlay] = useState({ returnPoints: [], regions: [], tempObstaclePoints: [] });
|
||
const stationOverlayIdsRef = useRef([]);
|
||
const returnPointPinUrlRef = useRef(null);
|
||
// 被点击聚焦的返航点 id / 图例高亮类型
|
||
const [highlightReturnPointId, setHighlightReturnPointId] = useState('');
|
||
const [legendHighlight, setLegendHighlight] = useState('');
|
||
|
||
|
||
const realtimeEntityRef = useRef(null);
|
||
const realtimeLineRef = useRef(null);
|
||
const realtimeTrackRef = useRef([]);
|
||
const realtimeHaloControllerRef = useRef(null); // 实时模式光圈 controller
|
||
const realtimeHaloRingsRef = useRef([]); // 实时模式光圈 3 个 ring
|
||
const realtimeLabelCarNameRef = useRef(''); // 实时模式机器名称缓存
|
||
|
||
const tracePointRef = useRef(new TracePoint());
|
||
const lastFinishPointRef = useRef(null);
|
||
const isNavigationModeRef = useRef(false);
|
||
const followCarEntityRef = useRef(null); // 跟随小车的实例
|
||
|
||
const isCameraFlyingRef = useRef(false);
|
||
const lastFlightPromiseRef = useRef(null);
|
||
|
||
const draggingObstacleRef = useRef(null)
|
||
const [isDraggingObstacle, setIsDraggingObstacle] = useState(false);
|
||
|
||
// ==============================
|
||
// 飞行优先级调度:优先级高的可打断低的;同级不重复起飞
|
||
// realtime(100) > focus(90) > devices(80) > track(70) > layer(10)
|
||
// ==============================
|
||
const lastFlightPriorityRef = useRef(-1);
|
||
//const FLIGHT_PRIORITY = { realtime: 100, focus: 90, devices: 80, track: 70, layer: 10 };
|
||
//const flyToView = (viewer, priority, config) => {
|
||
// if (!viewer) return;
|
||
// if (priority <= lastFlightPriorityRef.current) return; // 同级或更低不重复/覆盖;更高优先级才打断
|
||
// lastFlightPriorityRef.current = priority;
|
||
// try { viewer.camera.cancelFlight(); } catch (e) { /* 忽略取消异常 */ }
|
||
// viewer.camera.flyTo(config);
|
||
//};
|
||
|
||
|
||
const resetFlightPriority = () => { lastFlightPriorityRef.current = -1; };
|
||
const getObstacleHandlePosition = (
|
||
lon,
|
||
lat,
|
||
radius
|
||
) => {
|
||
const center = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
|
||
|
||
// 建立以圆心为原点的东-北-天坐标系
|
||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(center);
|
||
|
||
// 手柄放在圆周的东侧
|
||
return Cesium.Matrix4.multiplyByPoint(
|
||
enu,
|
||
new Cesium.Cartesian3(radius, 0, 0),
|
||
new Cesium.Cartesian3()
|
||
);
|
||
};
|
||
|
||
// 矩形障碍物:以 lon/lat 为中心、长宽(米)为 width/height 的经度纬度矩形
|
||
const getObstacleRectCoordinates = (lon, lat, width, height) => {
|
||
const halfWidthDeg =
|
||
width / 2 / (111320 * Math.cos(Cesium.Math.toRadians(lat)));
|
||
const halfHeightDeg = height / 2 / 111320;
|
||
return Cesium.Rectangle.fromDegrees(
|
||
lon - halfWidthDeg,
|
||
lat - halfHeightDeg,
|
||
lon + halfWidthDeg,
|
||
lat + halfHeightDeg
|
||
);
|
||
};
|
||
|
||
// 矩形拖动手柄:放在矩形的东北角
|
||
const getObstacleRectHandlePosition = (lon, lat, width, height) => {
|
||
const halfWidthDeg =
|
||
width / 2 / (111320 * Math.cos(Cesium.Math.toRadians(lat)));
|
||
const halfHeightDeg = height / 2 / 111320;
|
||
return Cesium.Cartesian3.fromDegrees(
|
||
lon + halfWidthDeg,
|
||
lat + halfHeightDeg,
|
||
0
|
||
);
|
||
};
|
||
|
||
// 打印矩形障碍物信息(center 为 WGS84,size 为以 center 为中心的长宽,单位米)
|
||
const logRectObstacleInfo = (obstacle, index, lon, lat, width, height) => {
|
||
const info = {
|
||
id: obstacle?.id ?? `station-obstacle-point-${index}`,
|
||
shape_type: 'aabb',
|
||
center: [Number(lon), Number(lat)],
|
||
size: [Number(width.toFixed(2)), Number(height.toFixed(2))],
|
||
yaw: 0,
|
||
cost: 254,
|
||
source: 'ui',
|
||
};
|
||
console.log('[矩形障碍物]', JSON.stringify(info, null, 2));
|
||
return info;
|
||
};
|
||
|
||
// 障碍物形状签名:内容变化时才重建地图实体
|
||
const obstacleShapeSignature = JSON.stringify(obstacleShapes || []);
|
||
|
||
const [drawPoints, setDrawPoints] = useState([]);
|
||
const drawLineRef = useRef(null);
|
||
const pointEntitiesRef = useRef([]);
|
||
|
||
const movingPathRef = useRef([]);
|
||
const movingIndexRef = useRef(0);
|
||
const isMovingRef = useRef(false);
|
||
const moveSpeedRef = useRef(0.02);
|
||
const movingEntityRef = useRef(null);
|
||
const realtimeCartesianRef = useRef([]); // 直接存 Cartesian3(性能最高)
|
||
const realtimeLineEntityRef = useRef(null);
|
||
const realtimeCarEntityRef = useRef(null);
|
||
const realtimeLastPointRef = useRef(null);
|
||
const realtimeHiddenRef = useRef(false);
|
||
const focusEntityRef = useRef(null);
|
||
const hiddenByFocusRef = useRef([]);
|
||
|
||
const yellowCircleCanvas = useMemo(
|
||
() => createYellowCircleCanvas(30),
|
||
[]
|
||
);
|
||
const glowCircleCanvas = useMemo(
|
||
() => createGlowCircleCanvas(45),
|
||
[]
|
||
);
|
||
const glowBlinkColor = useMemo(
|
||
() =>
|
||
createGlowBlinkColor({
|
||
minAlpha: 0.25,
|
||
maxAlpha: 0.75,
|
||
speed: 1.1
|
||
}),
|
||
[]
|
||
);
|
||
|
||
const liveObstacleEntities = new Map();
|
||
|
||
// ==============================
|
||
// 统一相机飞行调度器
|
||
// ==============================
|
||
const FLIGHT_PRIORITY = {
|
||
devices: 10,
|
||
track: 30,
|
||
layer: 40,
|
||
focus: 60,
|
||
realtime: 70,
|
||
manual: 100,
|
||
};
|
||
|
||
const flightStateRef = useRef({
|
||
priority: -1,
|
||
key: null,
|
||
token: 0,
|
||
flying: false,
|
||
});
|
||
|
||
useEffect(() => {
|
||
if (!containerRef.current) return;
|
||
if (viewerRef.current) return;
|
||
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjk0NjI1MC0wZGYyLTQ1YzItYjJmZi0wY2M5ODEwODllYzIiLCJpZCI6Mzk3MTQxLCJpYXQiOjE3NzI1MjkwMjV9.U6qmakhDgXJVXwLFyWzSxAUOFZRrDkIsRUPP6CCdnKg";
|
||
|
||
|
||
const viewer = new Cesium.Viewer(containerRef.current, {
|
||
useBrowserRecommendedResolution: false,
|
||
//terrain: Cesium.Terrain.fromWorldTerrain(),
|
||
|
||
|
||
animation: false,
|
||
timeline: false,
|
||
baseLayerPicker: true,
|
||
geocoder: false,
|
||
homeButton: false,
|
||
sceneModePicker: false,
|
||
navigationHelpButton: false,
|
||
fullscreenButton: false,
|
||
infoBox: false,
|
||
imageryProvider: new Cesium.UrlTemplateImageryProvider({
|
||
url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
|
||
fileExtension: "jpg"
|
||
})
|
||
});
|
||
viewer.resolutionScale = 2.0;
|
||
|
||
viewerRef.current = viewer;
|
||
viewer.scene.globe.baseColor = Cesium.Color.BLACK;
|
||
viewer.scene.globe.depthTestAgainstTerrain = false;
|
||
viewer.scene.requestRenderMode = true; // 👈 加这个(只在需要时渲染)
|
||
viewer.scene.globe.enableLighting = false;
|
||
|
||
//viewer.camera.flyTo({
|
||
// // 中国中心大致坐标 + 合适高度(200万米)
|
||
// destination: Cesium.Cartesian3.fromDegrees(103.84, 31.15, 2000000),
|
||
// orientation: {
|
||
// heading: Cesium.Math.toRadians(0),
|
||
// pitch: Cesium.Math.toRadians(-90),
|
||
// roll: 0
|
||
// },
|
||
// duration: 0 // 初始化直接到位,无需动画
|
||
//});
|
||
|
||
try { fetchPublishedLayers() } catch (e) { }
|
||
|
||
return () => {
|
||
if (lastFlightPromiseRef.current) viewer.camera.cancelFlight();
|
||
};
|
||
}, []);
|
||
function updateLiveObstacleBoxes(
|
||
viewer,
|
||
message,
|
||
) {
|
||
console.log(message, "障碍物信息")
|
||
return;
|
||
const payload = message.data ?? message;
|
||
const objects = payload.objects ?? [];
|
||
|
||
objects.forEach((obj, index) => {
|
||
const lat = Number(obj.latitude);
|
||
const lon = Number(obj.longitude);
|
||
const sx = Number(obj.size_x);
|
||
const sy = Number(obj.size_y);
|
||
const sz = Number(obj.size_z);
|
||
|
||
if (
|
||
!Number.isFinite(lat) ||
|
||
!Number.isFinite(lon) ||
|
||
!Number.isFinite(sx) ||
|
||
!Number.isFinite(sy) ||
|
||
!Number.isFinite(sz) ||
|
||
sx <= 0 ||
|
||
sy <= 0 ||
|
||
sz <= 0
|
||
) {
|
||
return;
|
||
}
|
||
|
||
const id = `live-obstacle-${obj.track_id ?? index}`;
|
||
|
||
// size_x、size_y、size_z 作为长、宽、高,单位按米处理
|
||
const position = Cesium.Cartesian3.fromDegrees(
|
||
lon,
|
||
lat,
|
||
sz / 2,
|
||
);
|
||
|
||
const orientation = Cesium.Transforms.headingPitchRollQuaternion(
|
||
position,
|
||
new Cesium.HeadingPitchRoll(
|
||
Cesium.Math.toRadians(Number(obj.angle ?? 0)),
|
||
0,
|
||
0,
|
||
),
|
||
);
|
||
|
||
const labelText =
|
||
`${obj.class_name ?? '障碍物'} #${obj.track_id ?? index}`;
|
||
|
||
let entity = viewer.entities.getById(id);
|
||
|
||
if (!entity) {
|
||
entity = viewer.entities.add({
|
||
id,
|
||
position,
|
||
orientation,
|
||
box: {
|
||
dimensions: new Cesium.Cartesian3(sx, sy, sz),
|
||
material: Cesium.Color.RED.withAlpha(0.18),
|
||
outline: true,
|
||
outlineColor: Cesium.Color.RED,
|
||
},
|
||
label: {
|
||
text: labelText,
|
||
font: '14px sans-serif',
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: Cesium.Color.RED.withAlpha(0.85),
|
||
pixelOffset: new Cesium.Cartesian2(0, -20),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
} else {
|
||
entity.position = position;
|
||
entity.orientation = orientation;
|
||
|
||
if (entity.box) {
|
||
entity.box.dimensions = new Cesium.Cartesian3(sx, sy, sz);
|
||
}
|
||
|
||
if (entity.label) {
|
||
entity.label.text = labelText;
|
||
}
|
||
}
|
||
|
||
liveObstacleEntities.set(id, entity);
|
||
});
|
||
}
|
||
|
||
|
||
const handleDetectFn = (res) => {
|
||
console.log(res, "监测到障碍物")
|
||
const viewer = viewerRef.current;
|
||
updateLiveObstacleBoxes(viewer, res);
|
||
};
|
||
|
||
|
||
|
||
|
||
|
||
const flyToView = (viewer, priority, config, key = '') => {
|
||
if (!viewer || viewer.isDestroyed()) return false;
|
||
|
||
const state = flightStateRef.current;
|
||
const now = Date.now();
|
||
|
||
// 相同目标正在飞行,忽略重复请求
|
||
if (
|
||
state.flying &&
|
||
state.priority === priority &&
|
||
state.key === key &&
|
||
now - (state.startedAt || 0) < 3000
|
||
) {
|
||
return false;
|
||
}
|
||
|
||
// 仅在当前飞行尚未结束时执行优先级比较
|
||
if (state.flying && priority < state.priority) {
|
||
return false;
|
||
}
|
||
|
||
const token = ++state.token;
|
||
|
||
state.priority = priority;
|
||
state.key = key;
|
||
state.startedAt = now;
|
||
state.flying = true;
|
||
|
||
try {
|
||
viewer.camera.cancelFlight();
|
||
|
||
viewer.camera.flyTo({
|
||
...config,
|
||
|
||
complete: () => {
|
||
// 旧飞行的回调不能清除新飞行状态
|
||
if (flightStateRef.current.token !== token) return;
|
||
|
||
flightStateRef.current.flying = false;
|
||
flightStateRef.current.priority = -1;
|
||
flightStateRef.current.key = null;
|
||
|
||
config.complete?.();
|
||
},
|
||
|
||
cancel: () => {
|
||
if (flightStateRef.current.token !== token) return;
|
||
|
||
flightStateRef.current.flying = false;
|
||
flightStateRef.current.priority = -1;
|
||
flightStateRef.current.key = null;
|
||
|
||
config.cancel?.();
|
||
},
|
||
});
|
||
|
||
return true;
|
||
} catch (error) {
|
||
if (flightStateRef.current.token === token) {
|
||
flightStateRef.current.flying = false;
|
||
flightStateRef.current.priority = -1;
|
||
flightStateRef.current.key = null;
|
||
}
|
||
|
||
console.error('地图飞行失败:', error);
|
||
return false;
|
||
}
|
||
};
|
||
|
||
|
||
|
||
const clearDrawingPath = () => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
|
||
pointEntitiesRef.current.forEach(p => {
|
||
viewer.entities.removeById(p);
|
||
});
|
||
pointEntitiesRef.current = [];
|
||
|
||
if (drawLineRef.current) {
|
||
viewer.entities.remove(drawLineRef.current);
|
||
drawLineRef.current = null;
|
||
}
|
||
|
||
setDrawPoints([]);
|
||
onPathChange && onPathChange([]);
|
||
};
|
||
|
||
// ============================================================
|
||
// 实时光圈创建 / 更新(给 realtimeCarEntity 配套使用)
|
||
// 特点:多层扩散动画光圈,独立一套 id
|
||
// ============================================================
|
||
function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') {
|
||
const haloBaseId = haloId;
|
||
const RING_COUNT = 3;
|
||
const MIN_SIZE = 100;
|
||
const MAX_SIZE = size;
|
||
const DURATION = 1600;
|
||
const DELAY = 530;
|
||
|
||
// 1) controller 是否存在
|
||
let controller = viewer.entities.getById(haloBaseId);
|
||
if (!controller) {
|
||
controller = viewer.entities.add({ id: haloBaseId, position, show: true });
|
||
} else {
|
||
controller.position = position;
|
||
}
|
||
realtimeHaloControllerRef.current = controller;
|
||
|
||
// 2) 三个 ring 是否存在(首次创建用,之后只更新 position)
|
||
if (realtimeHaloRingsRef.current.length !== RING_COUNT) {
|
||
realtimeHaloRingsRef.current = new Array(RING_COUNT).fill(null);
|
||
}
|
||
|
||
for (let ringIndex = 0; ringIndex < RING_COUNT; ringIndex++) {
|
||
const ringId = `${haloBaseId}_${ringIndex}`;
|
||
let ring = viewer.entities.getById(ringId);
|
||
const startTime = Date.now() - ringIndex * DELAY;
|
||
const getProgress = () => ((Date.now() - startTime) % DURATION) / DURATION;
|
||
|
||
if (!ring) {
|
||
const ringSize = new Cesium.CallbackProperty(() => {
|
||
const progress = getProgress();
|
||
const eased = 1 - Math.pow(1 - progress, 2);
|
||
return MIN_SIZE + (MAX_SIZE - MIN_SIZE) * eased;
|
||
}, false);
|
||
|
||
const ringColor = new Cesium.CallbackProperty(() => {
|
||
const progress = getProgress();
|
||
const alpha = 0.42 * Math.pow(1 - progress, 1.5);
|
||
return color.withAlpha(alpha);
|
||
}, false);
|
||
|
||
ring = viewer.entities.add({
|
||
id: ringId,
|
||
position: position,
|
||
billboard: {
|
||
image: createGlowCircleCanvas(64),
|
||
width: ringSize,
|
||
height: ringSize,
|
||
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
|
||
verticalOrigin: Cesium.VerticalOrigin.CENTER,
|
||
pixelOffset: new Cesium.Cartesian2(0, 0),
|
||
color: ringColor,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
heightReference: Cesium.HeightReference.NONE,
|
||
},
|
||
});
|
||
realtimeHaloRingsRef.current[ringIndex] = ring;
|
||
} else {
|
||
ring.position = position;
|
||
}
|
||
}
|
||
}
|
||
|
||
// ============================================================
|
||
// 清理实时光圈(hasRealtime 为 false 时调用)
|
||
// ============================================================
|
||
function removeRealtimeHalo(viewer) {
|
||
const haloBaseId = 'realtime_car_halo';
|
||
[haloBaseId, `${haloBaseId}_0`, `${haloBaseId}_1`, `${haloBaseId}_2`].forEach(eid => {
|
||
const entity = viewer.entities.getById(eid);
|
||
if (entity) viewer.entities.remove(entity);
|
||
});
|
||
realtimeHaloControllerRef.current = null;
|
||
realtimeHaloRingsRef.current = [];
|
||
}
|
||
|
||
const calculateDirection = (point1, point2) => {
|
||
const lon1 = point1.lon;
|
||
const lat1 = point1.lat;
|
||
const lon2 = point2.lon;
|
||
const lat2 = point2.lat;
|
||
const dLon = lon2 - lon1;
|
||
const dLat = lat2 - lat1;
|
||
const angle = Math.atan2(dLat, dLon);
|
||
return angle;
|
||
};
|
||
|
||
const drawTrackLine = (points) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
|
||
|
||
// ======================
|
||
// 是否实时模式
|
||
// ======================
|
||
const isRealtimeMode = !!(
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat))
|
||
);
|
||
|
||
if (planLineRef.current) {
|
||
viewer.entities.remove(planLineRef.current);
|
||
}
|
||
|
||
// 2. 传入的 points 本身为空 → 清空轨迹退出
|
||
if (!points || points.length === 0) {
|
||
const viewer = viewerRef.current;
|
||
if (viewer) {
|
||
try {
|
||
if (planLineRef.current) {
|
||
viewer.entities.remove(planLineRef.current);
|
||
planLineRef.current = null;
|
||
}
|
||
} catch (e) { }
|
||
viewer.scene.requestRender(); // 强制刷新!
|
||
}
|
||
return;
|
||
}
|
||
const validPoints = points?.filter(p => {
|
||
|
||
const lon = Number(p.lng);
|
||
const lat = Number(p.lat);
|
||
return (
|
||
!isNaN(lon) &&
|
||
!isNaN(lat) &&
|
||
Math.abs(lon) < 180 &&
|
||
Math.abs(lat) < 90 &&
|
||
lon !== 0 &&
|
||
lat !== 0
|
||
);
|
||
});
|
||
|
||
if (validPoints.length === 0) return;
|
||
|
||
const positions = validPoints.map(point =>
|
||
Cesium.Cartesian3.fromDegrees(
|
||
Number(point.lng),
|
||
Number(point.lat)
|
||
)
|
||
);
|
||
|
||
const trackLine = viewer.entities.add({
|
||
polyline: {
|
||
positions: positions,
|
||
width: 2,
|
||
// 规划航线用橙色,和实时轨迹区分
|
||
material: Cesium.Color.ORANGE.withAlpha(0.8),
|
||
clampToGround: true,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
|
||
planLineRef.current = trackLine;
|
||
|
||
// ======================
|
||
// 🚀 非实时模式 -> 自动飞到轨迹
|
||
// ======================
|
||
if (!isRealtimeMode) {
|
||
|
||
let minLon = 180, maxLon = -180;
|
||
let minLat = 90, maxLat = -90;
|
||
|
||
validPoints.forEach(p => {
|
||
minLon = Math.min(minLon, p.lng);
|
||
maxLon = Math.max(maxLon, p.lng);
|
||
minLat = Math.min(minLat, p.lat);
|
||
maxLat = Math.max(maxLat, p.lat);
|
||
});
|
||
if (getCameraMode() !== "track") return;
|
||
|
||
// 单个点
|
||
if (validPoints.length === 1) {
|
||
|
||
|
||
const p = validPoints[0];
|
||
viewer.scene.requestRender();
|
||
flyToView(viewer, FLIGHT_PRIORITY.track, {
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
p.lng,
|
||
p.lat,
|
||
800
|
||
),
|
||
duration: 1.2
|
||
}, `track:${minLon},${minLat},${maxLon},${maxLat}`
|
||
);
|
||
viewer.scene.requestRender();
|
||
|
||
} else {
|
||
|
||
const centerLon = (minLon + maxLon) / 2;
|
||
const centerLat = (minLat + maxLat) / 2;
|
||
|
||
const destination = Cesium.Cartesian3.fromDegrees(
|
||
centerLon,
|
||
centerLat,
|
||
800
|
||
);
|
||
|
||
flyToView(viewer, FLIGHT_PRIORITY.track, {
|
||
destination,
|
||
duration: 1.2
|
||
});
|
||
|
||
viewer.scene.requestRender();
|
||
|
||
}
|
||
|
||
}
|
||
|
||
};
|
||
|
||
const drawPolygon = (points) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
const isRealtimeMode = !!(
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat))
|
||
);
|
||
|
||
|
||
// 每次绘制区域前,先移除上一次绘制的地块
|
||
if (polygonRef.current) {
|
||
try {
|
||
viewer.entities.remove(polygonRef.current);
|
||
polygonRef.current = null;
|
||
} catch (e) { }
|
||
}
|
||
//if (planLineRef.current) {
|
||
// try {
|
||
// viewer.entities.remove(planLineRef.current);
|
||
// planLineRef.current = null;
|
||
// } catch (e) { }
|
||
//}
|
||
|
||
const validPoints = points?.filter(p => {
|
||
|
||
const lon = Number(p.lng);
|
||
const lat = Number(p.lat);
|
||
return (
|
||
!isNaN(lon) &&
|
||
!isNaN(lat) &&
|
||
Math.abs(lon) < 180 &&
|
||
Math.abs(lat) < 90 &&
|
||
lon !== 0 &&
|
||
lat !== 0
|
||
);
|
||
});
|
||
|
||
if (validPoints.length === 0) return;
|
||
|
||
const positions = validPoints.map(point =>
|
||
Cesium.Cartesian3.fromDegrees(
|
||
Number(point.lng),
|
||
Number(point.lat)
|
||
)
|
||
);
|
||
|
||
// coverage(区域覆盖)模式下以多边形 polygon 框绘制,否则为折线
|
||
const isCoverage = routeMode === 'coverage';
|
||
|
||
let trackLine;
|
||
if (isCoverage) {
|
||
trackLine = viewer.entities.add({
|
||
polygon: {
|
||
hierarchy: positions,
|
||
material: Cesium.Color.ORANGE.withAlpha(0.2),
|
||
outline: true,
|
||
outlineColor: Cesium.Color.ORANGE.withAlpha(0.8),
|
||
height: 0,
|
||
clampToGround: true,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
} else {
|
||
trackLine = viewer.entities.add({
|
||
polyline: {
|
||
positions: positions,
|
||
width: 2,
|
||
|
||
material: Cesium.Color.ORANGE.withAlpha(0.8),
|
||
clampToGround: true,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
}
|
||
|
||
polygonRef.current = trackLine;
|
||
|
||
// ======================
|
||
// 🚀 非实时模式 -> 自动飞到轨迹
|
||
// ======================
|
||
if (!isRealtimeMode) {
|
||
|
||
let minLon = 180, maxLon = -180;
|
||
let minLat = 90, maxLat = -90;
|
||
|
||
validPoints.forEach(p => {
|
||
minLon = Math.min(minLon, p.lng);
|
||
maxLon = Math.max(maxLon, p.lng);
|
||
minLat = Math.min(minLat, p.lat);
|
||
maxLat = Math.max(maxLat, p.lat);
|
||
});
|
||
if (getCameraMode() !== "track") return;
|
||
|
||
// 单个点
|
||
if (validPoints.length === 1) {
|
||
|
||
const p = validPoints[0];
|
||
viewer.scene.requestRender();
|
||
flyToView(viewer, FLIGHT_PRIORITY.track, {
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
p.lng,
|
||
p.lat,
|
||
800
|
||
),
|
||
duration: 1.2
|
||
});
|
||
viewer.scene.requestRender();
|
||
|
||
} else {
|
||
|
||
const rectangle = Cesium.Rectangle.fromDegrees(
|
||
minLon,
|
||
minLat,
|
||
maxLon,
|
||
maxLat
|
||
);
|
||
|
||
viewer.scene.requestRender();
|
||
|
||
flyToView(viewer, FLIGHT_PRIORITY.track, {
|
||
destination: rectangle,
|
||
duration: 1.2
|
||
});
|
||
|
||
viewer.scene.requestRender();
|
||
|
||
}
|
||
|
||
}
|
||
|
||
};
|
||
useEffect(() => {
|
||
resetFlightPriority();
|
||
if (polyPoints && polyPoints.length > 0) {
|
||
drawPolygon(polyPoints)
|
||
} else {
|
||
// polyPoints 被清空时,移除已绘制的区域
|
||
const viewer = viewerRef.current;
|
||
if (viewer && polygonRef.current) {
|
||
try {
|
||
viewer.entities.remove(polygonRef.current);
|
||
polygonRef.current = null;
|
||
} catch (e) { }
|
||
}
|
||
}
|
||
|
||
}, [polyPoints])
|
||
|
||
useEffect(() => {
|
||
resetFlightPriority();
|
||
if (viewerRef.current) {
|
||
drawTrackLine(points);
|
||
}
|
||
}, [points]);
|
||
|
||
// 渲染标记点 + 连线(增量更新:只增删改真正变化的点)
|
||
const drawMarkedPoints = (points) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
|
||
const newPoints = points || [];
|
||
const prevPoints = lastMarkedPointsRef.current || [];
|
||
const isObstacle = activeType === 'obstaclePoint';
|
||
|
||
const nextIds = new Set(newPoints.map((p, i) => `marked-point-${p.id ?? i}`));
|
||
const nextObstacleCircleIds = new Set(newPoints.map((p, i) => `marked-obstacle-circle-${p.id ?? i}`));
|
||
|
||
// 1) 删除不在新列表中的旧 entity
|
||
markedPointsRef.current = markedPointsRef.current.filter(id => {
|
||
if (!nextIds.has(id)) {
|
||
viewer.entities.removeById(id);
|
||
// 同时删除对应的 obstacle circle
|
||
const circleId = `marked-obstacle-circle-${id ?? i}`;
|
||
viewer.entities.removeById(circleId);
|
||
return false;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
// 清理不在列表中的 obstacle circle
|
||
obstacleCirclesRef.current = obstacleCirclesRef.current.filter(id => {
|
||
if (!nextObstacleCircleIds.has(id)) {
|
||
viewer.entities.removeById(id);
|
||
return false;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
// 2) 新增或更新标记点 entity
|
||
newPoints.forEach((p, i) => {
|
||
const id = `marked-point-${p.id ?? i}`;
|
||
|
||
const circleId = `marked-obstacle-circle-${p.id ?? i}`;
|
||
const entity = viewer.entities.getById(id);
|
||
const position = Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat));
|
||
const labelText = `${i + 1}`;
|
||
|
||
if (entity) {
|
||
entity.position = position;
|
||
if (entity.label) entity.label.text = labelText;
|
||
} else {
|
||
const pointColor = isObstacle
|
||
? Cesium.Color.fromCssColorString('#ff4d4f')
|
||
: Cesium.Color.GREEN;
|
||
viewer.entities.add({
|
||
id,
|
||
position,
|
||
point: {
|
||
color: pointColor,
|
||
pixelSize: 15,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
label: {
|
||
text: labelText,
|
||
font: '14px sans-serif',
|
||
pixelOffset: new Cesium.Cartesian2(0, -20),
|
||
fillColor: Cesium.Color.WHITE,
|
||
outlineColor: Cesium.Color.BLACK,
|
||
outlineWidth: 2,
|
||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||
}
|
||
});
|
||
markedPointsRef.current.push(id);
|
||
}
|
||
|
||
// 障碍物点:创建/更新圆形区域(EllipseGraphics,单位是米)
|
||
//if (isObstacle) {
|
||
// const radius = Math.max(0.5, Number(p.radius) || 2.0);
|
||
// const circleEntity = viewer.entities.getById(circleId);
|
||
// if (circleEntity) {
|
||
// circleEntity.position = position;
|
||
// circleEntity.ellipse.semiMajorAxis = radius;
|
||
// circleEntity.ellipse.semiMinorAxis = radius;
|
||
// } else {
|
||
// viewer.entities.add({
|
||
// id: circleId,
|
||
// position,
|
||
// ellipse: {
|
||
// semiMajorAxis: radius,
|
||
// semiMinorAxis: radius,
|
||
// material: new Cesium.Color(1.0, 0.3, 0.3, 0.25),
|
||
// outline: true,
|
||
// outlineColor: Cesium.Color.RED,
|
||
// outlineWidth: 2,
|
||
// height: 0,
|
||
// },
|
||
// });
|
||
// obstacleCirclesRef.current.push(circleId);
|
||
// }
|
||
//}
|
||
});
|
||
|
||
// 3) 连线:只有坐标/数量真正变化时才重建
|
||
if (activeType !== "routeGen") {
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
const lineChanged = newPoints.length !== prevPoints.length ||
|
||
newPoints.some((p, i) => {
|
||
const pp = prevPoints[i];
|
||
return !pp || Number(pp.lon) !== Number(p.lon) || Number(pp.lat) !== Number(p.lat);
|
||
});
|
||
|
||
if (lineChanged) {
|
||
if (markedLineRef.current) {
|
||
try { viewer.entities.remove(markedLineRef.current); } catch (e) { }
|
||
markedLineRef.current = null;
|
||
}
|
||
if (newPoints.length >= 2) {
|
||
const linePositions = newPoints.map(p =>
|
||
Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat))
|
||
);
|
||
markedLineRef.current = viewer.entities.add({
|
||
polyline: {
|
||
positions: linePositions,
|
||
width: 4,
|
||
material: Cesium.Color.SKYBLUE,
|
||
clampToGround: true,
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
lastMarkedPointsRef.current = newPoints.map(p => ({ ...p }));
|
||
viewer.scene.requestRender();
|
||
};
|
||
|
||
useEffect(() => {
|
||
if (viewerRef.current) {
|
||
drawMarkedPoints(markedPoints);
|
||
}
|
||
}, [markedPoints]);
|
||
|
||
function resolveDeviceStatus(device) {
|
||
const fsRaw = device?.feStatus;
|
||
const stRaw = device?.status;
|
||
|
||
// feStatus:0=离线,1=工作中,2=空闲
|
||
if (fsRaw !== undefined && fsRaw !== null && fsRaw !== '') {
|
||
const fs = Number(fsRaw);
|
||
if (fs === 0) return 'offline';
|
||
if (fs === 1) return 'working';
|
||
if (fs === 2) return 'idle';
|
||
}
|
||
|
||
// status:1=工作中,2=空闲,3=离线
|
||
if (stRaw !== undefined && stRaw !== null && stRaw !== '') {
|
||
const st = Number(stRaw);
|
||
if (st === 1) return 'working';
|
||
if (st === 2) return 'idle';
|
||
if (st === 3) return 'offline';
|
||
}
|
||
|
||
return 'idle';
|
||
}
|
||
|
||
// 光圈颜色:工作中蓝(#1677ff)/ 空闲绿(#52c41a)/ 离线红(#ff4d4f)
|
||
function getDeviceHaloColor(device) {
|
||
const state = resolveDeviceStatus(device);
|
||
if (state === 'working') return Cesium.Color.fromCssColorString('#1677ff');
|
||
if (state === 'offline') return Cesium.Color.fromCssColorString('#ff4d4f');
|
||
return Cesium.Color.fromCssColorString('#52c41a');
|
||
}
|
||
|
||
const getCursorLngLat = (viewer, screenPos) => {
|
||
const cartesian = viewer.camera.pickEllipsoid(screenPos, viewer.scene.globe.ellipsoid);
|
||
if (!Cesium.defined(cartesian)) return { lon: NaN, lat: NaN };
|
||
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
|
||
return {
|
||
lon: Cesium.Math.toDegrees(cartographic.longitude),
|
||
lat: Cesium.Math.toDegrees(cartographic.latitude),
|
||
};
|
||
};
|
||
|
||
function showCoordinateTooltip(tooltip, position, t, lon, lat, robot) {
|
||
tooltip.style.display = "block";
|
||
tooltip.style.left = position.x + 12 + "px";
|
||
tooltip.style.top = position.y + 12 + "px";
|
||
tooltip.style.whiteSpace = "nowrap";
|
||
|
||
const lonStr = Number.isFinite(lon) ? lon.toFixed(6) : "--";
|
||
const latStr = Number.isFinite(lat) ? lat.toFixed(6) : "--";
|
||
|
||
if (robot) {
|
||
const stateKey = resolveDeviceStatus(robot);
|
||
const statusMap = {
|
||
working: { text: t('common.working'), color: '#0a40df' },
|
||
idle: { text: t('devices.idle'), color: '#12c60e' },
|
||
offline: { text: t('devices.offline'), color: '#f01212' }
|
||
};
|
||
const status = statusMap[stateKey] || statusMap.idle;
|
||
let deviceValuesHTML = '';
|
||
if (robot.devicevalue && robot.devicevalue.length > 0) {
|
||
deviceValuesHTML = robot.devicevalue.map((device) => `
|
||
<div style = "margin-bottom:4px;" > <strong>${device.name}:</strong> ${device.value}${device.unit}</div >
|
||
`).join('');
|
||
}
|
||
tooltip.innerHTML = `
|
||
<div style = "font-weight:600;margin-bottom:6px;" >🤖 ${robot.deviceAlias || robot.serialNumber || robot.name} ${robot.deviceType != null && robot.deviceType !== '' ? `
|
||
<span style="
|
||
display:inline-block;
|
||
margin-left:8px;
|
||
padding:2px 8px;
|
||
border-radius:4px;
|
||
font-size:12px;
|
||
font-weight:400;
|
||
background:#f6ffed;
|
||
color:#1677ff;
|
||
border:1px solid #b7eb8f;
|
||
">
|
||
${robot.deviceType}
|
||
</span>
|
||
` : ''}</div >
|
||
${deviceValuesHTML ? `<div style="margin-top:8px;"><strong>${t('devices.deviceData')}:</strong>${deviceValuesHTML}</div>` : ''}
|
||
<div>${t('systemSetting.longitude')}:${lonStr}</div>
|
||
<div>${t('systemSetting.latitude')}:${latStr}</div>
|
||
<div>${t('systemSetting.status')}:
|
||
<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${status.color};margin-right:4px;"></span>
|
||
<span style="color:${status.color};font-weight:bold">${status.text}</span>
|
||
</div> `;
|
||
} else {
|
||
tooltip.innerHTML = `
|
||
<div style = "font-weight:600;margin-bottom:4px;" >📍 ${t('systemSetting.longitude')}:${lonStr}</div >
|
||
<div style="font-weight:600;">${t('systemSetting.latitude')}:${latStr}</div>
|
||
`;
|
||
}
|
||
}
|
||
const handleFlyToDevice = () => {
|
||
let validPositions = [];
|
||
const viewer = viewerRef.current;
|
||
|
||
devices.forEach((device, index) => {
|
||
|
||
const raw = device?.locationMessage || device?.lastRunningStatus || {};
|
||
const parsed = parseLngLat(raw.longitude, raw.latitude);
|
||
if (!parsed) return;
|
||
|
||
const { longitude, latitude } = parsed;
|
||
|
||
validPositions.push({ lon: longitude, lat: latitude });
|
||
});
|
||
if (validPositions.length > 0) {
|
||
|
||
let minLon = 180,
|
||
maxLon = -180,
|
||
minLat = 90,
|
||
maxLat = -90;
|
||
|
||
validPositions.forEach(p => {
|
||
|
||
minLon = Math.min(minLon, p.lon);
|
||
maxLon = Math.max(maxLon, p.lon);
|
||
minLat = Math.min(minLat, p.lat);
|
||
maxLat = Math.max(maxLat, p.lat);
|
||
|
||
});
|
||
|
||
|
||
if (validPositions.length === 1) {
|
||
|
||
const p = validPositions[0];
|
||
|
||
flyToView(viewer, FLIGHT_PRIORITY.devices, {
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
p.lon,
|
||
p.lat,
|
||
800
|
||
),
|
||
duration: 1.2
|
||
});
|
||
|
||
} else {
|
||
|
||
const rectangle = Cesium.Rectangle.fromDegrees(
|
||
minLon,
|
||
minLat,
|
||
maxLon,
|
||
maxLat
|
||
);
|
||
|
||
flyToView(viewer, FLIGHT_PRIORITY.devices, {
|
||
destination: rectangle,
|
||
duration: 1.2,
|
||
});
|
||
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
// 返航点悬浮提示:显示别名与该返航点绑定的机器
|
||
function showReturnPointTooltip(tooltip, position, point) {
|
||
if (!tooltip) return;
|
||
tooltip.style.display = "block";
|
||
tooltip.style.left = position.x + 12 + "px";
|
||
tooltip.style.top = position.y + 12 + "px";
|
||
tooltip.style.whiteSpace = "nowrap";
|
||
|
||
const boundDevice = devices.find(d => d?.serialNumber === point.bindDeviceId);
|
||
const deviceLabel = point.bindDeviceId
|
||
? (boundDevice?.deviceAlias || boundDevice?.deviceName || point.bindDeviceId)
|
||
: t('devices.mapEditor.unbound');
|
||
|
||
tooltip.innerHTML = `
|
||
<div style = "font-weight:600;margin-bottom:4px;" >📍 ${point.alias || '-'}</div >
|
||
`;
|
||
}
|
||
|
||
function fetchPublishedLayers() {
|
||
const baseUrl = envConfig.geoserver_url;
|
||
//const baseUrl = 'https://gis.caasrobot.com/geoserver';
|
||
const getCapabilitiesUrl = `${baseUrl}/wms?service=WMS&version=1.1.1&request=GetCapabilities`;
|
||
|
||
fetch(getCapabilitiesUrl)
|
||
.then(response => response.text())
|
||
.then(xmlText => {
|
||
const parser = new DOMParser();
|
||
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
|
||
const layerElements = xmlDoc.getElementsByTagName('Layer');
|
||
const uniqueLayerNames = new Set();
|
||
const publishedLayers = [];
|
||
|
||
for (let i = 0; i < layerElements.length; i++) {
|
||
const layer = layerElements[i];
|
||
const nameElement = layer.getElementsByTagName('Name')[0];
|
||
const titleElement = layer.getElementsByTagName('Title')[0];
|
||
if (nameElement && nameElement.textContent) {
|
||
const layerName = nameElement.textContent;
|
||
if (layerName.includes(':') && !uniqueLayerNames.has(layerName)) {
|
||
uniqueLayerNames.add(layerName);
|
||
publishedLayers.push({
|
||
name: layerName,
|
||
title: titleElement ? titleElement.textContent : layerName
|
||
});
|
||
}
|
||
}
|
||
}
|
||
displayPublishedLayers(publishedLayers, baseUrl);
|
||
})
|
||
.catch(error => console.error('获取图层失败:', error));
|
||
}
|
||
|
||
function displayPublishedLayers(publishedLayers, baseUrl) {
|
||
//console.log('已发布的图层:', publishedLayers)
|
||
publishedLayers.forEach((layer, index) => {
|
||
const [workspace, layerName] = layer.name.split(':');
|
||
if (workspace && layerName) {
|
||
addLayerFromList(layer.name, baseUrl, index);
|
||
}
|
||
});
|
||
}
|
||
|
||
function addLayerFromList(layerFullName, baseUrl, index) {
|
||
const [workspace, layerName] = layerFullName.split(':');
|
||
if (!workspace || !layerName) return;
|
||
const wmsUrl = `${baseUrl}/wms`;
|
||
addWmsLayerToCesium(wmsUrl, workspace, layerName, index);
|
||
}
|
||
|
||
function getLayerBoundsAndFit(wmsUrl, layerName) {
|
||
console.log('=== 获取图层范围开始 ===');
|
||
|
||
const getCapabilitiesUrl = `${wmsUrl}?service=WMS&version=1.1.1&request=GetCapabilities`;
|
||
|
||
fetch(getCapabilitiesUrl)
|
||
.then(response => response.text())
|
||
.then(xmlText => {
|
||
const parser = new DOMParser();
|
||
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
|
||
const layerElements = xmlDoc.getElementsByTagName('Layer');
|
||
let layerBbox = null;
|
||
|
||
for (let i = 0; i < layerElements.length; i++) {
|
||
const layer = layerElements[i];
|
||
const nameElement = layer.getElementsByTagName('Name')[0];
|
||
|
||
if (nameElement && nameElement.textContent === layerName) {
|
||
const bboxElement = layer.getElementsByTagName('BoundingBox')[0];
|
||
if (bboxElement) {
|
||
const minx = parseFloat(bboxElement.getAttribute('minx'));
|
||
const miny = parseFloat(bboxElement.getAttribute('miny'));
|
||
const maxx = parseFloat(bboxElement.getAttribute('maxx'));
|
||
const maxy = parseFloat(bboxElement.getAttribute('maxy'));
|
||
|
||
layerBbox = [minx, miny, maxx, maxy];
|
||
console.log('找到图层范围:', layerBbox);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (layerBbox) {
|
||
try {
|
||
const bounds = new AMap.Bounds(
|
||
new AMap.LngLat(layerBbox[0], layerBbox[1]),
|
||
new AMap.LngLat(layerBbox[2], layerBbox[3])
|
||
);
|
||
map.setFitView(bounds, 15, [50, 50, 50, 50]);
|
||
console.log('地图已定位到图层范围');
|
||
} catch (error) {
|
||
console.error('地图定位失败:', error);
|
||
}
|
||
} else {
|
||
console.warn('未找到图层范围,使用默认位置');
|
||
map.setCenter([120.565, 31.453]);
|
||
map.setZoom(10);
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('获取图层范围失败:', error);
|
||
map.setCenter([120.565, 31.453]);
|
||
map.setZoom(10);
|
||
});
|
||
}
|
||
const getCameraMode = () => {
|
||
const hasRealtime =
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat));
|
||
|
||
const hasTrack = (points && points.length > 0) || polyPoints?.length > 0;
|
||
|
||
if (hasRealtime) return "realtime";
|
||
if (hasTrack) return "track";
|
||
return "devices";
|
||
};
|
||
|
||
function addWmsLayerToCesium(wmsUrl, workspace, layerName, index) {
|
||
const layerIdentifier = `${workspace}:${layerName}`;
|
||
let baseUrl = wmsUrl;
|
||
const cesiumLayers = [];
|
||
//if (index == 2 && from == "other") {
|
||
// //flyToLayer(layerIdentifier, baseUrl, 100);
|
||
//}
|
||
//if (index == 0 && from == "other") {
|
||
// flyToLayer(layerIdentifier, baseUrl, 100);
|
||
//}
|
||
//getLayerBoundsAndFit(wmsUrl, layerName);
|
||
|
||
if (baseUrl.includes('/gwc/service/wms')) {
|
||
baseUrl = baseUrl.replace('/gwc/service/wms', '');
|
||
} else if (baseUrl.includes('/gwc/service/wmts')) {
|
||
baseUrl = baseUrl.replace('/gwc/service/wmts', '');
|
||
} else if (baseUrl.includes('/wms?')) {
|
||
baseUrl = baseUrl.split('/wms?')[0];
|
||
} else if (baseUrl.includes('/wms')) {
|
||
baseUrl = baseUrl.split('/wms')[0];
|
||
}
|
||
|
||
try {
|
||
const imageryProvider = new Cesium.WebMapServiceImageryProvider({
|
||
url: `${baseUrl}/gwc/service/wms`,
|
||
layers: layerIdentifier,
|
||
parameters: {
|
||
service: 'WMS',
|
||
version: '1.1.1',
|
||
request: 'GetMap',
|
||
transparent: true,
|
||
format: 'image/png',
|
||
srs: 'EPSG:4326',
|
||
width: 256,
|
||
height: 256,
|
||
styles: ''
|
||
},
|
||
tilingScheme: new Cesium.GeographicTilingScheme(),
|
||
tileWidth: 256,
|
||
tileHeight: 256,
|
||
maximumLevel: 21,
|
||
minimumLevel: 1,
|
||
credit: new Cesium.Credit('GeoServer GWC WMS'),
|
||
usePreCachedTilesIfAvailable: true,
|
||
enablePickFeatures: false,
|
||
maximumRequests: 15,
|
||
retryAttempts: 2
|
||
});
|
||
|
||
const layer = viewerRef.current.imageryLayers.addImageryProvider(imageryProvider);
|
||
cesiumLayers.push(layer);
|
||
} catch (gwcWmsError) {
|
||
try {
|
||
const imageryProvider = new Cesium.WebMapServiceImageryProvider({
|
||
url: `${baseUrl}/${workspace}/wms`,
|
||
layers: layerIdentifier,
|
||
parameters: {
|
||
service: 'WMS',
|
||
version: '1.1.1',
|
||
request: 'GetMap',
|
||
transparent: true,
|
||
format: 'image/png',
|
||
srs: 'EPSG:3857',
|
||
width: 256,
|
||
height: 256,
|
||
styles: ''
|
||
},
|
||
tilingScheme: new Cesium.WebMercatorTilingScheme(),
|
||
tileWidth: 256,
|
||
tileHeight: 256,
|
||
maximumLevel: 18,
|
||
minimumLevel: 5,
|
||
credit: new Cesium.Credit('GeoServer WMS'),
|
||
usePreCachedTilesIfAvailable: true,
|
||
enablePickFeatures: false,
|
||
maximumRequests: 10,
|
||
retryAttempts: 2
|
||
});
|
||
|
||
const layer = viewerRef.current.imageryLayers.addImageryProvider(imageryProvider);
|
||
cesiumLayers.push(layer);
|
||
} catch (wmsError) {
|
||
const imageryProvider = new Cesium.WebMapServiceImageryProvider({
|
||
url: `${baseUrl}/gwc/service/wms`,
|
||
layers: layerIdentifier,
|
||
parameters: {
|
||
service: 'WMS',
|
||
version: '1.1.1',
|
||
request: 'GetMap',
|
||
transparent: true,
|
||
format: 'image/png',
|
||
srs: 'EPSG:4326',
|
||
width: 256,
|
||
height: 256,
|
||
styles: ''
|
||
},
|
||
tilingScheme: new Cesium.GeographicTilingScheme(),
|
||
tileWidth: 256,
|
||
tileHeight: 256,
|
||
maximumLevel: 21,
|
||
minimumLevel: 1,
|
||
credit: new Cesium.Credit('GeoServer GWC WMS'),
|
||
usePreCachedTilesIfAvailable: true,
|
||
enablePickFeatures: false,
|
||
maximumRequests: 15,
|
||
retryAttempts: 2
|
||
});
|
||
|
||
const layer = viewerRef.current.imageryLayers.addImageryProvider(imageryProvider);
|
||
cesiumLayers.push(layer);
|
||
}
|
||
}
|
||
}
|
||
|
||
function flyToLayer(layerIdentifier, baseUrl, flyHeight = 400) {
|
||
//console.log('开始获取图层范围', layerIdentifier);
|
||
const url = `${baseUrl}/wms?service=WMS&version=1.1.1&request=GetCapabilities`;
|
||
|
||
fetch(url)
|
||
.then(res => res.text())
|
||
.then(xmlText => {
|
||
const xml = new DOMParser().parseFromString(xmlText, 'text/xml');
|
||
const layerElements = xml.getElementsByTagName('Layer');
|
||
let targetBbox = null;
|
||
|
||
for (let i = 0; i < layerElements.length; i++) {
|
||
const layer = layerElements[i];
|
||
const nameElement = layer.getElementsByTagName('Name')[0];
|
||
|
||
if (nameElement && nameElement.textContent === layerIdentifier) {
|
||
const bboxElement = layer.getElementsByTagName('BoundingBox')[0];
|
||
if (bboxElement) {
|
||
const minx = parseFloat(bboxElement.getAttribute('minx'));
|
||
const miny = parseFloat(bboxElement.getAttribute('miny'));
|
||
const maxx = parseFloat(bboxElement.getAttribute('maxx'));
|
||
const maxy = parseFloat(bboxElement.getAttribute('maxy'));
|
||
targetBbox = [minx, miny, maxx, maxy];
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (!targetBbox) {
|
||
console.warn('该图层未找到BoundingBox,无法飞行', layerIdentifier);
|
||
return;
|
||
}
|
||
|
||
const [minx, miny, maxx, maxy] = targetBbox;
|
||
// 取图层中心点
|
||
const centerLon = (minx + maxx) / 2;
|
||
const centerLat = (miny + maxy) / 2;
|
||
|
||
flyToView(viewerRef.current, FLIGHT_PRIORITY.layer, {
|
||
// 固定高度,第三个参数就是高度(单位米)
|
||
destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, flyHeight),
|
||
orientation: {
|
||
heading: 0,
|
||
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
|
||
roll: 0
|
||
},
|
||
duration: 2
|
||
});
|
||
})
|
||
.catch(err => {
|
||
console.error('获取WMS Capabilities失败', err);
|
||
});
|
||
}
|
||
|
||
function getRobotEntityId(robot, index) {
|
||
if (robot.id != null) return `robot-${robot.id}`;
|
||
if (robot.name) return `robot-${robot.name}`;
|
||
return `robot-index-${index}`;
|
||
}
|
||
|
||
function createGlowCircleCanvas(size = 40, innerAlpha = 0.8) {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = Math.max(1, Number(size) || 40);
|
||
canvas.height = Math.max(1, Number(size) || 40);
|
||
const ctx = canvas.getContext("2d");
|
||
const r = Math.max(1, Number(size) || 40) / 2;
|
||
const gradient = ctx.createRadialGradient(r, r, r * 0.2, r, r, r);
|
||
gradient.addColorStop(0, `rgba(255,255,255,${innerAlpha})`);
|
||
gradient.addColorStop(0.4, `rgba(255,255,255,0.6)`);
|
||
gradient.addColorStop(0.7, `rgba(255,255,255,0.3)`);
|
||
gradient.addColorStop(1, `rgba(255,255,25,0)`);
|
||
ctx.fillStyle = gradient;
|
||
ctx.beginPath();
|
||
ctx.arc(r, r, r, 0, Math.PI * 2);
|
||
ctx.fill();
|
||
return canvas;
|
||
}
|
||
|
||
// ========== 修改 createGlowBlinkColor,增加baseColor入参 ==========
|
||
function createGlowBlinkColor({
|
||
minAlpha = 0.2,
|
||
maxAlpha = 0.9,
|
||
speed = 1.2,
|
||
baseColor
|
||
} = {}) {
|
||
const start = Date.now();
|
||
return new Cesium.CallbackProperty(() => {
|
||
const t = (Date.now() - start) / 1000;
|
||
const alpha = minAlpha + (maxAlpha - minAlpha) * (0.5 + 0.5 * Math.sin(t * speed * Math.PI * 2));
|
||
return baseColor.withAlpha(alpha);
|
||
}, false);
|
||
}
|
||
|
||
function createRobotEntity(viewer, robot, index) {
|
||
const raw = robot?.lastRunningStatus || {};
|
||
const parsed = parseLngLat(raw.longitude, raw.latitude);
|
||
if (!parsed) return null;
|
||
const { longitude, latitude } = parsed;
|
||
const baseId = getRobotEntityId(robot, index);
|
||
viewer.entities.removeById(baseId);
|
||
viewer.entities.removeById(baseId + "_alarm");
|
||
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, 0);
|
||
|
||
viewer.entities.add({
|
||
id: baseId + "_alarm",
|
||
position,
|
||
billboard: {
|
||
image: createGlowCircleCanvas(45),
|
||
width: 45,
|
||
height: 45,
|
||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||
pixelOffset: new Cesium.Cartesian2(0, -6),
|
||
color: createGlowBlinkColor({
|
||
minAlpha: 0.25,
|
||
maxAlpha: 0.75,
|
||
speed: 1.1
|
||
}),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
||
}
|
||
});
|
||
|
||
const entity = viewer.entities.add({
|
||
id: baseId,
|
||
position,
|
||
billboard: {
|
||
image: carImg,
|
||
width: 30,
|
||
height: 30,
|
||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
||
},
|
||
label: {
|
||
text: robot.name,
|
||
font: "14px sans-serif",
|
||
pixelOffset: new Cesium.Cartesian2(0, -40),
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: Cesium.Color.BLACK.withAlpha(0.6)
|
||
}
|
||
});
|
||
entity.robotData = robot;
|
||
return entity;
|
||
}
|
||
|
||
|
||
|
||
// 根据场站映射图层定位地图:切换场站时始终飞向该场站的图层
|
||
// 不再用可能滞后的 devices 判断(避免用上一场站的机器决策);
|
||
// 若场站有机器,由 devices 效果按更高优先级接管飞向机器
|
||
useEffect(() => {
|
||
const hasRealtime =
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat));
|
||
if (!mapLayer || !viewerRef.current || hasRealtime) return;
|
||
resetFlightPriority();
|
||
flyToLayer(mapLayer, envConfig.geoserver_url, 400);
|
||
}, [mapLayer]);
|
||
|
||
// 拉取当前场站已配置的返航点与分区
|
||
useEffect(() => {
|
||
if (!stationId) {
|
||
setStationOverlay({ returnPoints: [], regions: [], tempObstaclePoints: [] });
|
||
return;
|
||
}
|
||
let cancelled = false;
|
||
getSiteMapInfo({ siteId: stationId })
|
||
.then((res) => {
|
||
if (cancelled) return;
|
||
const pts = res?.code === 200 ? (res?.data?.restPoints || []) : [];
|
||
setStationOverlay(prev => ({ ...prev, tempObstaclePoints: res?.data?.tempObstaclePoints || [], returnPoints: Array.isArray(pts) ? pts : [] }));
|
||
})
|
||
.catch(() => { });
|
||
getStationRegions({ siteId: stationId })
|
||
.then((res) => {
|
||
if (cancelled) return;
|
||
const list = res?.code === 200 ? (res?.data || res?.rows || []) : [];
|
||
setStationOverlay(prev => ({ ...prev, regions: Array.isArray(list) ? list : [] }));
|
||
})
|
||
.catch(() => { });
|
||
return () => { cancelled = true; };
|
||
}, [stationId, overlayRefreshKey]);
|
||
|
||
// 在地图上叠加显示:返航点用标志图标,分区用小框
|
||
useEffect(() => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !Cesium) return;
|
||
|
||
// 清理上一次叠加实体
|
||
stationOverlayIdsRef.current.forEach(id => viewer.entities.removeById(id));
|
||
stationOverlayIdsRef.current = [];
|
||
|
||
// 返航点标志图标(PinBuilder 生成,失败则退化为圆点)
|
||
if (!returnPointPinUrlRef.current && Cesium.PinBuilder) {
|
||
try {
|
||
returnPointPinUrlRef.current = Cesium.PinBuilder.fromColor(Cesium.Color.fromCssColorString('#165DFF'), 36).toDataURL();
|
||
} catch (e) { /* ignore */ }
|
||
}
|
||
(stationOverlay.returnPoints || []).forEach((pt, idx) => {
|
||
const lon = Number(pt?.position?.lng ?? pt?.lng);
|
||
const lat = Number(pt?.position?.lat ?? pt?.lat);
|
||
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
|
||
const id = `station-return-point-${idx}`;
|
||
const isHighlighted = id === highlightReturnPointId;
|
||
viewer.entities.add({
|
||
id,
|
||
returnPointData: {
|
||
alias: pt?.alias || '',
|
||
bindDeviceId: pt?.bindDeviceId || '',
|
||
},
|
||
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
|
||
...(returnPointPinUrlRef.current
|
||
? {
|
||
billboard: {
|
||
image: returnPointPinUrlRef.current,
|
||
width: isHighlighted ? 36 : 24,
|
||
height: isHighlighted ? 48 : 32,
|
||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
}
|
||
}
|
||
: {
|
||
point: {
|
||
pixelSize: isHighlighted ? 16 : 10,
|
||
color: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF'),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
}
|
||
}),
|
||
label: pt?.alias ? {
|
||
text: pt.alias,
|
||
font: 'bold 12px sans-serif',
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF').withAlpha(0.8),
|
||
pixelOffset: new Cesium.Cartesian2(0, isHighlighted ? -48 : -34),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
} : undefined,
|
||
});
|
||
stationOverlayIdsRef.current.push(id);
|
||
});
|
||
|
||
// 分区:用小框(多边形)显示
|
||
(stationOverlay.regions || []).forEach((region, idx) => {
|
||
const scope = Array.isArray(region?.scope) ? region.scope : [];
|
||
const positions = scope
|
||
.map(p => {
|
||
const lon = Number(p?.lng ?? p?.lon);
|
||
const lat = Number(p?.lat);
|
||
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return null;
|
||
return Cesium.Cartesian3.fromDegrees(lon, lat, 0);
|
||
})
|
||
.filter(Boolean);
|
||
if (positions.length < 3) return;
|
||
const id = `station-region-${region?.id ?? idx}`;
|
||
viewer.entities.add({
|
||
id,
|
||
polygon: {
|
||
hierarchy: positions,
|
||
material: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.18),
|
||
outline: true,
|
||
outlineColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.9),
|
||
height: 0,
|
||
clampToGround: true,
|
||
},
|
||
label: region?.regionName ? {
|
||
text: region.regionName,
|
||
font: '12px sans-serif',
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.8),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
} : undefined,
|
||
});
|
||
stationOverlayIdsRef.current.push(id);
|
||
});
|
||
// 障碍物点:圆心 + 半径红色圆圈
|
||
(stationOverlay.tempObstaclePoints || []).forEach((obstacle, idx) => {
|
||
const lon = Number(
|
||
obstacle?.position?.lng ?? obstacle?.position?.lon
|
||
);
|
||
const lat = Number(obstacle?.position?.lat);
|
||
const radius = Number(obstacle?.radius ?? 2);
|
||
// 形状配置:圆形走原有半径逻辑,矩形按长宽渲染
|
||
const shapeConfig = obstacleShapes?.[idx] || {};
|
||
const isRect = shapeConfig.shapeType === 'rect';
|
||
const rectWidth = Math.max(0.1, Number(shapeConfig.width) || radius * 2);
|
||
const rectHeight = Math.max(0.1, Number(shapeConfig.height) || radius * 2);
|
||
|
||
if (
|
||
!Number.isFinite(lon) ||
|
||
!Number.isFinite(lat) ||
|
||
lon === 0 ||
|
||
lat === 0 ||
|
||
!Number.isFinite(radius) ||
|
||
radius <= 0
|
||
) {
|
||
return;
|
||
}
|
||
|
||
// 每个障碍物使用稳定的实体 ID
|
||
const id = `station-obstacle-point-${idx}`;
|
||
|
||
// 判断当前障碍物是否被选中
|
||
const isHighlighted =
|
||
focusOverlay?.type === 'obstaclePoint' &&
|
||
(
|
||
String(focusOverlay.id) === String(obstacle.id) ||
|
||
String(focusOverlay.index) === String(idx)
|
||
);
|
||
|
||
const redColor = Cesium.Color.fromCssColorString(
|
||
isHighlighted ? '#FF1F1F' : '#F5222D'
|
||
);
|
||
|
||
// 圆心位置
|
||
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
|
||
|
||
viewer.entities.add({
|
||
id,
|
||
|
||
// 保存障碍物信息,方便后续识别
|
||
obstaclePointData: {
|
||
alias: obstacle?.alias || `障碍物点-${idx + 1}`,
|
||
radius,
|
||
index: idx,
|
||
},
|
||
|
||
position,
|
||
|
||
// 以经纬度位置为圆心,radius 单位为米
|
||
ellipse: isRect ? undefined : {
|
||
semiMajorAxis: new Cesium.ConstantProperty(radius),
|
||
semiMinorAxis: new Cesium.ConstantProperty(radius),
|
||
height: 0,
|
||
|
||
material: redColor.withAlpha(isHighlighted ? 0.3 : 0.18),
|
||
|
||
// 红色圆圈轮廓
|
||
outline: true,
|
||
outlineColor: redColor,
|
||
outlineWidth: isHighlighted ? 4 : 2,
|
||
|
||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||
},
|
||
|
||
// 矩形障碍物:以中心点为 center 的经纬度矩形
|
||
rectangle: isRect
|
||
? {
|
||
coordinates: getObstacleRectCoordinates(
|
||
lon,
|
||
lat,
|
||
rectWidth,
|
||
rectHeight
|
||
),
|
||
height: 0,
|
||
material: redColor.withAlpha(isHighlighted ? 0.3 : 0.18),
|
||
outline: true,
|
||
outlineColor: redColor,
|
||
outlineWidth: isHighlighted ? 4 : 2,
|
||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||
}
|
||
: undefined,
|
||
|
||
// 圆心标记
|
||
point: {
|
||
pixelSize: isHighlighted ? 12 : 9,
|
||
color: redColor,
|
||
outlineColor: Cesium.Color.WHITE,
|
||
outlineWidth: 2,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
|
||
// 名称与半径标签
|
||
label: {
|
||
text: isRect
|
||
? `${obstacle?.alias || `障碍物点-${idx + 1}`} (${rectWidth.toFixed(2)}×${rectHeight.toFixed(2)}m)`
|
||
: `${obstacle?.alias || `障碍物点-${idx + 1}`} (${radius}m)`,
|
||
font: isHighlighted ? 'bold 14px sans-serif' : '12px sans-serif',
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: redColor.withAlpha(0.85),
|
||
pixelOffset: new Cesium.Cartesian2(0, -18),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
|
||
0,
|
||
100000
|
||
),
|
||
},
|
||
});
|
||
|
||
stationOverlayIdsRef.current.push(id);
|
||
|
||
const handleId = `station-obstacle-handle-${idx}`;
|
||
|
||
viewer.entities.add({
|
||
id: handleId,
|
||
|
||
// 给鼠标事件识别手柄用
|
||
obstacleHandleData: {
|
||
index: idx,
|
||
obstacleId: obstacle?.id,
|
||
},
|
||
|
||
position: isRect
|
||
? getObstacleRectHandlePosition(lon, lat, rectWidth, rectHeight)
|
||
: getObstacleHandlePosition(lon, lat, radius),
|
||
|
||
point: {
|
||
pixelSize: isHighlighted ? 16 : 13,
|
||
color: Cesium.Color.WHITE,
|
||
outlineColor: Cesium.Color.RED,
|
||
outlineWidth: 3,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
|
||
label: {
|
||
text: '↔',
|
||
font: 'bold 12px sans-serif',
|
||
fillColor: Cesium.Color.RED,
|
||
pixelOffset: new Cesium.Cartesian2(0, -1),
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
|
||
stationOverlayIdsRef.current.push(handleId);
|
||
});
|
||
|
||
viewer.scene.requestRender();
|
||
}, [stationOverlay, highlightReturnPointId, obstacleShapeSignature]);
|
||
|
||
|
||
useEffect(() => {
|
||
const viewer = viewerRef.current;
|
||
|
||
if (!viewer || !Cesium || from != "mapEditor") return;
|
||
|
||
const handler = new Cesium.ScreenSpaceEventHandler(
|
||
viewer.scene.canvas
|
||
);
|
||
|
||
const getGroundPosition = (position) => {
|
||
const ray = viewer.camera.getPickRay(position);
|
||
if (!ray) return null;
|
||
|
||
return viewer.scene.globe.pick(ray, viewer.scene);
|
||
};
|
||
|
||
const getDistance = (center, target) => {
|
||
return Cesium.Cartesian3.distance(center, target);
|
||
};
|
||
|
||
// 鼠标按下:判断是否点中障碍物圆圈边缘
|
||
handler.setInputAction((event) => {
|
||
const viewer = viewerRef.current;
|
||
|
||
if (!viewer || !Cesium) return;
|
||
|
||
const picked = viewer.scene.pick(event.position);
|
||
const entity = picked?.id;
|
||
const handleData = entity?.obstacleHandleData?.getValue
|
||
? entity.obstacleHandleData.getValue()
|
||
: entity?.obstacleHandleData;
|
||
|
||
// 没点中手柄,不启动半径拖动
|
||
if (!handleData) return;
|
||
|
||
const index = Number(handleData.index);
|
||
const obstacles = stationOverlay.tempObstaclePoints || [];
|
||
const obstacle = obstacles[index];
|
||
|
||
if (!obstacle) return;
|
||
|
||
const lon = Number(
|
||
obstacle.position?.lng ?? obstacle.position?.lon
|
||
);
|
||
const lat = Number(obstacle.position?.lat);
|
||
const radius = Number(obstacle.radius ?? 2);
|
||
|
||
if (
|
||
!Number.isFinite(lon) ||
|
||
!Number.isFinite(lat) ||
|
||
!Number.isFinite(radius)
|
||
) {
|
||
return;
|
||
}
|
||
|
||
// 形状配置:圆形 / 矩形
|
||
const shapeConfig = obstacleShapes?.[index] || {};
|
||
const isRect = shapeConfig.shapeType === 'rect';
|
||
const rectWidth = Math.max(
|
||
0.1,
|
||
Number(shapeConfig.width) || radius * 2
|
||
);
|
||
const rectHeight = Math.max(
|
||
0.1,
|
||
Number(shapeConfig.height) || radius * 2
|
||
);
|
||
|
||
draggingObstacleRef.current = {
|
||
index,
|
||
entityId: `station-obstacle-point-${index}`,
|
||
handleId: `station-obstacle-handle-${index}`,
|
||
center: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
|
||
lon,
|
||
lat,
|
||
radius,
|
||
shapeType: isRect ? 'rect' : 'circle',
|
||
width: rectWidth,
|
||
height: rectHeight,
|
||
};
|
||
|
||
setIsDraggingObstacle(true);
|
||
|
||
// 拖动时禁用相机旋转,避免地图跟着转
|
||
viewer.scene.screenSpaceCameraController.enableRotate = false;
|
||
viewer.scene.screenSpaceCameraController.enableTranslate = false;
|
||
viewer.scene.screenSpaceCameraController.enableZoom = false;
|
||
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
|
||
|
||
// 鼠标移动:实时更新圆圈半径
|
||
//handler.setInputAction((event) => {
|
||
// const viewer = viewerRef.current;
|
||
// const Cesium = window.Cesium;
|
||
// const dragging = draggingObstacleRef.current;
|
||
|
||
// if (!viewer || !Cesium || !dragging) return;
|
||
|
||
// const camera = viewer.camera;
|
||
// const ray = camera.getPickRay(event.endPosition);
|
||
|
||
// if (!ray) return;
|
||
|
||
// // 取鼠标在地球表面的交点
|
||
// const mousePosition = viewer.scene.globe.pick(
|
||
// ray,
|
||
// viewer.scene
|
||
// );
|
||
|
||
// if (!mousePosition) return;
|
||
|
||
// // 鼠标到圆心的地表近似距离(米)
|
||
// const nextRadius = Math.max(
|
||
// 0.5,
|
||
// Cesium.Cartesian3.distance(
|
||
// dragging.center,
|
||
// mousePosition
|
||
// )
|
||
// );
|
||
|
||
// dragging.radius = nextRadius;
|
||
|
||
// const circleEntity = viewer.entities.getById(
|
||
// dragging.entityId
|
||
// );
|
||
|
||
// const handleEntity = viewer.entities.getById(
|
||
// dragging.handleId
|
||
// );
|
||
|
||
// if (circleEntity?.ellipse) {
|
||
// circleEntity.ellipse.semiMajorAxis = nextRadius;
|
||
// circleEntity.ellipse.semiMinorAxis = nextRadius;
|
||
// }
|
||
|
||
// if (handleEntity) {
|
||
// handleEntity.position = getObstacleHandlePosition(
|
||
// Cesium,
|
||
// dragging.lon,
|
||
// dragging.lat,
|
||
// nextRadius
|
||
// );
|
||
// }
|
||
|
||
// // 如需同步更新标签
|
||
// if (circleEntity?.label) {
|
||
// const obstacle =
|
||
// (stationOverlay.tempObstaclePoints || [])[dragging.index];
|
||
|
||
// circleEntity.label.text =
|
||
// `${obstacle?.alias || `障碍物点-${dragging.index + 1}`} (${nextRadius.toFixed(2)}m)`;
|
||
// }
|
||
|
||
// viewer.scene.requestRender();
|
||
//}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||
|
||
handler.setInputAction((event) => {
|
||
const viewer = viewerRef.current;
|
||
const dragging = draggingObstacleRef.current;
|
||
|
||
if (!viewer || !Cesium || !dragging) return;
|
||
|
||
const ray = viewer.camera.getPickRay(event.endPosition);
|
||
if (!ray) return;
|
||
|
||
const mousePosition = viewer.scene.globe.pick(
|
||
ray,
|
||
viewer.scene
|
||
);
|
||
if (!mousePosition) return;
|
||
|
||
// 矩形:按鼠标相对中心点的偏移计算长宽,并同步矩形与手柄
|
||
if (dragging.shapeType === 'rect') {
|
||
const carto = Cesium.Cartographic.fromCartesian(mousePosition);
|
||
if (!carto) return;
|
||
const mouseLon = Cesium.Math.toDegrees(carto.longitude);
|
||
const mouseLat = Cesium.Math.toDegrees(carto.latitude);
|
||
|
||
const width = Math.max(
|
||
0.2,
|
||
2 *
|
||
Cesium.Cartesian3.distance(
|
||
dragging.center,
|
||
Cesium.Cartesian3.fromDegrees(mouseLon, dragging.lat, 0)
|
||
)
|
||
);
|
||
const height = Math.max(
|
||
0.2,
|
||
2 *
|
||
Cesium.Cartesian3.distance(
|
||
dragging.center,
|
||
Cesium.Cartesian3.fromDegrees(dragging.lon, mouseLat, 0)
|
||
)
|
||
);
|
||
|
||
dragging.width = width;
|
||
dragging.height = height;
|
||
|
||
const rectEntity = viewer.entities.getById(dragging.entityId);
|
||
const rectHandle = viewer.entities.getById(dragging.handleId);
|
||
|
||
if (rectEntity?.rectangle) {
|
||
rectEntity.rectangle.coordinates.setValue(
|
||
getObstacleRectCoordinates(
|
||
dragging.lon,
|
||
dragging.lat,
|
||
width,
|
||
height
|
||
)
|
||
);
|
||
}
|
||
if (rectHandle) {
|
||
rectHandle.position = new Cesium.ConstantPositionProperty(
|
||
getObstacleRectHandlePosition(
|
||
dragging.lon,
|
||
dragging.lat,
|
||
width,
|
||
height
|
||
)
|
||
);
|
||
}
|
||
if (rectEntity?.label) {
|
||
const obstacle =
|
||
stationOverlay.tempObstaclePoints?.[dragging.index];
|
||
rectEntity.label.text.setValue(
|
||
`${obstacle?.alias || `障碍物点-${dragging.index + 1}`} (${width.toFixed(2)}×${height.toFixed(2)}m)`
|
||
);
|
||
}
|
||
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
|
||
// 计算鼠标到圆心的距离,单位米
|
||
const nextRadius = Math.max(
|
||
0.01,
|
||
Cesium.Cartesian3.distance(
|
||
dragging.center,
|
||
mousePosition
|
||
)
|
||
);
|
||
|
||
dragging.radius = nextRadius;
|
||
|
||
const circle = viewer.entities.getById(dragging.entityId);
|
||
const handle = viewer.entities.getById(dragging.handleId);
|
||
|
||
// 同步更新圆圈半径
|
||
if (circle?.ellipse) {
|
||
circle.ellipse.semiMajorAxis.setValue(nextRadius);
|
||
circle.ellipse.semiMinorAxis.setValue(nextRadius);
|
||
}
|
||
|
||
// 同步更新手柄位置
|
||
if (handle) {
|
||
handle.position = new Cesium.ConstantPositionProperty(
|
||
getObstacleHandlePosition(
|
||
dragging.lon,
|
||
dragging.lat,
|
||
nextRadius
|
||
)
|
||
);
|
||
}
|
||
|
||
// 同步更新圆圈标签
|
||
if (circle?.label) {
|
||
const obstacle =
|
||
stationOverlay.tempObstaclePoints?.[dragging.index];
|
||
|
||
circle.label.text.setValue(
|
||
`${obstacle?.alias || `障碍物点-${dragging.index + 1}`} (${nextRadius.toFixed(2)}m)`
|
||
);
|
||
}
|
||
|
||
viewer.scene.requestRender();
|
||
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||
|
||
// 鼠标松开:更新数据并保存
|
||
handler.setInputAction(() => {
|
||
const viewer = viewerRef.current;
|
||
const dragging = draggingObstacleRef.current;
|
||
|
||
if (!dragging) return;
|
||
|
||
const { index, radius } = dragging;
|
||
|
||
draggingObstacleRef.current = null;
|
||
setIsDraggingObstacle(false);
|
||
|
||
if (viewer) {
|
||
const ctrl = viewer.scene.screenSpaceCameraController;
|
||
ctrl.enableRotate = true;
|
||
ctrl.enableTranslate = true;
|
||
ctrl.enableZoom = true;
|
||
}
|
||
|
||
// 矩形:打印信息并回传长宽给父组件(暂不走圆形保存逻辑)
|
||
if (dragging.shapeType === 'rect') {
|
||
const obstacle =
|
||
stationOverlay.tempObstaclePoints?.[index];
|
||
const { width, height } = dragging;
|
||
|
||
logRectObstacleInfo(
|
||
obstacle,
|
||
index,
|
||
dragging.lon,
|
||
dragging.lat,
|
||
width,
|
||
height
|
||
);
|
||
|
||
onObstacleRectResize?.(
|
||
index,
|
||
Number(width.toFixed(2)),
|
||
Number(height.toFixed(2))
|
||
);
|
||
viewer?.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
// 通知父组件更新列表
|
||
onObstacleRadiusChange?.(index, radius, siteMapInfoId);
|
||
}, Cesium.ScreenSpaceEventType.LEFT_UP);
|
||
|
||
return () => {
|
||
handler.destroy();
|
||
|
||
viewer.scene.screenSpaceCameraController.enableRotate = true;
|
||
viewer.scene.screenSpaceCameraController.enableTranslate = true;
|
||
};
|
||
}, [stationOverlay]);
|
||
|
||
// 点击已配置列表:定位到对应返航点/分区;返航点额外高亮
|
||
useEffect(() => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !Cesium || !focusOverlay) return;
|
||
|
||
if (focusOverlay.type === 'returnPoint') {
|
||
const pt = (stationOverlay.returnPoints || [])[focusOverlay.index];
|
||
const lon = Number(pt?.position?.lng ?? pt?.lng);
|
||
const lat = Number(pt?.position?.lat ?? pt?.lat);
|
||
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
|
||
setLegendHighlight('returnPoint');
|
||
setHighlightReturnPointId(`station-return-point-${focusOverlay.index}`);
|
||
viewer.camera.flyTo({
|
||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 500),
|
||
duration: 0.8,
|
||
});
|
||
} else if (focusOverlay.type === 'region') {
|
||
const region = (stationOverlay.regions || []).find(r => String(r.id) === String(focusOverlay.id));
|
||
const scope = Array.isArray(region?.scope) ? region.scope : [];
|
||
const lons = scope.map(p => Number(p?.lng ?? p?.lon)).filter(n => isFinite(n) && n !== 0);
|
||
const lats = scope.map(p => Number(p?.lat)).filter(n => isFinite(n) && n !== 0);
|
||
if (!lons.length || !lats.length) return;
|
||
setLegendHighlight('region');
|
||
setHighlightReturnPointId('');
|
||
viewer.camera.flyTo({
|
||
destination: Cesium.Rectangle.fromDegrees(
|
||
Math.min(...lons), Math.min(...lats), Math.max(...lons), Math.max(...lats)
|
||
),
|
||
duration: 0.8,
|
||
});
|
||
} else if (focusOverlay.type === 'route') {
|
||
// 飞到路线的边界框
|
||
const pts = Array.isArray(focusOverlay.points) ? focusOverlay.points : [];
|
||
const lons = pts.map(p => Number(p?.lng ?? p?.lon)).filter(n => isFinite(n) && n !== 0);
|
||
const lats = pts.map(p => Number(p?.lat)).filter(n => isFinite(n) && n !== 0);
|
||
if (!lons.length || !lats.length) return;
|
||
setLegendHighlight('');
|
||
setHighlightReturnPointId('');
|
||
viewer.camera.flyTo({
|
||
destination: Cesium.Rectangle.fromDegrees(
|
||
Math.min(...lons), Math.min(...lats), Math.max(...lons), Math.max(...lats)
|
||
),
|
||
duration: 0.8,
|
||
});
|
||
} else {
|
||
const obstaclePoints = stationOverlay.tempObstaclePoints || [];
|
||
|
||
// 优先根据 index 查找;如果没有 index,再尝试根据 id 查找
|
||
const obstacleIndex = Number.isInteger(focusOverlay.index)
|
||
? focusOverlay.index
|
||
: obstaclePoints.findIndex(
|
||
(item) =>
|
||
String(item.id) === String(focusOverlay.id)
|
||
);
|
||
|
||
const obstacle = obstaclePoints[obstacleIndex];
|
||
|
||
if (!obstacle) return;
|
||
|
||
const lon = Number(
|
||
obstacle?.position?.lng ?? obstacle?.position?.lon
|
||
);
|
||
const lat = Number(obstacle?.position?.lat);
|
||
const radius = Number(obstacle?.radius ?? 2);
|
||
|
||
if (
|
||
!Number.isFinite(lon) ||
|
||
!Number.isFinite(lat) ||
|
||
lon === 0 ||
|
||
lat === 0
|
||
) {
|
||
return;
|
||
}
|
||
|
||
setLegendHighlight('obstaclePoint');
|
||
setHighlightReturnPointId('');
|
||
|
||
// 飞到障碍物圆心附近,并根据半径调整视角
|
||
viewer.camera.flyTo({
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
lon,
|
||
lat,
|
||
Math.max(50, Number.isFinite(radius) ? radius * 5 : 50)
|
||
),
|
||
duration: 0.8,
|
||
});
|
||
}
|
||
}, [focusOverlay, stationOverlay]);
|
||
|
||
useEffect(() => {
|
||
// 如果有 realtimePosition,不显示 focusEntity
|
||
const hasRealtime =
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat));
|
||
|
||
if (!viewerRef.current || !focusLocation || hasRealtime) {
|
||
if (focusEntityRef.current) {
|
||
viewerRef.current?.entities.remove(focusEntityRef.current);
|
||
focusEntityRef.current = null;
|
||
}
|
||
// 恢复被 focusEntity 隐藏的设备实体
|
||
hiddenByFocusRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = true;
|
||
if (e.label) e.label.show = true;
|
||
});
|
||
hiddenByFocusRef.current = [];
|
||
return;
|
||
}
|
||
const viewer = viewerRef.current;
|
||
|
||
// 恢复上一次被隐藏的设备实体
|
||
hiddenByFocusRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = true;
|
||
if (e.label) e.label.show = true;
|
||
});
|
||
hiddenByFocusRef.current = [];
|
||
|
||
// 选择图片
|
||
let image = carImg;
|
||
if (focusLocation.type === "plane" || focusLocation.type === "drone") {
|
||
image = planeImg;
|
||
} else if (focusLocation.type === "robot") {
|
||
image = carImg;
|
||
} else if (focusLocation.type === "mower") {
|
||
image = carImg;
|
||
}
|
||
|
||
// 如果已经有 focusEntity,先移除
|
||
if (focusEntityRef.current) {
|
||
viewer.entities.remove(focusEntityRef.current);
|
||
}
|
||
|
||
// 点击设备后仅做地图相机定位:不隐藏其他设备图标、不创建额外的 focusEntity
|
||
// 所有设备图标与光圈保持原样显示,由侧边抽屉展示详情
|
||
|
||
const lon = Number(focusLocation.lon);
|
||
const lat = Number(focusLocation.lat);
|
||
|
||
if (isValidCoordinate(lon, lat)) {
|
||
flyToView(
|
||
viewer,
|
||
FLIGHT_PRIORITY.focus,
|
||
{
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
lon,
|
||
lat,
|
||
800
|
||
),
|
||
orientation: {
|
||
heading: 0,
|
||
pitch: Cesium.Math.toRadians(-90),
|
||
roll: 0,
|
||
},
|
||
duration: 1.2,
|
||
},
|
||
`focus:${focusLocation.id ?? `${lon},${lat}`}`
|
||
);
|
||
}
|
||
}, [focusLocation]);
|
||
|
||
function flyToRobots(viewer, robots) {
|
||
if (!robots || robots.length === 0) return;
|
||
|
||
let west = 180, south = 90, east = -180, north = -90;
|
||
|
||
robots.forEach(r => {
|
||
const lon = Number(r?.lastRunningStatus?.longitude);
|
||
const lat = Number(r?.lastRunningStatus?.latitude);
|
||
|
||
west = Math.min(west, lon);
|
||
south = Math.min(south, lat);
|
||
east = Math.max(east, lon);
|
||
north = Math.max(north, lat);
|
||
});
|
||
|
||
const rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);
|
||
flyToView(viewer, FLIGHT_PRIORITY.devices, { destination: rectangle, duration: 1.5 });
|
||
}
|
||
|
||
function parseLngLat(lon, lat) {
|
||
const longitude = Number(lon);
|
||
const latitude = Number(lat);
|
||
if (Number.isFinite(longitude) && Number.isFinite(latitude)) {
|
||
return { longitude, latitude };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
|
||
// 监听 drawRealTime 变化,每次开始执行任务时重置为定位模式
|
||
useEffect(() => {
|
||
if (drawRealTime) {
|
||
// 开始执行任务时:重置为定位模式,清空之前的轨迹数据
|
||
tracePointRef.current.setMode(TPMode.LOCATION);
|
||
isNavigationModeRef.current = false;
|
||
lastFinishPointRef.current = null;
|
||
|
||
// 清空导航相关的实体
|
||
const viewer = viewerRef.current;
|
||
if (viewer) {
|
||
if (navLineRef.current) {
|
||
viewer.entities.remove(navLineRef.current);
|
||
navLineRef.current = null;
|
||
}
|
||
if (followCarEntityRef.current) {
|
||
viewer.entities.remove(followCarEntityRef.current);
|
||
followCarEntityRef.current = null;
|
||
}
|
||
viewer.scene.requestRender();
|
||
}
|
||
} else {
|
||
tracePointRef.current.setMode(TPMode.LOCATION);
|
||
isNavigationModeRef.current = false;
|
||
lastFinishPointRef.current = null;
|
||
}
|
||
|
||
}, [drawRealTime]);
|
||
|
||
// 处理完成点
|
||
//useEffect(() => {
|
||
// if (!finishPoint || !finishPoint.lng || !finishPoint.lat || !drawRealTime) {
|
||
// // 没有 finishPoint 时,移除跟随小车
|
||
// const viewer = viewerRef.current;
|
||
// if (viewer && followCarEntityRef.current) {
|
||
// viewer.entities.remove(followCarEntityRef.current);
|
||
// followCarEntityRef.current = null;
|
||
// }
|
||
// return;
|
||
// }
|
||
|
||
// const point = { lng: finishPoint.lng, lat: finishPoint.lat };
|
||
|
||
// // 如果是定位模式且还没有导航模式,则切换到导航模式
|
||
// if (!isNavigationModeRef.current && drawRealTime) {
|
||
// tracePointRef.current.setMode(TPMode.NAVIGATION);
|
||
// isNavigationModeRef.current = true;
|
||
// }
|
||
|
||
// tracePointRef.current.upsert(point, TPAction.ADD);
|
||
// lastFinishPointRef.current = finishPoint;
|
||
|
||
// // 更新轨迹绘制
|
||
// updateTraceLine();
|
||
|
||
// // 更新或添加跟随小车
|
||
//}, [finishPoint, drawRealTime]);
|
||
|
||
// 更新跟随小车
|
||
const updateFollowCar = (cartesianPos, heading = 0) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !cartesianPos) return;
|
||
|
||
const hpr = new Cesium.HeadingPitchRoll(heading, 0, 0);
|
||
const orientation = Cesium.Transforms.headingPitchRollQuaternion(cartesianPos, hpr);
|
||
|
||
if (followCarEntityRef.current) {
|
||
followCarEntityRef.current.position = cartesianPos;
|
||
followCarEntityRef.current.orientation = orientation;
|
||
} else {
|
||
followCarEntityRef.current = viewer.entities.add({
|
||
position: cartesianPos,
|
||
orientation: orientation,
|
||
billboard: {
|
||
image: carImg,
|
||
width: 30,
|
||
height: 30,
|
||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
color: Cesium.Color.YELLOW.withAlpha(0.8),
|
||
},
|
||
});
|
||
}
|
||
};
|
||
|
||
const updateTraceLine = (clear = false) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
|
||
// 主动清空 或 轨迹数据为空:统一清理
|
||
if (clear) {
|
||
tracePointRef.current.reset?.();
|
||
lastFinishPointRef.current = null;
|
||
isNavigationModeRef.current = false;
|
||
realtimeCartesianRef.current = [];
|
||
realtimeLastPointRef.current = null;
|
||
|
||
if (navLineRef.current) {
|
||
viewer.entities.remove(navLineRef.current);
|
||
navLineRef.current = null;
|
||
}
|
||
if (followCarEntityRef.current) {
|
||
viewer.entities.remove(followCarEntityRef.current);
|
||
followCarEntityRef.current = null;
|
||
}
|
||
if (realtimeLineEntityRef.current) {
|
||
viewer.entities.remove(realtimeLineEntityRef.current);
|
||
realtimeLineEntityRef.current = null;
|
||
}
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
const tracePoints = tracePointRef.current.getTracePoint();
|
||
if (!tracePoints || tracePoints.length === 0) {
|
||
if (navLineRef.current) {
|
||
viewer.entities.remove(navLineRef.current);
|
||
navLineRef.current = null;
|
||
}
|
||
if (followCarEntityRef.current) {
|
||
viewer.entities.remove(followCarEntityRef.current);
|
||
followCarEntityRef.current = null;
|
||
}
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
const validPoints = tracePoints?.filter(p => {
|
||
const lng = Number(p.lng);
|
||
const lat = Number(p.lat);
|
||
return !isNaN(lng) && !isNaN(lat) && Math.abs(lng) < 180 && Math.abs(lat) < 90 && lng !== 0 && lat !== 0;
|
||
});
|
||
|
||
if (validPoints.length === 0) {
|
||
if (followCarEntityRef.current) {
|
||
viewer.entities.remove(followCarEntityRef.current);
|
||
followCarEntityRef.current = null;
|
||
}
|
||
return;
|
||
}
|
||
|
||
const positions = validPoints.map(point =>
|
||
Cesium.Cartesian3.fromDegrees(Number(point.lng), Number(point.lat))
|
||
);
|
||
|
||
// 更新轨迹线
|
||
if (navLineRef.current) {
|
||
navLineRef.current.polyline.positions = positions;
|
||
} else {
|
||
navLineRef.current = viewer.entities.add({
|
||
polyline: {
|
||
positions: positions,
|
||
width: 2,
|
||
material: Cesium.Color.BLUE.withAlpha(0.9),
|
||
clampToGround: true,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
},
|
||
});
|
||
}
|
||
|
||
// 计算小车朝向
|
||
let heading = 0;
|
||
const lastIdx = positions.length - 1;
|
||
if (lastIdx > 0) {
|
||
const prevCart = positions[lastIdx - 1];
|
||
const currCart = positions[lastIdx];
|
||
const prevCartographic = Cesium.Cartographic.fromCartesian(prevCart);
|
||
const currCartographic = Cesium.Cartographic.fromCartesian(currCart);
|
||
|
||
const dLon = currCartographic.longitude - prevCartographic.longitude;
|
||
const dLat = currCartographic.latitude - prevCartographic.latitude;
|
||
heading = Math.atan2(dLat, dLon);
|
||
}
|
||
|
||
// 直接传 Cartesian3,无需二次转换
|
||
//updateFollowCar(positions[lastIdx], heading);
|
||
|
||
viewer.scene.requestRender();
|
||
};
|
||
// 清空规划航线(使用上一次的 ifClearPlanLine 作为比较,避免重复触发)
|
||
const prevIfClearPlanLine = useRef(0);
|
||
useEffect(() => {
|
||
if (ifClearPlanLine !== prevIfClearPlanLine.current && ifClearPlanLine) {
|
||
const viewer = viewerRef.current;
|
||
if (viewer) {
|
||
if (planLineRef.current) {
|
||
viewer.entities.remove(planLineRef.current);
|
||
|
||
planLineRef.current = null;
|
||
}
|
||
|
||
if (polygonRef.current) {
|
||
viewer.entities.remove(polygonRef.current);
|
||
|
||
polygonRef.current = null;
|
||
}
|
||
viewer.scene.requestRender();
|
||
}
|
||
prevIfClearPlanLine.current = ifClearPlanLine;
|
||
}
|
||
}, [ifClearPlanLine]);
|
||
|
||
// 清空实时轨迹
|
||
const prevIfClearNavLine = useRef(0);
|
||
useEffect(() => {
|
||
if (ifClearNavLine !== prevIfClearNavLine.current && ifClearNavLine) {
|
||
updateTraceLine(true);
|
||
prevIfClearNavLine.current = ifClearNavLine;
|
||
}
|
||
}, [ifClearNavLine]);
|
||
|
||
// 兼容旧 ifClear:同时清空两类
|
||
useEffect(() => {
|
||
if (ifClear) {
|
||
const viewer = viewerRef.current;
|
||
if (viewer) {
|
||
if (planLineRef.current) {
|
||
viewer.entities.remove(planLineRef.current);
|
||
planLineRef.current = null;
|
||
}
|
||
updateTraceLine(true);
|
||
}
|
||
}
|
||
}, [ifClear])
|
||
function isValidCoordinate(lon, lat) {
|
||
const longitude = Number(lon);
|
||
const latitude = Number(lat);
|
||
|
||
return (
|
||
lon != null &&
|
||
lat != null &&
|
||
Number.isFinite(longitude) &&
|
||
Number.isFinite(latitude) &&
|
||
Math.abs(longitude) <= 180 &&
|
||
Math.abs(latitude) <= 90 &&
|
||
!(longitude === 0 && latitude === 0)
|
||
);
|
||
}
|
||
|
||
useEffect(() => {
|
||
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !Cesium) return;
|
||
|
||
|
||
const isRealtimeMode =
|
||
realtimePosition?.lon &&
|
||
realtimePosition?.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat));
|
||
|
||
const nextIds = new Set();
|
||
|
||
const validPositions = [];
|
||
|
||
devices.forEach((device, index) => {
|
||
|
||
const raw = device?.locationMessage || device?.lastRunningStatus || {};
|
||
const parsed = parseLngLat(raw.longitude, raw.latitude);
|
||
if (!parsed) return;
|
||
|
||
const { longitude, latitude } = parsed;
|
||
|
||
validPositions.push({ lon: longitude, lat: latitude });
|
||
|
||
const id = getRobotEntityId(device, index);
|
||
nextIds.add(id);
|
||
|
||
const isIOT = device.from == "IOT";
|
||
|
||
const position = Cesium.Cartesian3.fromDegrees(
|
||
longitude,
|
||
latitude,
|
||
1
|
||
);
|
||
|
||
// ==============================
|
||
// 图标选择
|
||
// ==============================
|
||
|
||
let image = carImg;
|
||
let width = 30;
|
||
let height = 30;
|
||
const carsize = device?.productId == 138 ? 30 : 30;
|
||
|
||
if (isIOT) {
|
||
|
||
image = device?.type === "camera" ? cameraImg : iotImg;
|
||
|
||
width = device?.type === "camera" ? 40 : 20;
|
||
height = device?.type === "camera" ? 40 : 20;
|
||
|
||
} else {
|
||
|
||
image =
|
||
device?.type === "plane" ? planeImg : // 飞机
|
||
device?.type === "drone" ? planeImg : // 无人机
|
||
device?.type === "mower" ? carImg : // 割草
|
||
device?.type === "robot" ? droneInspectImg : // 巡检
|
||
carImg; // 默认车
|
||
|
||
width =
|
||
device?.type === "plane" ||
|
||
device?.type === "drone" ||
|
||
device?.type === "drone-inspect"
|
||
? 30
|
||
: carsize;
|
||
|
||
height =
|
||
device?.type === "plane" ||
|
||
device?.type === "drone" ||
|
||
device?.type === "drone-inspect"
|
||
? 30
|
||
: carsize;
|
||
|
||
}
|
||
|
||
// ==============================
|
||
// 航向角:优先用设备自带 heading/yaw/angle,否则按设备索引模拟角度(演示旋转)
|
||
// ==============================
|
||
|
||
//let headingDeg = Number(device?.heading ?? device?.yaw ?? device?.headingAngle ?? device?.angle);
|
||
//if (!isFinite(headingDeg)) {
|
||
// headingDeg = (index * 36) % 360;
|
||
//}
|
||
//const headingRotation = Cesium.Math.toRadians(-10);
|
||
|
||
// entity 获取 / 创建
|
||
// ==============================
|
||
|
||
// 光圈颜色:工作中蓝 / 空闲绿 / 离线红
|
||
|
||
let entity = entityMapRef.current.get(id);
|
||
|
||
if (!entity) {
|
||
|
||
entity = viewer.entities.add({
|
||
id,
|
||
position,
|
||
billboard: {
|
||
image,
|
||
width,
|
||
height,
|
||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
show: !isIOT,
|
||
},
|
||
|
||
//point: {
|
||
// pixelSize: 12,
|
||
// color: createGlowBlinkColor("", "", "", Cesium.Color.BLACK), // 绑定到颜色
|
||
// outlineColor: Cesium.Color.WHITE,
|
||
// outlineWidth: 2
|
||
//},
|
||
|
||
label: {
|
||
text: device.name || "",
|
||
font: "12px sans-serif",
|
||
pixelOffset: new Cesium.Cartesian2(0, -40),
|
||
fillColor: Cesium.Color.WHITE,
|
||
showBackground: true,
|
||
backgroundColor: Cesium.Color.BLACK.withAlpha(0.6),
|
||
},
|
||
properties: {
|
||
robot: device,
|
||
},
|
||
});
|
||
|
||
// ==============================
|
||
// 设备底部状态光晕:比机器稍大一点
|
||
// ==============================
|
||
const haloId = `${id}_halo`;
|
||
|
||
const haloColor = getDeviceHaloColor(device);
|
||
|
||
// 尺寸可根据设备类型微调:车辆类稍大,IOT/相机类稍小
|
||
let haloSize = 0.8;
|
||
if (isIOT) {
|
||
haloSize = device?.type === "camera" ? 0.8 : 0.8;
|
||
} else if (
|
||
device?.type === "plane" ||
|
||
device?.type === "drone" ||
|
||
device?.type === "drone-inspect"
|
||
) {
|
||
haloSize = 0.1;
|
||
} else {
|
||
haloSize = 0.8;
|
||
}
|
||
|
||
ensureRealtimeHalo(viewer, position, haloColor, 100, haloId);
|
||
|
||
entityMapRef.current.set(id, entity);
|
||
|
||
} else {
|
||
|
||
entity.position = position;
|
||
entity.billboard.image = image;
|
||
entity.billboard.width = width;
|
||
entity.billboard.height = height;
|
||
entity.label.text = device.name || "";
|
||
entity.properties.robot = device;
|
||
|
||
// 同步更新底部光晕位置与颜色
|
||
const haloId = `${id}_halo`;
|
||
const haloColor = getDeviceHaloColor(device);
|
||
|
||
if (isRealtimeMode) {
|
||
// 一机一光圈:实时模式下移除设备光圈,避免原位置残留
|
||
viewer.entities.removeById(haloId);
|
||
for (let hi = 0; hi < 3; hi++) {
|
||
viewer.entities.removeById(`${haloId}_${hi}`);
|
||
}
|
||
} else {
|
||
let haloSize = 40;
|
||
|
||
if (isIOT) {
|
||
haloSize = device?.type === "camera" ? 35 : 28;
|
||
} else if (
|
||
device?.type === "plane" ||
|
||
device?.type === "drone" ||
|
||
device?.type === "drone-inspect"
|
||
) {
|
||
haloSize = 42;
|
||
} else {
|
||
haloSize = 38;
|
||
}
|
||
ensureRealtimeHalo(viewer, position, haloColor, haloSize, haloId);
|
||
|
||
//ensureRealtimeHalo·entity(viewer, haloId, position, haloColor, haloSize);
|
||
|
||
//createDeviceHaloEntity(viewer, haloId, position, haloColor, haloSize);
|
||
}
|
||
|
||
}
|
||
|
||
});
|
||
|
||
// ==============================
|
||
// 删除不存在设备
|
||
// ==============================
|
||
|
||
entityMapRef.current.forEach((entity, id) => {
|
||
if (!nextIds.has(id)) {
|
||
viewer.entities.remove(entity);
|
||
entityMapRef.current.delete(id);
|
||
|
||
viewer.entities.removeById(`${id}_halo`);
|
||
for (let ri = 0; ri < 3; ri++) {
|
||
viewer.entities.removeById(`${id}_halo_${ri}`);
|
||
}
|
||
}
|
||
});
|
||
|
||
// ==============================
|
||
// 请求渲染
|
||
// ==============================
|
||
|
||
viewer.scene.requestRender();
|
||
|
||
// 鼠标停在设备上时,设备状态变化立即刷新 tooltip(无需移动鼠标)
|
||
if (lastHoverPositionRef.current && tooltipRef.current && tooltipRef.current.style.display === "block") {
|
||
const hoverPos = lastHoverPositionRef.current;
|
||
const pickedNow = viewer.scene.pick(hoverPos);
|
||
const pickedReturnPointNow = (Cesium.defined(pickedNow) && pickedNow.id?.returnPointData) ? pickedNow.id.returnPointData : null;
|
||
const pickedRobotNow = (Cesium.defined(pickedNow) && pickedNow.id?.properties?.robot) ? pickedNow.id.properties.robot.getValue() : null;
|
||
if (pickedReturnPointNow) {
|
||
showReturnPointTooltip(tooltipRef.current, hoverPos, pickedReturnPointNow);
|
||
} else if (pickedRobotNow) {
|
||
const hoverLngLat = getCursorLngLat(viewer, hoverPos);
|
||
showCoordinateTooltip(tooltipRef.current, hoverPos, t, hoverLngLat.lon, hoverLngLat.lat, pickedRobotNow);
|
||
}
|
||
}
|
||
|
||
// ==============================
|
||
// 首屏:仅第一次根据 devices 自动定位视野;之后 devices 实时更新不再飞行
|
||
//if (!hasInitialDevicesFlyRef.current && !isRealtimeMode && validPositions.length > 0) {
|
||
// let started = false;
|
||
// if (validPositions.length === 1) {
|
||
// const p = validPositions[0];
|
||
// started = flyToView(viewer, FLIGHT_PRIORITY.devices, {
|
||
// destination: Cesium.Cartesian3.fromDegrees(p.lon, p.lat, 800),
|
||
// duration: 1.2,
|
||
// }, `devices-init:${p.lon.toFixed(5)},${p.lat.toFixed(5)}`);
|
||
// } else {
|
||
// let minLon = 180, maxLon = -180, minLat = 90, maxLat = -90;
|
||
// validPositions.forEach(p => {
|
||
// minLon = Math.min(minLon, p.lon);
|
||
// maxLon = Math.max(maxLon, p.lon);
|
||
// minLat = Math.min(minLat, p.lat);
|
||
// maxLat = Math.max(maxLat, p.lat);
|
||
// });
|
||
// // 所有点重合时补一点边距,避免 Rectangle 面积为 0
|
||
// const pad = 0.0008;
|
||
// if (maxLon - minLon < pad) { minLon -= pad; maxLon += pad; }
|
||
// if (maxLat - minLat < pad) { minLat -= pad; maxLat += pad; }
|
||
// const rectangle = Cesium.Rectangle.fromDegrees(minLon, minLat, maxLon, maxLat);
|
||
// started = flyToView(viewer, FLIGHT_PRIORITY.devices, { destination: rectangle, duration: 1.2 }, 'devices-init:all');
|
||
// }
|
||
// if (started) hasInitialDevicesFlyRef.current = true;
|
||
//}
|
||
// ==============================
|
||
// 自动 flyTo(已停用:改为仅首屏按 devices 定位一次)
|
||
// ==============================
|
||
// 自动 flyTo
|
||
//const hasRealtime = isValidCoordinate(
|
||
// realtimePosition?.lon,
|
||
// realtimePosition?.lat
|
||
//);
|
||
|
||
//if (!hasRealtime && validPositions.length > 0) {
|
||
|
||
// let minLon = 180,
|
||
// maxLon = -180,
|
||
// minLat = 90,
|
||
// maxLat = -90;
|
||
|
||
// validPositions.forEach(p => {
|
||
|
||
// minLon = Math.min(minLon, p.lon);
|
||
// maxLon = Math.max(maxLon, p.lon);
|
||
// minLat = Math.min(minLat, p.lat);
|
||
// maxLat = Math.max(maxLat, p.lat);
|
||
|
||
// });
|
||
// if (getCameraMode() !== "devices") return;
|
||
|
||
// if (validPositions.length === 1) {
|
||
|
||
// const p = validPositions[0];
|
||
|
||
// flyToView(viewer, FLIGHT_PRIORITY.devices, {
|
||
// destination: Cesium.Cartesian3.fromDegrees(
|
||
// p.lon,
|
||
// p.lat,
|
||
// 800
|
||
// ),
|
||
// duration: 1.2
|
||
// });
|
||
|
||
// } else {
|
||
|
||
// const rectangle = Cesium.Rectangle.fromDegrees(
|
||
// minLon,
|
||
// minLat,
|
||
// maxLon,
|
||
// maxLat
|
||
// );
|
||
|
||
// flyToView(viewer, FLIGHT_PRIORITY.devices, {
|
||
// destination: rectangle,
|
||
// duration: 1.2
|
||
// });
|
||
|
||
// }
|
||
|
||
//}
|
||
|
||
}, [devices, realtimePosition]);
|
||
|
||
useEffect(() => {
|
||
if (!viewerRef.current || pathPoints.length < 2) return;
|
||
const viewer = viewerRef.current;
|
||
movingPathRef.current = [...points];
|
||
movingIndexRef.current = 0;
|
||
isMovingRef.current = true;
|
||
|
||
let targetEntity = null;
|
||
for (let [id, ent] of entityMapRef.current) {
|
||
targetEntity = ent;
|
||
break;
|
||
}
|
||
if (!targetEntity) return;
|
||
movingEntityRef.current = targetEntity;
|
||
|
||
const animateMove = () => {
|
||
if (!isMovingRef.current) return;
|
||
const path = movingPathRef.current;
|
||
const idx = movingIndexRef.current;
|
||
if (idx >= path.length - 1) {
|
||
isMovingRef.current = false;
|
||
return;
|
||
}
|
||
const p1 = path[idx];
|
||
const p2 = path[idx + 1];
|
||
const step = moveSpeedRef.current;
|
||
const lon = p1.lon + (p2.lon - p1.lon) * step;
|
||
const lat = p1.lat + (p2.lat - p1.lat) * step;
|
||
const newPos = Cesium.Cartesian3.fromDegrees(lon, lat, 1);
|
||
targetEntity.position = newPos;
|
||
|
||
// 背景光圈跟随机器一起移动
|
||
const movingHaloId = `${targetEntity.id}_halo`;
|
||
const movingHalo = viewer.entities.getById(movingHaloId);
|
||
if (movingHalo) {
|
||
movingHalo.position = newPos;
|
||
for (let hi = 0; hi < 3; hi++) {
|
||
const mRing = viewer.entities.getById(`${movingHaloId}_${hi}`);
|
||
if (mRing) mRing.position = newPos;
|
||
}
|
||
}
|
||
|
||
const heading = Math.atan2(p2.lat - p1.lat, p2.lon - p1.lon);
|
||
targetEntity.orientation = Cesium.Transforms.headingPitchRollQuaternion(
|
||
newPos,
|
||
new Cesium.HeadingPitchRoll(heading, 0, 0)
|
||
);
|
||
const distance = Math.hypot(lon - p2.lon, lat - p2.lat);
|
||
if (distance < 0.00005) {
|
||
movingIndexRef.current += 1;
|
||
}
|
||
viewer.scene.requestRender();
|
||
requestAnimationFrame(animateMove);
|
||
};
|
||
animateMove();
|
||
return () => {
|
||
isMovingRef.current = false;
|
||
};
|
||
}, [points]);
|
||
|
||
// 每次渲染都更新回调引用,确保单击处理器用最新版本(避免闭包滞后)
|
||
onMarkPointRef.current = onMarkPoint;
|
||
onCameraClickRef.current = onCameraClick;
|
||
|
||
useEffect(() => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) return;
|
||
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||
eventHandlerRef.current = handler;
|
||
|
||
handler.setInputAction((movement) => {
|
||
const picked = viewer.scene.pick(movement.endPosition);
|
||
const pickedReturnPoint = (Cesium.defined(picked) && picked.id?.returnPointData) ? picked.id.returnPointData : null;
|
||
const pickedRobot = (Cesium.defined(picked) && picked.id?.properties?.robot) ? picked.id.properties.robot.getValue() : null;
|
||
|
||
// 返航点优先显示「别名 + 绑定机器」,设备显示设备信息,空白区域隐藏
|
||
if (pickedReturnPoint) {
|
||
showReturnPointTooltip(tooltipRef.current, movement.endPosition, pickedReturnPoint);
|
||
} else if (pickedRobot) {
|
||
const { lon, lat } = getCursorLngLat(viewer, movement.endPosition);
|
||
showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, lon, lat, pickedRobot);
|
||
} else {
|
||
lastHoverPositionRef.current = null;
|
||
tooltipRef.current.style.display = "none";
|
||
}
|
||
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||
|
||
handler.setInputAction((movement) => {
|
||
// ========= 增加防护,直接拦截 movement.position undefined =========
|
||
if (!movement || !movement.position) return;
|
||
|
||
const picked = viewer.scene.pick(movement.position);
|
||
let robot = null;
|
||
//if (Cesium.defined(picked) && picked.id) {
|
||
// const robotProp = picked.id.properties?.robot;
|
||
// robot = robotProp ? (typeof robotProp.getValue === "function" ? robotProp.getValue() : robotProp) : (picked.id.robotData || null);
|
||
// if (!robot) {
|
||
// const pickedCarto = viewer.scene.globe.pick(movement.position, viewer.scene);
|
||
// if (Cesium.defined(pickedCarto)) {
|
||
// const clon = Cesium.Math.toDegrees(pickedCarto.longitude);
|
||
// const clat = Cesium.Math.toDegrees(pickedCarto.latitude);
|
||
// let best = null;
|
||
// let bestDist = 0.002;
|
||
// devices.forEach(d => {
|
||
// const raw = d?.locationMessage || d?.lastRunningStatus || {};
|
||
// const dlon = Number(raw.longitude);
|
||
// const dlat = Number(raw.latitude);
|
||
// if (!isFinite(dlon) || !isFinite(dlat)) return;
|
||
// const dist = Math.hypot(dlon - clon, dlat - clat);
|
||
// if (dist < bestDist) { bestDist = dist; best = d; }
|
||
// });
|
||
// robot = best;
|
||
// }
|
||
// }
|
||
//}
|
||
if (robot) {
|
||
onCameraClickRef.current?.(robot);
|
||
}
|
||
const _allowedFrom = ["mapEditor"];
|
||
if (!_allowedFrom.includes(from))
|
||
return;
|
||
const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
|
||
if (!cartesian) return;
|
||
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
|
||
const lon = Cesium.Math.toDegrees(cartographic.longitude);
|
||
const lat = Cesium.Math.toDegrees(cartographic.latitude);
|
||
onMarkPointRef.current?.({ lon, lat });
|
||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||
|
||
if (onClearDraw) {
|
||
onClearDraw(clearDrawingPath);
|
||
}
|
||
|
||
return () => {
|
||
handler.destroy();
|
||
};
|
||
}, [drawPoints, from, devices]);
|
||
|
||
//useEffect(() => {
|
||
// const viewer = viewerRef.current;
|
||
// if (!viewer) return;
|
||
// const tick = viewer.clock.onTick.addEventListener(() => {
|
||
// viewer.scene.requestRender();
|
||
// });
|
||
// return () => {
|
||
// viewer.clock.onTick.removeEventListener(tick);
|
||
// };
|
||
//}, []);
|
||
|
||
function createYellowCircleCanvas(size = 40) {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size; canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
const r = size / 2;
|
||
ctx.beginPath();
|
||
ctx.arc(r, r, r, 0, Math.PI * 2);
|
||
ctx.fillStyle = "#facc15";
|
||
ctx.fill();
|
||
return canvas;
|
||
}
|
||
|
||
// ======================
|
||
// ✅ 永久不闪烁 · 实时轨迹终极版
|
||
// ======================
|
||
|
||
useEffect(() => {
|
||
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !Cesium) return;
|
||
|
||
|
||
viewer.scene.requestRender();
|
||
|
||
// =============================
|
||
// 判断是否是无人机模式
|
||
// =============================
|
||
const isDroneMode = realtimeType === 'plane' || realtimeType === 'drone' || devices.some(d => d.type === 'plane' || d.type === 'drone');
|
||
|
||
// =============================
|
||
// 判断实时数据是否合法
|
||
// =============================
|
||
|
||
const hasRealtime =
|
||
realtimePosition &&
|
||
realtimePosition.lon &&
|
||
realtimePosition.lat &&
|
||
!isNaN(Number(realtimePosition.lon)) &&
|
||
!isNaN(Number(realtimePosition.lat));
|
||
|
||
// ====================================
|
||
// 情况1:没有实时数据 -> 清理所有 realtime
|
||
// ====================================
|
||
|
||
if (!hasRealtime) {
|
||
|
||
if (realtimeCarEntityRef.current) {
|
||
viewer.entities.remove(realtimeCarEntityRef.current);
|
||
realtimeCarEntityRef.current = null;
|
||
}
|
||
|
||
// 移除实时轨迹线
|
||
if (realtimeLineEntityRef.current) {
|
||
viewer.entities.remove(realtimeLineEntityRef.current);
|
||
realtimeLineEntityRef.current = null;
|
||
}
|
||
|
||
realtimeCartesianRef.current = [];
|
||
realtimeLastPointRef.current = null;
|
||
realtimeHiddenRef.current = false;
|
||
hasFlownRef.current = false;
|
||
resetFlightPriority();
|
||
|
||
// 恢复所有设备显示
|
||
entityMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = true;
|
||
if (e.point) e.point.show = true;
|
||
if (e.label) e.label.show = true; // ✅ 恢复 label
|
||
});
|
||
|
||
entityMapRef.current.forEach((entity, id) => {
|
||
const haloId = `${id}_halo`;
|
||
const haloEntity = viewer.entities.getById(haloId);
|
||
if (haloEntity) {
|
||
haloEntity.show = true;
|
||
|
||
for (let i = 0; i < 3; i++) {
|
||
const ring = viewer.entities.getById(
|
||
`${haloId}_${i}`
|
||
);
|
||
|
||
if (ring) {
|
||
ring.show = true;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
alarmMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = true;
|
||
if (e.point) e.point.show = true;
|
||
if (e.label) e.label.show = true; // ✅ 恢复 label
|
||
});
|
||
|
||
iotMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = true;
|
||
if (e.point) e.point.show = true;
|
||
if (e.label) e.label.show = true; // ✅ 恢复 label
|
||
});
|
||
|
||
removeRealtimeHalo(viewer);
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
// ====================================
|
||
// 情况2:有实时数据 -> 隐藏 focusEntity
|
||
// ====================================
|
||
if (focusEntityRef.current) {
|
||
viewer.entities.remove(focusEntityRef.current);
|
||
focusEntityRef.current = null;
|
||
}
|
||
|
||
// ====================================
|
||
// 解析实时坐标
|
||
// ====================================
|
||
entityMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
if (e.label) e.label.show = false; // ✅ 同时隐藏 label,避免残留
|
||
});
|
||
|
||
// 隐藏设备底部光晕
|
||
entityMapRef.current.forEach((entity, id) => {
|
||
const haloId = `${id}_halo`;
|
||
const haloEntity = viewer.entities.getById(haloId);
|
||
if (haloEntity) {
|
||
haloEntity.show = false;
|
||
|
||
for (let i = 0; i < 3; i++) {
|
||
const ring = viewer.entities.getById(
|
||
`${haloId}_${i}`
|
||
);
|
||
|
||
if (ring) {
|
||
ring.show = false;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
alarmMapRef.current.forEach((entity) => {
|
||
if (entity.billboard) entity.billboard.show = false;
|
||
if (entity.point) entity.point.show = false;
|
||
if (entity.label) entity.label.show = false; // ✅ 隐藏 label
|
||
});
|
||
iotMapRef.current.forEach((entity) => {
|
||
if (entity.billboard) entity.billboard.show = false;
|
||
if (entity.point) entity.point.show = false;
|
||
if (entity.label) entity.label.show = false; // ✅ 隐藏 label
|
||
});
|
||
|
||
const rawLon = realtimePosition?.lon;
|
||
const rawLat = realtimePosition?.lat;
|
||
|
||
const lon = Number(rawLon);
|
||
const lat = Number(rawLat);
|
||
|
||
// 实时坐标缺失或无效时,不绘制、不追加轨迹点
|
||
if (
|
||
rawLon == null ||
|
||
rawLat == null ||
|
||
!Number.isFinite(lon) ||
|
||
!Number.isFinite(lat) ||
|
||
lon < -180 ||
|
||
lon > 180 ||
|
||
lat < -90 ||
|
||
lat > 90 ||
|
||
(lon === 0 && lat === 0)
|
||
) {
|
||
return;
|
||
}
|
||
|
||
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1);
|
||
|
||
// 实时光圈颜色:优先取设备状态色,缺省蓝色(工作)
|
||
const rtHaloColor = devices?.[0] ? getDeviceHaloColor(devices[0]) : Cesium.Color.fromCssColorString('#1677ff');
|
||
|
||
// ====================================
|
||
// 无人机模式:保持原来的逻辑
|
||
// ====================================
|
||
if (isDroneMode || from == "deviceStatus" || from == "devicesTask") {
|
||
// 轨迹点去抖动(防止重复点)
|
||
// 实时轨迹过滤:重复点不添加,异常跳点不连接
|
||
const last = realtimeLastPointRef.current;
|
||
let shouldAdd = true;
|
||
|
||
if (last) {
|
||
const toRad = (deg) => (deg * Math.PI) / 180;
|
||
const R = 6371000; // 地球半径,米
|
||
|
||
const dLat = toRad(lat - last.lat);
|
||
const dLon = toRad(lon - last.lon);
|
||
const lat1 = toRad(last.lat);
|
||
const lat2 = toRad(lat);
|
||
|
||
const a =
|
||
Math.sin(dLat / 2) ** 2 +
|
||
Math.cos(lat1) *
|
||
Math.cos(lat2) *
|
||
Math.sin(dLon / 2) ** 2;
|
||
|
||
const distance = 2 * R * Math.atan2(
|
||
Math.sqrt(a),
|
||
Math.sqrt(1 - a)
|
||
);
|
||
|
||
// 重复点不添加
|
||
if (distance < 0.001) {
|
||
shouldAdd = false;
|
||
}
|
||
|
||
// 单次位置跳变超过 2 米,视为异常点,不连线
|
||
if (distance > 2) {
|
||
shouldAdd = false;
|
||
}
|
||
}
|
||
|
||
if (shouldAdd && drawRealTime) {
|
||
realtimeLastPointRef.current = { lon, lat };
|
||
|
||
realtimeCartesianRef.current.push(
|
||
Cesium.Cartesian3.fromDegrees(lon, lat, 1)
|
||
);
|
||
}
|
||
// 第一次进入 realtime -> 隐藏所有设备
|
||
if (!realtimeHiddenRef.current) {
|
||
realtimeHiddenRef.current = true;
|
||
|
||
entityMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
// 隐藏设备底部光晕
|
||
entityMapRef.current.forEach((entity, id) => {
|
||
const haloId = `${id}_halo`;
|
||
const haloEntity = viewer.entities.getById(haloId);
|
||
if (haloEntity) {
|
||
haloEntity.show = false;
|
||
|
||
for (let i = 0; i < 3; i++) {
|
||
const ring = viewer.entities.getById(
|
||
`${haloId}_${i}`
|
||
);
|
||
|
||
if (ring) {
|
||
ring.show = false;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
alarmMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
|
||
iotMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
}
|
||
|
||
// 无人机图标
|
||
const img = realtimeType === 'plane' || realtimeType === 'drone' ? planeImg : carImg;
|
||
const imgWidth = 30;
|
||
const imgHeight = 30;
|
||
|
||
// 如果有航向角,设置旋转
|
||
let rotation = 0;
|
||
|
||
if (realtimePosition?.heading !== undefined && !isNaN(Number(realtimePosition.heading))) {
|
||
let headingDeg = Number(realtimePosition.heading);
|
||
|
||
rotation = Cesium.Math.toRadians(-headingDeg);
|
||
|
||
}
|
||
|
||
if (!realtimeCarEntityRef.current) {
|
||
realtimeCarEntityRef.current = viewer.entities.add({
|
||
position: position,
|
||
billboard: {
|
||
image: img,
|
||
width: imgWidth,
|
||
height: imgHeight,
|
||
verticalOrigin: Cesium.VerticalOrigin.CENTER,
|
||
rotation: rotation,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
}
|
||
});
|
||
} else {
|
||
realtimeCarEntityRef.current.position = position;
|
||
realtimeCarEntityRef.current.billboard.image = img;
|
||
realtimeCarEntityRef.current.billboard.width = imgWidth;
|
||
realtimeCarEntityRef.current.billboard.height = imgHeight;
|
||
realtimeCarEntityRef.current.billboard.rotation = rotation;
|
||
|
||
// 实时光圈跟随机器移动,原光随动不残留
|
||
ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
|
||
}
|
||
|
||
// 无人机模式的实时轨迹线
|
||
if (drawRealTime) {
|
||
if (realtimeLineEntityRef.current) {
|
||
// 已存在,CallbackProperty 会自动更新
|
||
} else {
|
||
const callbackPositions = new Cesium.CallbackProperty(() => {
|
||
return realtimeCartesianRef.current;
|
||
}, false);
|
||
|
||
realtimeLineEntityRef.current = viewer.entities.add({
|
||
polyline: {
|
||
positions: callbackPositions,
|
||
width: 5,
|
||
material: new Cesium.PolylineGlowMaterialProperty({
|
||
glowPower: 0.25,
|
||
color: Cesium?.Color.LIME
|
||
}),
|
||
// ✅ 取消贴地,和机器图标保持 1 米同高度,放大后轨迹中心与机器中心完全重合
|
||
clampToGround: false,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
||
}
|
||
});
|
||
}
|
||
} else {
|
||
// 不绘制实时轨迹,移除线
|
||
if (realtimeLineEntityRef.current) {
|
||
viewer.entities.remove(realtimeLineEntityRef.current);
|
||
realtimeLineEntityRef.current = null;
|
||
}
|
||
realtimeCartesianRef.current = [];
|
||
}
|
||
|
||
// 无人机模式不需要完成点逻辑,直接返回
|
||
if (!hasFlownRef.current) {
|
||
hasFlownRef.current = true;
|
||
if (getCameraMode() !== "realtime") return;
|
||
|
||
flyToView(viewer, FLIGHT_PRIORITY.realtime, {
|
||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 30),
|
||
orientation: {
|
||
heading: 0,
|
||
pitch: Cesium.Math.toRadians(-90),
|
||
roll: 0
|
||
},
|
||
duration: 1.2
|
||
});
|
||
}
|
||
|
||
viewer.scene.requestRender();
|
||
return;
|
||
}
|
||
|
||
// ====================================
|
||
// 机器人模式:使用 TracePoint 逻辑
|
||
// ====================================
|
||
const point = { lng: lon, lat: lat };
|
||
|
||
// 如果是定位模式且 drawRealTime 为 false,保持定位模式
|
||
if (!drawRealTime) {
|
||
tracePointRef.current.setMode(TPMode.LOCATION);
|
||
isNavigationModeRef.current = false;
|
||
}
|
||
|
||
// 更新当前点
|
||
tracePointRef.current.upsert(point, TPAction.UPDATE);
|
||
|
||
// 更新轨迹绘制
|
||
updateTraceLine();
|
||
|
||
// 第一次进入 realtime -> 隐藏所有设备
|
||
if (!realtimeHiddenRef.current) {
|
||
|
||
realtimeHiddenRef.current = true;
|
||
|
||
entityMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
|
||
// 隐藏设备底部光晕
|
||
entityMapRef.current.forEach((entity, id) => {
|
||
const haloId = `${id}_halo`;
|
||
const haloEntity = viewer.entities.getById(haloId);
|
||
if (haloEntity) {
|
||
haloEntity.show = false;
|
||
|
||
for (let i = 0; i < 3; i++) {
|
||
const ring = viewer.entities.getById(
|
||
`${haloId}_${i}`
|
||
);
|
||
|
||
if (ring) {
|
||
ring.show = false;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
alarmMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
|
||
iotMapRef.current.forEach(e => {
|
||
if (e.billboard) e.billboard.show = false;
|
||
if (e.point) e.point.show = false;
|
||
});
|
||
|
||
}
|
||
|
||
// 机器人图标
|
||
const img = carImg;
|
||
const imgWidth = 30;
|
||
const imgHeight = 30;
|
||
|
||
// 如果有航向角,设置旋转
|
||
let rotation = 0;
|
||
|
||
if (realtimePosition?.heading !== undefined && !isNaN(Number(realtimePosition.heading))) {
|
||
let headingDeg = Number(realtimePosition.heading);
|
||
|
||
rotation = Cesium.Math.toRadians(headingDeg);
|
||
}
|
||
if (!realtimeCarEntityRef.current) {
|
||
realtimeCarEntityRef.current = viewer.entities.add({
|
||
position: position,
|
||
billboard: {
|
||
image: img,
|
||
width: imgWidth,
|
||
height: imgHeight,
|
||
verticalOrigin: Cesium.VerticalOrigin.CENTER,
|
||
rotation: rotation,
|
||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||
}
|
||
});
|
||
} else {
|
||
realtimeCarEntityRef.current.position = position;
|
||
realtimeCarEntityRef.current.billboard.image = img;
|
||
realtimeCarEntityRef.current.billboard.width = imgWidth;
|
||
realtimeCarEntityRef.current.billboard.height = imgHeight;
|
||
realtimeCarEntityRef.current.billboard.rotation = rotation;
|
||
|
||
// 实时光圈跟随机器移动,原光随动不残留
|
||
ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
|
||
}
|
||
|
||
// 机器人模式只在导航模式下显示额外的实时轨迹线
|
||
if (drawRealTime && isNavigationModeRef.current) {
|
||
// 轨迹点去抖动(防止重复点)
|
||
const last = realtimeLastPointRef.current;
|
||
let shouldAdd = true;
|
||
|
||
if (last) {
|
||
const dx = last.lon - lon;
|
||
const dy = last.lat - lat;
|
||
const dist = Math.sqrt(dx * dx + dy * dy);
|
||
//if (dist < 0.0000001) {
|
||
// shouldAdd = false;
|
||
//}
|
||
}
|
||
|
||
//if (shouldAdd) {
|
||
// realtimeLastPointRef.current = { lon, lat };
|
||
// realtimeCartesianRef.current.push(
|
||
// Cesium.Cartesian3.fromDegrees(lon, lat)
|
||
// );
|
||
//}
|
||
|
||
//if (realtimeLineEntityRef.current) {
|
||
// // 已存在,CallbackProperty 会自动更新
|
||
//} else {
|
||
// const callbackPositions = new Cesium.CallbackProperty(() => {
|
||
// return realtimeCartesianRef.current;
|
||
// }, false);
|
||
|
||
// realtimeLineEntityRef.current = viewer.entities.add({
|
||
// polyline: {
|
||
// positions: callbackPositions,
|
||
// width: 5,
|
||
// material: new Cesium.PolylineGlowMaterialProperty({
|
||
// glowPower: 0.25,
|
||
// color: Cesium?.Color.LIME
|
||
// }),
|
||
// clampToGround: true,
|
||
// disableDepthTestDistance: Number.POSITIVE_INFINITY
|
||
// }
|
||
// });
|
||
//}
|
||
} else {
|
||
// 移除实时轨迹线
|
||
if (realtimeLineEntityRef.current) {
|
||
viewer.entities.remove(realtimeLineEntityRef.current);
|
||
realtimeLineEntityRef.current = null;
|
||
}
|
||
realtimeCartesianRef.current = [];
|
||
}
|
||
|
||
if (
|
||
!hasFlownRef.current &&
|
||
getCameraMode() === 'realtime'
|
||
) {
|
||
const started = flyToView(
|
||
viewer,
|
||
FLIGHT_PRIORITY.realtime,
|
||
{
|
||
destination: Cesium.Cartesian3.fromDegrees(
|
||
lon,
|
||
lat,
|
||
30
|
||
),
|
||
orientation: {
|
||
heading: 0,
|
||
pitch: Cesium.Math.toRadians(-90),
|
||
roll: 0,
|
||
},
|
||
duration: 1.2,
|
||
},
|
||
`realtime:${lon.toFixed(6)},${lat.toFixed(6)}`
|
||
);
|
||
|
||
if (started) {
|
||
hasFlownRef.current = true;
|
||
}
|
||
}
|
||
viewer.scene.requestRender();
|
||
|
||
}, [realtimePosition]);
|
||
// 截图功能
|
||
const captureScreenshot = useCallback(() => {
|
||
return new Promise((resolve) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer) {
|
||
resolve(null);
|
||
return;
|
||
}
|
||
|
||
// 使用 Cesium 的截图功能
|
||
viewer.scene.render();
|
||
|
||
const canvas = viewer.scene.canvas;
|
||
const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
|
||
resolve(dataUrl);
|
||
});
|
||
}, []);
|
||
useEffect(() => {
|
||
handleDetectFn(detectReportInfo)
|
||
}, [detectReportInfo])
|
||
|
||
// 暴露 ref 方法
|
||
useImperativeHandle(ref, () => ({
|
||
captureScreenshot,
|
||
// 寻车/定位:直接飞到指定经纬度,绕过飞行优先级系统,确保手动触发一定生效
|
||
flyToPosition: (position, options = {}) => {
|
||
const viewer = viewerRef.current;
|
||
if (!viewer || !position) return;
|
||
const { lon, lat } = position;
|
||
if (lon == null || lat == null || isNaN(Number(lon)) || isNaN(Number(lat))) return;
|
||
const height = options.height || 300;
|
||
const duration = options.duration ?? 1.5;
|
||
try { viewer.camera.cancelFlight(); } catch (e) { /* 忽略 */ }
|
||
lastFlightPriorityRef.current = -1;
|
||
viewer.camera.flyTo({
|
||
destination: Cesium.Cartesian3.fromDegrees(Number(lon), Number(lat), height),
|
||
orientation: {
|
||
heading: Cesium.Math.toRadians(0.0),
|
||
pitch: Cesium.Math.toRadians(-90.0),
|
||
roll: 0.0,
|
||
},
|
||
duration,
|
||
});
|
||
},
|
||
}));
|
||
|
||
return (
|
||
<div className="w-full h-full bg-slate-900 overflow-hidden relative">
|
||
<div ref={containerRef} className="w-full h-full overflow-hidden" />
|
||
<div
|
||
ref={tooltipRef}
|
||
style={{
|
||
position: "absolute",
|
||
display: "none",
|
||
pointerEvents: "none",
|
||
background: "rgba(0,0,0,0.75)",
|
||
color: "#fff",
|
||
padding: "8px 10px",
|
||
borderRadius: "4px",
|
||
fontSize: "12px",
|
||
zIndex: 99999,
|
||
whiteSpace: "nowrap",
|
||
}}
|
||
/>
|
||
{/* 图例:返航点 / 分区 */}
|
||
{(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0 || stationOverlay.tempObstaclePoints.length > 0) && (
|
||
<div
|
||
style={{
|
||
position: "absolute",
|
||
right: 12,
|
||
top: 12,
|
||
zIndex: 20,
|
||
background: "rgba(255,255,255,0.92)",
|
||
borderRadius: 6,
|
||
padding: "8px 10px",
|
||
fontSize: 12,
|
||
color: "#333",
|
||
lineHeight: "18px",
|
||
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
|
||
}}
|
||
>
|
||
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
|
||
<div style={{
|
||
display: "flex",
|
||
alignItems: "center",
|
||
gap: 6,
|
||
padding: "2px 4px",
|
||
borderRadius: 4,
|
||
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
|
||
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
|
||
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
|
||
}}>
|
||
<span style={{
|
||
display: "inline-block",
|
||
width: 10,
|
||
height: 10,
|
||
background: "#165DFF",
|
||
borderRadius: "50% 50% 50% 0",
|
||
transform: "rotate(-45deg)",
|
||
}} />
|
||
<span>{t('devices.mapEditor.returnPoint')}</span>
|
||
</div>
|
||
<div style={{
|
||
display: "flex",
|
||
alignItems: "center",
|
||
gap: 6,
|
||
marginTop: 4,
|
||
padding: "2px 4px",
|
||
borderRadius: 4,
|
||
fontWeight: legendHighlight === "region" ? 600 : 400,
|
||
color: legendHighlight === "region" ? "#13C2C2" : "#333",
|
||
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
|
||
}}>
|
||
<span style={{
|
||
display: "inline-block",
|
||
width: 12,
|
||
height: 10,
|
||
border: "1px solid #13C2C2",
|
||
background: "rgba(19,194,194,0.18)",
|
||
}} />
|
||
<span>{t('devices.mapEditor.restArea')}</span>
|
||
</div>
|
||
|
||
<div style={{
|
||
display: "flex",
|
||
alignItems: "center",
|
||
gap: 6,
|
||
marginTop: 4,
|
||
padding: "2px 4px",
|
||
borderRadius: 4,
|
||
fontWeight: legendHighlight === "obstaclePoint" ? 600 : 400,
|
||
color: legendHighlight === "obstaclePoint" ? "#13C2C2" : "#333",
|
||
background: legendHighlight === "obstaclePoint" ? "rgba(19,194,194,0.12)" : "transparent",
|
||
}}>
|
||
<span
|
||
style={{
|
||
display: 'inline-block',
|
||
width: 12,
|
||
height: 12,
|
||
border: '2px solid #F5222D',
|
||
borderRadius: '50%',
|
||
background: 'rgba(245,34,45,0.18)',
|
||
boxSizing: 'border-box',
|
||
}}
|
||
/>
|
||
<span>{t('devices.mapEditor.obstacle')}</span>
|
||
</div>
|
||
<button
|
||
onClick={handleFlyToDevice}
|
||
style={{
|
||
display: 'inline-flex',
|
||
alignItems: 'center',
|
||
justifyContent: 'center',
|
||
gap: '8px',
|
||
padding: '4px 8px',
|
||
color: '#fff',
|
||
fontSize: '14px',
|
||
fontWeight: 500,
|
||
background: 'linear-gradient(135deg, #409eff 0%, #1677ff 100%)',
|
||
border: 'none',
|
||
borderRadius: '8px',
|
||
boxShadow: '0 3px 10px rgba(22, 119, 255, 0.25)',
|
||
cursor: 'pointer',
|
||
transition: 'all 0.2s ease',
|
||
}}
|
||
>
|
||
<span style={{ fontSize: '18px', lineHeight: 1 }}>⌖</span>
|
||
<span>定位到机器</span>
|
||
</button>
|
||
</div>
|
||
)}
|
||
|
||
</div>
|
||
);
|
||
|
||
});
|
||
|
||
export default CesiumMap;
|