import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react'; import carImg from '../assets/images/carplane.webp'; 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'; // 天地图 Key(在 .env 中配置 VITE_TIANDITU_TK) const TIANDITU_TK = "8861b77bd716627423751e526cb2c466"; // 天地图 WMTS 图层:vec_w 矢量 / img_w 卫星影像 / ter_w 地形晕渲,cva_w、cia_w、cta_w 依次为对应注记 const createTiandituProvider = (layerName) => new Cesium.WebMapTileServiceImageryProvider({ url: `https://t{s}.tianditu.gov.cn/${layerName}/wmts?tk=${TIANDITU_TK}`, layer: layerName.replace('_w', ''), style: 'default', format: 'tiles', tileMatrixSetID: 'w', tileMatrixLabels: Array.from({ length: 19 }, (_, i) => String(i)), tilingScheme: new Cesium.WebMercatorTilingScheme(), subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'], minimumLevel: 0, maximumLevel: 18, tileWidth: 256, tileHeight: 256, credit: '天地图', }); // 降级底图:天地图瓦片取不到时用 Esri 卫星影像兜底,避免地图黑屏 const createEsriSatelliteProvider = () => new Cesium.UrlTemplateImageryProvider({ url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', credit: 'Tiles © Esri', minimumLevel: 0, maximumLevel: 19, tilingScheme: new Cesium.WebMercatorTilingScheme(), }); const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, realtimeDevice, 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 markedObstacleHandlesRef = useRef([]); // 编辑中障碍物拖拽手柄 const markedLineRef = useRef(null); // 标记点连线实体 const lastMarkedPointsRef = useRef([]); // 上次渲染的标记点数据,用于增量更新 const onMarkPointRef = useRef(onMarkPoint); // 总是指向最新的 onMarkPoint,避免闭包滞后 const onCameraClickRef = useRef(onCameraClick); // 同样处理,避免闭包滞后 const lastHoverPositionRef = useRef(null); // 实时车辆图标(realtimeCarEntity)对应的设备信息,用于悬浮提示 const realtimeDeviceRef = useRef(null); const { t } = useTranslation(); // 实时模式下车图标为独立实体,没有 properties.robot,这里记录其设备信息 realtimeDeviceRef.current = realtimeDevice || (devices && devices[0]) || null; // 天地图底图:矢量 / 卫星 切换 const tiandituLayersRef = useRef(null); const esriFallbackLayerRef = useRef(null); const [baseMapType, setBaseMapType] = useState('satellite'); // 天地图不可用标记:瓦片连续加载失败后降级为 Esri 影像,并隐藏底图切换 const [tiandituUnavailable, setTiandituUnavailable] = useState(false); const tiandituUnavailableRef = useRef(false); const tiandituErrorCountRef = useRef(0); // 场站已配置的返航点 / 分区叠加显示 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 ); }; // 拖拽手柄时显示障碍物尺寸(长×宽 / 半径),跟随手柄位置 const OBSTACLE_DRAG_TIP_ID = 'obstacle-drag-tip'; const updateObstacleDragTip = (viewer, position, text) => { if (!viewer || !position) return; const existing = viewer.entities.getById(OBSTACLE_DRAG_TIP_ID); if (existing) { existing.position = new Cesium.ConstantPositionProperty(position); if (existing.label?.text?.setValue) { existing.label.text.setValue(text); } else if (existing.label) { existing.label.text = text; } return; } viewer.entities.add({ id: OBSTACLE_DRAG_TIP_ID, position, label: { text, font: 'bold 13px sans-serif', fillColor: Cesium.Color.WHITE, showBackground: true, backgroundColor: Cesium.Color.fromCssColorString('#ff4d4f').withAlpha(0.9), pixelOffset: new Cesium.Cartesian2(0, -18), disableDepthTestDistance: Number.POSITIVE_INFINITY, show: true, }, }); }; // 打印矩形障碍物信息(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 liveObstacleLastTsRef = useRef(0); // ============================== // 统一相机飞行调度器 // ============================== 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: false, geocoder: false, homeButton: false, sceneModePicker: false, navigationHelpButton: false, fullscreenButton: false, infoBox: false, baseLayer: false }); viewer.resolutionScale = 2.0; viewerRef.current = viewer; // 天地图底图:矢量 / 卫星 / 地形,均带注记,默认显示矢量 const tdtLayers = { vector: viewer.imageryLayers.addImageryProvider(createTiandituProvider('vec_w')), vectorLabel: viewer.imageryLayers.addImageryProvider(createTiandituProvider('cva_w')), satellite: viewer.imageryLayers.addImageryProvider(createTiandituProvider('img_w')), satelliteLabel: viewer.imageryLayers.addImageryProvider(createTiandituProvider('cia_w')), terrain: viewer.imageryLayers.addImageryProvider(createTiandituProvider('ter_w')), terrainLabel: viewer.imageryLayers.addImageryProvider(createTiandituProvider('cta_w')), }; tdtLayers.satellite.show = false; tdtLayers.satelliteLabel.show = false; tdtLayers.terrain.show = false; tdtLayers.terrainLabel.show = false; tiandituLayersRef.current = tdtLayers; // Esri 影像置于最底层:天地图对应瓦片加载失败时会透出该图层,防止地图一片黑 const esriFallbackLayer = viewer.imageryLayers.addImageryProvider(createEsriSatelliteProvider(), 0); esriFallbackLayer.show = true; esriFallbackLayerRef.current = esriFallbackLayer; // 天地图瓦片加载失败累计超过阈值后判定不可用,后续只显示 Esri 影像 const handleTiandituError = () => { if (tiandituUnavailableRef.current) return; tiandituErrorCountRef.current += 1; if (tiandituErrorCountRef.current >= 6) { tiandituUnavailableRef.current = true; setTiandituUnavailable(true); } }; Object.values(tdtLayers).forEach((layer) => { layer.imageryProvider?.errorEvent?.addEventListener(handleTiandituError); }); // 主动探测天地图服务可达性:请求 0 级瓦片,失败即判定不可用 const probeImg = new Image(); probeImg.onerror = () => { tiandituUnavailableRef.current = true; setTiandituUnavailable(true); }; probeImg.src = `https://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX=0&TILEROW=0&TILECOL=0&tk=${TIANDITU_TK}`; 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(); Object.values(tdtLayers).forEach((layer) => { layer.imageryProvider?.errorEvent?.removeEventListener(handleTiandituError); }); }; }, []); // 底图切换:矢量 / 卫星 / 地形 useEffect(() => { const layers = tiandituLayersRef.current; if (!layers) return; // 天地图不可用:隐藏全部天地图图层,只保留最底层的 Esri 影像 if (tiandituUnavailable) { Object.values(layers).forEach((layer) => { layer.show = false; }); if (esriFallbackLayerRef.current) esriFallbackLayerRef.current.show = true; viewerRef.current?.scene?.requestRender?.(); return; } const showVector = baseMapType === 'vector'; const showSatellite = baseMapType === 'satellite'; const showTerrain = baseMapType === 'terrain'; layers.vector.show = showVector; layers.vectorLabel.show = showVector; layers.satellite.show = showSatellite; layers.satelliteLabel.show = showSatellite; layers.terrain.show = showTerrain; layers.terrainLabel.show = showTerrain; viewerRef.current?.scene?.requestRender?.(); }, [baseMapType, tiandituUnavailable]); const computeDistanceScale = () => { const viewer = viewerRef.current; const MIN_SCALE = 0.35; const MAX_SCALE = 2.5; const REF_HEIGHT = 50; // 相机高度 50m 时 scale = 1(基准尺寸) const h = viewer.camera.positionCartographic?.height ?? REF_HEIGHT; let s = REF_HEIGHT / Math.max(h, 1); // 反比 if (s < MIN_SCALE) s = MIN_SCALE; if (s > MAX_SCALE) s = MAX_SCALE; return s; }; function updateLiveObstacleBoxes( message, ) { const viewer = viewerRef.current; //for (const [, entity] of liveObstacleEntities) { // viewer.entities.remove(entity); //} //liveObstacleEntities.clear(); // 让 billboard / label 图标随相机高度(地图远近)动态缩放 // 经验映射:相机越高(地图越远)scale 越小,相机越低(地图越近)scale 越大 // 相机高度 20m → scale 1.5;50m → 1.0;200m → 0.5;上限/下限 clamp if (!viewer || !Cesium) return; const payload = message; const objects = Array.isArray(payload) ? payload : Array.isArray(payload?.objects) ? payload.objects : []; console.log(objects, "障碍物信息") // 全量替换:先把地图上所有 live-obstacle 实体按 id 前缀全部移除 // 不依赖 liveObstacleEntities Map(避免历史孤儿实体残留) const toRemove = []; viewer.entities.values.forEach((ent) => { if (ent && ent.id && String(ent.id).startsWith('live-obstacle-')) { toRemove.push(ent); } }); toRemove.forEach((ent) => viewer.entities.remove(ent)); liveObstacleEntities.clear(); if (objects.length === 0) { console.log("没有障碍物") viewer.scene.requestRender(); return; } // 记录第一个有效障碍物的位置,用于视角跳转 let firstPos = null; objects.forEach((obj, index) => { console.log(obj, "障碍物信息1111") const lat = Number(obj.latitude ?? obj.lat); const lon = Number(obj.longitude ?? obj.lng ?? obj.lon); const dis = obj?.distance; // 优先按 class_id 判定类型;未提供时再 fallback 到 class_name 字符串 const CLASS_ID_MAP = { 0: 'bus', 1: 'car', 2: 'motorcycle', 3: 'person', 4: 'truck', }; const classIdRaw = obj.class_id ?? obj.classId ?? obj.class; const parsedClassId = Number(classIdRaw); const kindByClassId = Number.isInteger(parsedClassId) && CLASS_ID_MAP[parsedClassId] ? CLASS_ID_MAP[parsedClassId] : null; const rawName = (obj.class_name ?? obj.name ?? '').toLowerCase(); const kindByName = rawName.includes('person') || rawName.includes('行人') || rawName.includes('人') ? 'person' : rawName.includes('motorcycle') || rawName.includes('摩托车') || rawName.includes('电驴') ? 'motorcycle' : rawName.includes('bus') || rawName.includes('公交') || rawName.includes('大巴') ? 'bus' : rawName.includes('truck') || rawName.includes('货车') || rawName.includes('卡车') ? 'truck' : rawName.includes('car') || rawName.includes('车辆') || rawName.includes('车') ? 'car' : rawName.includes('fence') || rawName.includes('围挡') || rawName.includes('障碍') ? 'fence' : 'unknown'; const obstacleKind = kindByClassId || kindByName; const isPerson = obstacleKind === 'person'; const isVehicle = ['car', 'truck', 'bus', 'motorcycle'].includes(obstacleKind); const isFence = obstacleKind === 'fence'; // 尺寸兜底:过滤 NaN / 负数 / 0,避免 Cesium BoxOutlineGeometry 抛 DeveloperError const safeSize = (val, fallback) => { const n = Number(val); return Number.isFinite(n) && n > 0 ? n : fallback; }; // 不同类别的默认尺寸(长 x 宽 x 高,单位米) const KIND_DEFAULT_SIZE = { person: { sx: 0.6, sy: 0.6, sz: 1.7 }, motorcycle: { sx: 0.8, sy: 2.2, sz: 1.6 }, car: { sx: 1.8, sy: 4.5, sz: 1.5 }, truck: { sx: 2.5, sy: 7.0, sz: 3.0 }, bus: { sx: 2.6, sy: 10.0, sz: 3.2 }, fence: { sx: 1.2, sy: 1.2, sz: 1.5 }, unknown: { sx: 1.2, sy: 1.2, sz: 1.5 }, }; const defaults = KIND_DEFAULT_SIZE[obstacleKind] || KIND_DEFAULT_SIZE.unknown; const sx = safeSize(obj.size_x ?? obj.sizeX, defaults.sx); const sy = safeSize(obj.size_y ?? obj.sizeY, defaults.sy); const sz = safeSize(obj.size_z ?? obj.sizeZ, defaults.sz); if (!Number.isFinite(lat) || !Number.isFinite(lon)) return; const id = `live-obstacle-${index}`; const position = Cesium.Cartesian3.fromDegrees(lon, lat, sz / 2); if (!firstPos) firstPos = { lon, lat }; const orientation = Cesium.Transforms.headingPitchRollQuaternion( position, new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(Number(obj.angle ?? obj.yaw ?? 0)), 0, 0) ); // 不同类别的颜色、图标和文字 const KIND_STYLE = { person: { color: Cesium.Color.YELLOW, emoji: '🚶', label: '行人', icon: 'https://img.icons8.com/color/96/walking--v1.png', width: 24 }, motorcycle: { color: Cesium.Color.ORANGE, emoji: '🛵', label: '摩托车', icon: 'https://img.icons8.com/color/96/motorcycle--v1.png', width: 28 }, car: { color: Cesium.Color.CYAN, emoji: '🚗', label: '小车', icon: 'https://img.icons8.com/color/96/car--v1.png', width: 32 }, truck: { color: Cesium.Color.LIME, emoji: '🚚', label: '货车', icon: 'https://img.icons8.com/color/96/delivery-truck--v1.png', width: 36 }, bus: { color: Cesium.Color.VIOLET, emoji: '🚌', label: '公交', icon: 'https://img.icons8.com/color/96/bus--v1.png', width: 36 }, unknown: { color: Cesium.Color.RED, emoji: '⚠️', label: '障碍物', icon: null, width: 32 }, }; const style = KIND_STYLE[obstacleKind] || KIND_STYLE.unknown; const boxColor = style.color; const typeEmoji = style.emoji; const iconImage = style.icon; const labelText = `${typeEmoji} ${style.label} (${sx.toFixed(1)}x${sy.toFixed(1)}m) ${dis ? `\n距离: ${dis.toFixed(1)}m` : ''}`; const billboardSize = style.width; let entity = viewer.entities.getById(id); if (!entity) { entity = viewer.entities.add({ id, position, orientation, // 外部包围盒,显示物理占用空间 //box: { // dimensions: new Cesium.Cartesian3(sx, sy, sz), // material: boxColor.withAlpha(0.2), // outline: true, // outlineColor: boxColor, // outlineWidth: 1, //}, // 内部图标,直观显示物体类型 billboard: iconImage ? { image: iconImage, width: billboardSize, height: billboardSize, heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND, disableDepthTestDistance: Number.POSITIVE_INFINITY, scale: new Cesium.CallbackProperty(computeDistanceScale, false), } : undefined, //label: { // text: labelText, // font: 'bold 14px sans-serif', // fillColor: Cesium.Color.WHITE, // showBackground: true, // backgroundColor: boxColor.withAlpha(0.85), // pixelOffset: new Cesium.Cartesian2(0, -40), // disableDepthTestDistance: Number.POSITIVE_INFINITY, // //scale: new Cesium.CallbackProperty(computeDistanceScale, false), //}, }); } else { entity.position = position; entity.orientation = orientation; if (entity.box) { entity.box.dimensions = new Cesium.Cartesian3(sx, sy, sz); entity.box.material = boxColor.withAlpha(0.2); entity.box.outlineColor = boxColor; } if (entity.billboard && iconImage) { entity.billboard.image = iconImage; entity.billboard.scale = new Cesium.CallbackProperty(computeDistanceScale, false); } if (entity.label) { entity.label.text = labelText; entity.label.backgroundColor = boxColor.withAlpha(0.85); entity.label.scale = new Cesium.CallbackProperty(computeDistanceScale, false); } } liveObstacleEntities.set(id, entity); }); // 自动跳转到第一个障碍物 //if (firstPos) { // flyToView(viewer, 100, { // destination: Cesium.Cartesian3.fromDegrees(firstPos.lon, firstPos.lat, 60), // orientation: { // heading: Cesium.Math.toRadians(0), // pitch: Cesium.Math.toRadians(-40), // roll: 0 // }, // duration: 2.0 // }, 'live-obstacle-jump'); //} viewer.scene.requestRender(); } // 模拟触发实时障碍物(仅用于演示) //useEffect(() => { // const viewer = viewerRef.current; // if (!viewer || !Cesium) return; // const timer = setTimeout(() => { // console.log("[Mock] 触发模拟实时障碍物渲染 (人+车+围挡)"); // const mockMsg = { // objects: [ // { // track_id: "obs-v-001", // latitude: 31.2989, // longitude: 120.5853, // size_x: 1.8, // size_y: 4.2, // size_z: 1.5, // angle: 30, // class_name: "车辆" // }, // { // track_id: "obs-p-002", // latitude: 31.2992, // longitude: 120.5856, // size_x: 0.6, // size_y: 0.6, // size_z: 1.7, // angle: 0, // class_name: "行人" // }, // //{ // // track_id: "obs-f-003", // // latitude: 31.2987, // // longitude: 120.5850, // // size_x: 3.0, // // size_y: 0.5, // // size_z: 2.0, // // angle: 90, // // class_name: "施工围挡" // //} // ] // }; // updateLiveObstacleBoxes(mockMsg); // }, 3000); // return () => clearTimeout(timer); //}, [stationId]); //useEffect(() => { // const viewer = viewerRef.current; // if (!viewer || !Cesium) return; // let count = 0; // const mockTimer = setInterval(() => { // count++; // let mockMsg; // // 奇数次:模拟有障碍物 // if (count % 2 === 1) { // mockMsg = { // objects: [ // { // track_id: "obs-v-001", // latitude: 31.2989, // longitude: 120.5853, // size_x: 1.8, // size_y: 4.2, // size_z: 1.5, // angle: 30, // class_name: "车辆", // distance: 15.5 // }, // { // track_id: "obs-p-002", // latitude: 31.2992, // longitude: 120.5856, // size_x: 0.6, // size_y: 0.6, // size_z: 1.7, // angle: 0, // class_name: "行人", // distance: 8.2 // }, // { // track_id: "obs-t-003", // latitude: 31.2987, // longitude: 120.5850, // size_x: 2.5, // size_y: 7.0, // size_z: 3.0, // angle: 90, // class_name: "货车", // distance: 22.6 // } // ] // }; // console.log("模拟发送:有障碍物", mockMsg); // } else { // // 偶数次:模拟没有障碍物 // mockMsg = { // objects: [] // }; // console.log("模拟发送:没有障碍物"); // } // updateLiveObstacleBoxes(mockMsg); // }, 3000); // 每隔3秒发送一次 // return () => { // clearInterval(mockTimer); // }; //}, [stationId]); const handleDetectFn = (res) => { liveObstacleLastTsRef.current = Date.now(); updateLiveObstacleBoxes(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') { return; 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, scale: new Cesium.CallbackProperty(computeDistanceScale, false), 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); //viewer.entities.removeById(`marked-obstacle-handle-${baseId}`); return false; } return true; }); // 清理不在列表中的 obstacle circle obstacleCirclesRef.current = obstacleCirclesRef.current.filter(id => { if (!nextObstacleCircleIds.has(id)) { viewer.entities.removeById(id); return false; } return true; }); markedObstacleHandlesRef.current = markedObstacleHandlesRef.current.filter(id => { if (!newPoints.some((p, i) => `marked-obstacle-handle-${p.id ?? i}` === 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); } // 障碍物点:根据形状创建预览 + 拖拽手柄 if (isObstacle) { const shapeType = p.shapeType === 'circle' ? 'circle' : 'rect'; const sizeX = Math.max(0.1, Number(p.sizeX) || Number(p.size_x) || 2); const sizeY = Math.max(0.1, Number(p.sizeY) || Number(p.size_y) || 2); const radius = Math.max(0.1, Number(p.radius) || 2); const entity = viewer.entities.getById(circleId); if (shapeType === 'rect') { if (entity?.rectangle) { entity.rectangle.coordinates.setValue(getObstacleRectCoordinates(Number(p.lon), Number(p.lat), sizeX, sizeY)); } else { viewer.entities.add({ id: circleId, position, rectangle: { coordinates: getObstacleRectCoordinates(Number(p.lon), Number(p.lat), sizeX, sizeY), height: 0, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, material: new Cesium.Color(1.0, 0.3, 0.3, 0.25), outline: true, outlineColor: Cesium.Color.RED, outlineWidth: 2, }, }); } } else { if (entity?.ellipse) { entity.ellipse.semiMajorAxis.setValue(radius); entity.ellipse.semiMinorAxis.setValue(radius); } else { viewer.entities.add({ id: circleId, position, ellipse: { semiMajorAxis: radius, semiMinorAxis: radius, height: 0, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, material: new Cesium.Color(1.0, 0.3, 0.3, 0.25), outline: true, outlineColor: Cesium.Color.RED, outlineWidth: 2, }, }); } } if (!obstacleCirclesRef.current.includes(circleId)) obstacleCirclesRef.current.push(circleId); // 拖拽手柄 const handleId = `marked-obstacle-handle-${p.id ?? i}`; const handlePos = shapeType === 'rect' ? getObstacleRectHandlePosition(Number(p.lon), Number(p.lat), sizeX, sizeY) : getObstacleHandlePosition(Number(p.lon), Number(p.lat), radius); const existingHandle = viewer.entities.getById(handleId); if (existingHandle) { existingHandle.position = new Cesium.ConstantPositionProperty(handlePos); } else { viewer.entities.add({ id: handleId, obstacleHandleData: { index: i, pointId: p.id, source: 'marked' }, position: handlePos, point: { pixelSize: 13, color: Cesium.Color.WHITE, outlineColor: Cesium.Color.RED, outlineWidth: 3, disableDepthTestDistance: Number.POSITIVE_INFINITY }, label: { text: '\u2194', font: 'bold 12px sans-serif', fillColor: Cesium.Color.RED, pixelOffset: new Cesium.Cartesian2(0, -1), disableDepthTestDistance: Number.POSITIVE_INFINITY }, }); if (!markedObstacleHandlesRef.current.includes(handleId)) markedObstacleHandlesRef.current.push(handleId); } } }); // 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?.color; return fsRaw === 'red' ? 'offline' : fsRaw === 'green' ? 'working' : fsRaw === 'blue' ? 'idle' : 'idle'; ////if (device?.onlineStatus == 0) return 'offline'; //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'; //} //// 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'; //} } // 设备状态视觉统一:工作中蓝 / 空闲绿 / 离线红(底层光圈与悬浮提示共用同一套颜色) const DEVICE_STATUS_COLORS = { working: '#1677ff', idle: '#52c41a', offline: '#ff4d4f', }; // 设备类型归一化:统一读 deviceType(I=巡检 / M=割草机 / U=无人机),兼容旧 type 字段 function getDeviceKind(device) { const dt = String(device?.deviceType || '').toUpperCase(); if (dt === 'U') return 'drone'; if (dt === 'M') return 'mower'; if (dt === 'I') return 'inspection'; // 兼容旧 type 字段值 const legacy = String(device?.type || '').toLowerCase(); if (legacy === 'plane' || legacy === 'drone' || legacy === 'drone-inspect') return 'drone'; if (legacy === 'mower') return 'mower'; if (legacy === 'robot') return 'inspection'; if (legacy === 'camera') return 'camera'; return 'unknown'; } const isDroneDevice = (d) => getDeviceKind(d) === 'drone'; const isMowerDevice = (d) => getDeviceKind(d) === 'mower'; const isInspectionDevice = (d) => getDeviceKind(d) === 'inspection'; const isCameraDevice = (d) => getDeviceKind(d) === 'camera'; // 光圈颜色:工作中蓝(#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: DEVICE_STATUS_COLORS.working }, idle: { text: t('devices.idle'), color: DEVICE_STATUS_COLORS.idle }, offline: { text: t('devices.offline'), color: DEVICE_STATUS_COLORS.offline } }; const status = statusMap[stateKey] || statusMap.idle; // 控制模式 / 系统模式 / 定位状态 文案映射(与任务规划页保持一致) const controlModeMap = { '0': t('devices.controlOff'), '1': t('devices.localCpntrol'), '2': t('devices.autoTask'), '3': t('devices.remoteControl') }; const systemModeMap = { '2': t('devices.autoTask'), '3': t('devices.remoteControl') }; const fixStatusMap = { no_fix: t('devices.noFix'), single: t('devices.single'), dgnss: t('devices.dgnss'), ins: t('devices.ins'), rtk_fixed: t('devices.rtkFixed'), rtk_float: t('devices.rtkFloat'), single_no_heading: t('devices.singleNoHeading'), dgnss_no_heading: t('devices.dgnssNoHeading'), rtk_fixed_no_heading: t('devices.rtkFixedNoHeading'), rtk_float_no_heading: t('devices.rtkFloatNoHeading') }; // 以下状态行仅在设备携带对应字段时展示,普通标记点的悬浮提示不受影响 const hasWorkStatus = robot.color !== undefined || robot.status !== undefined || robot.feStatus !== undefined; const controlModeText = robot.controlMode !== undefined && robot.controlMode !== null && robot.controlMode !== '' ? (controlModeMap[String(robot.controlMode)] || '-') : ''; const systemModeText = robot.sm !== undefined && robot.sm !== null && robot.sm !== '' ? (systemModeMap[String(robot.sm)] || '-') : ''; const fixStatusText = robot.fix_status ? (fixStatusMap[robot.fix_status] || String(robot.fix_status)) : ''; const batteryRaw = robot.battery !== undefined && robot.battery !== null ? robot.battery : (robot.batteryLevel !== undefined ? robot.batteryLevel : undefined); const batteryText = batteryRaw !== undefined && batteryRaw !== null && batteryRaw !== '' ? Number(batteryRaw) + '%' : ''; let deviceValuesHTML = ''; if (robot.devicevalue && robot.devicevalue.length > 0) { deviceValuesHTML = robot.devicevalue.map((device) => `
${device.name}: ${device.value}${device.unit}
`).join(''); } tooltip.innerHTML = `
🤖 ${robot.deviceAlias || robot.serialNumber || robot.name} ${robot.deviceType != null && robot.deviceType !== '' ? ` ${robot.deviceType} ` : ''}
${deviceValuesHTML ? `
${t('devices.deviceData')}:${deviceValuesHTML}
` : ''} ${hasWorkStatus ? `
${t('systemSetting.status')}:${status.text}
` : ''} ${controlModeText ? `
${t('devices.controlMode')}${controlModeText}
` : ''} ${systemModeText ? `
${t('devices.systemMode')}:${systemModeText}
` : ''} ${batteryText ? `
${t('devices.rtBattery')}:${batteryText}
` : ''}
${t('systemSetting.longitude')}:${lonStr}
${t('systemSetting.latitude')}:${latStr}
`; } else { tooltip.innerHTML = `
📍 ${t('systemSetting.longitude')}:${lonStr}
${t('systemSetting.latitude')}:${latStr}
`; } } // 判断拾取到的实体是否为实时车图标或其光圈(光圈实体没有 properties.robot,需单独识别) const isRealtimeCarPick = (picked) => { if (!Cesium.defined(picked) || !picked.id) return false; const target = picked.id; if (realtimeCarEntityRef.current && target === realtimeCarEntityRef.current) return true; const entityId = typeof target.id === 'string' ? target.id : ''; return entityId.startsWith('realtime_car_halo'); }; 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 = `
📍 ${point.alias || '-'}
`; } 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, show: true, }, // 名称与半径标签 label: { text: isRect ? `${obstacle?.alias || obstacle?.name || `障碍物点-${idx + 1}`} (${rectWidth.toFixed(2)}×${rectHeight.toFixed(2)}m)` : `${obstacle?.alias || obstacle?.name || `障碍物点-${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 ), show: true, }, }); 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, show: true, }, label: { text: '↔', font: 'bold 12px sans-serif', fillColor: Cesium.Color.RED, pixelOffset: new Cesium.Cartesian2(0, -1), disableDepthTestDistance: Number.POSITIVE_INFINITY, show: true, }, }); stationOverlayIdsRef.current.push(handleId); }); viewer.scene.requestRender(); }, [stationOverlay, highlightReturnPointId, obstacleShapeSignature, activeType]); 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 handleSource = handleData.source || 'station'; let lon, lat, radius, shapeType, rectWidth, rectHeight, entityId, handleId; if (handleSource === 'marked') { const obstacle = markedPoints[index]; if (!obstacle) return; lon = Number(obstacle.lon); lat = Number(obstacle.lat); shapeType = obstacle.shapeType === 'circle' ? 'circle' : 'rect'; radius = Math.max(0.1, Number(obstacle.radius) || 2); rectWidth = shapeType === 'rect' ? (Number(obstacle.sizeX) || Number(obstacle.size_x) || 2) : radius * 2; rectHeight = shapeType === 'rect' ? (Number(obstacle.sizeY) || Number(obstacle.size_y) || 2) : radius * 2; entityId = `marked-obstacle-circle-${obstacle.id ?? index}`; handleId = `marked-obstacle-handle-${obstacle.id ?? index}`; } else { const obstacles = stationOverlay.tempObstaclePoints || []; const obstacle = obstacles[index]; if (!obstacle) return; lon = Number(obstacle.position?.lng ?? obstacle.position?.lon); lat = Number(obstacle.position?.lat); radius = Number(obstacle.radius ?? 2); const shapeConfig = obstacleShapes?.[index] || {}; shapeType = shapeConfig.shapeType === 'rect' ? 'rect' : 'circle'; rectWidth = Math.max(0.1, Number(shapeConfig.width) || radius * 2); rectHeight = Math.max(0.1, Number(shapeConfig.height) || radius * 2); entityId = `station-obstacle-point-${index}`; handleId = `station-obstacle-handle-${index}`; } if (!Number.isFinite(lon) || !Number.isFinite(lat) || !Number.isFinite(radius)) return; draggingObstacleRef.current = { index, source: handleSource, entityId, handleId, center: Cesium.Cartesian3.fromDegrees(lon, lat, 0), lon, lat, radius, shapeType, 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 ) ); } const handlePos = getObstacleRectHandlePosition( dragging.lon, dragging.lat, width, height ); if (rectHandle) { rectHandle.position = new Cesium.ConstantPositionProperty(handlePos); } // 拖拽过程中实时显示长宽 updateObstacleDragTip( viewer, handlePos, `${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); } // 同步更新手柄位置 const circleHandlePos = getObstacleHandlePosition( dragging.lon, dragging.lat, nextRadius ); if (handle) { handle.position = new Cesium.ConstantPositionProperty(circleHandlePos); } // 拖拽过程中实时显示直径 updateObstacleDragTip( viewer, circleHandlePos, `直径 ${(nextRadius * 2).toFixed(2)} m` ); // 同步更新圆圈标签 if (circle) { const obstacle = dragging.source === 'marked' ? markedPoints?.[dragging.index] : stationOverlay.tempObstaclePoints?.[dragging.index]; const labelText = `${obstacle?.alias || obstacle?.name || `障碍物点-${dragging.index + 1}`} (${nextRadius.toFixed(2)}m)`; if (circle.label) { if (circle.label.text && circle.label.text.setValue) { circle.label.text.setValue(labelText); } else { circle.label.text = labelText; } circle.label.show = new Cesium.ConstantProperty(true); } } 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; // 移除拖拽尺寸提示 const tip = viewer.entities.getById(OBSTACLE_DRAG_TIP_ID); if (tip) viewer.entities.remove(tip); } // 矩形:打印信息并回传长宽给父组件(暂不走圆形保存逻辑) if (dragging.shapeType === 'rect') { const obstacle = dragging.source === 'marked' ? markedPoints?.[index] : 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, markedPoints, activeType]); // 点击已配置列表:定位到对应返航点/分区;返航点额外高亮 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 = isCameraDevice(device) ? cameraImg : iotImg; width = isCameraDevice(device) ? 40 : 20; height = isCameraDevice(device) ? 40 : 20; } else { image = isDroneDevice(device) ? planeImg : // 无人机/飞机 isMowerDevice(device) ? carImg : // 割草机 carImg; // 巡检/默认车 width = isDroneDevice(device) ? 30 : carsize; height = isDroneDevice(device) ? 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 = isCameraDevice(device) ? 0.8 : 0.8; } else if (isDroneDevice(device)) { 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 = isCameraDevice(device) ? 35 : 28; } else if (isDroneDevice(device)) { 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; // 实时车图标及其光圈(无 properties.robot)悬浮时,用当前实时设备信息补全 const pickedIsRealtimeCarNow = isRealtimeCarPick(pickedNow); const robotNow = pickedRobotNow || (pickedIsRealtimeCarNow ? realtimeDeviceRef.current : null); if (pickedReturnPointNow) { showReturnPointTooltip(tooltipRef.current, hoverPos, pickedReturnPointNow); } else if (robotNow) { const hoverLngLat = getCursorLngLat(viewer, hoverPos); showCoordinateTooltip(tooltipRef.current, hoverPos, t, hoverLngLat.lon, hoverLngLat.lat, robotNow); } } // ============================== // 首屏:仅第一次根据 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; // 实时模式下的车图标及光圈是独立实体(无 properties.robot),用当前实时设备信息补全悬浮提示 const pickedIsRealtimeCar = isRealtimeCarPick(picked); // 返航点优先显示「别名 + 绑定机器」,设备显示设备信息,空白区域隐藏 if (pickedReturnPoint) { lastHoverPositionRef.current = movement.endPosition; showReturnPointTooltip(tooltipRef.current, movement.endPosition, pickedReturnPoint); } else if (pickedRobot || (pickedIsRealtimeCar && realtimeDeviceRef.current)) { lastHoverPositionRef.current = movement.endPosition; const robot = pickedRobot || realtimeDeviceRef.current; const { lon, lat } = getCursorLngLat(viewer, movement.endPosition); showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, lon, lat, robot); } 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 => isDroneDevice(d)); // ============================= // 判断实时数据是否合法 // ============================= const hasRealtime = realtimePosition && realtimePosition.lon && realtimePosition.lat && !isNaN(Number(realtimePosition.lon)) && !isNaN(Number(realtimePosition.lat)); const rtHaloColor = realtimePosition?.status == "online" ? Cesium.Color.fromCssColorString('#19cd08') : Cesium.Color.fromCssColorString('#ef340b'); // ============================= // 判断是否需要飞行 // ============================= const needFlight = hasRealtime && !hasFlownRef.current && !realtimeHiddenRef.current; // ============================= // 判断是否需要隐藏 // ============================= // ==================================== // 情况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); // 实时光圈颜色:优先取设备状态色,缺省蓝色(工作) // ==================================== // 无人机模式:保持原来的逻辑 // ==================================== if (isDroneMode || from == "deviceStatus" || from == "devicesTask" || from == "mapEditor") { // 轨迹点去抖动(防止重复点) // 实时轨迹过滤:重复点不添加,异常跳点不连接 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]) // // 超时兜底:2s 没收到新的障碍物消息,自动清掉(防止上游停推时残留) useEffect(() => { const TIMEOUT = 2000; const timer = setInterval(() => { const now = Date.now(); if (liveObstacleLastTsRef.current > 0 && now - liveObstacleLastTsRef.current > TIMEOUT) { const v = viewerRef.current; if (!v || !v.scene) return; // 按 id 前缀扫掉所有 live-obstacle 实体(不依赖 Map 记录) const toRemove = []; v.entities.values.forEach((ent) => { if (ent && ent.id && String(ent.id).startsWith('live-obstacle-')) toRemove.push(ent); }); toRemove.forEach((ent) => v.entities.remove(ent)); liveObstacleEntities.clear(); liveObstacleLastTsRef.current = 0; v.scene.requestRender(); } }, 500); return () => clearInterval(timer); }, []); // 暴露 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 (
{/* 底图切换:矢量 / 卫星 / 地形(天地图不可用时降级 Esri,隐藏切换) */} {!tiandituUnavailable && (
{[{ key: 'vector', label: t('common.mapVector') }, { key: 'satellite', label: t('common.mapSatellite') }, { key: 'terrain', label: t('common.mapTerrain') }].map((item) => ( ))}
)} {/* 图例:返航点 / 分区 */}
{t('devices.mapEditor.legend')}
{t('devices.mapEditor.returnPoint')}
{t('devices.mapEditor.restArea')}
{t('devices.mapEditor.obstacle')}
); }); export default CesiumMap;