feat: 1:地图仪表盘 2:获取设备消息

This commit is contained in:
2025-11-28 12:38:53 +08:00
parent 5102461a4c
commit 7ce0185974
74 changed files with 15488 additions and 55 deletions
@@ -0,0 +1,177 @@
import React, { useEffect, useRef } from 'react';
import { message } from 'antd';
// 扩展Window类型,添加AMap全局变量
declare global {
interface Window {
AMap: any;
}
}
interface AmapContainerProps {
tourismList: any[];
onTourismClick: (tourism: any) => void;
}
const AmapContainer: React.FC<AmapContainerProps> = (props) => {
const { tourismList, onTourismClick } = props;
const mapRef = useRef<HTMLDivElement>(null);
const mapInstanceRef = useRef<any>(null);
const markersRef = useRef<Map<string, any>>(new Map());
// 初始化地图
useEffect(() => {
const initMap = () => {
if (!window.AMap) {
console.error('window.AMap 未定义');
message.error('地图SDK未加载');
return;
}
if (!mapRef.current) {
console.error('地图容器未找到');
return;
}
try {
console.log('开始初始化高德地图...');
mapInstanceRef.current = new window.AMap.Map(mapRef.current, {
zoom: 5, // 缩放级别5可以看到整个中国
center: [104.195397, 35.86166], // 中国地理中心
mapStyle: 'amap://styles/normal',
viewMode: '2D',
features: ['bg', 'road', 'building'],
resizeEnable: true,
});
console.log('地图初始化成功,开始加载控件插件...');
// 添加地图控件 - 使用 AMap.plugin 异步加载
window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
if (mapInstanceRef.current) {
try {
const scale = new window.AMap.Scale();
const toolBar = new window.AMap.ToolBar();
mapInstanceRef.current.addControl(scale);
mapInstanceRef.current.addControl(toolBar);
console.log('地图控件加载成功');
} catch (err: any) {
console.error('地图控件加载失败:', err);
}
}
});
} catch (error: any) {
console.error('地图初始化失败:', error);
message.error('地图初始化失败: ' + error.message);
}
};
// 加载高德地图SDK
if (!window.AMap) {
const apiKey = process.env.REACT_APP_AMAP_KEY || 'YOUR_AMAP_KEY';
console.log('开始加载高德地图SDK, API Key:', apiKey);
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${apiKey}`;
script.async = true;
script.crossOrigin = 'anonymous';
script.onload = () => {
console.log('高德地图SDK加载成功');
initMap();
};
script.onerror = (error) => {
console.error('高德地图SDK加载失败:', error);
message.error('地图SDK加载失败,请检查网络连接和API Key');
};
document.head.appendChild(script);
} else {
console.log('高德地图SDK已存在,直接初始化');
initMap();
}
return () => {
if (mapInstanceRef.current) {
try {
mapInstanceRef.current.destroy();
} catch (error) {
console.error('地图销毁失败:', error);
}
}
};
}, []);
// 更新景区标记
useEffect(() => {
if (!mapInstanceRef.current || !tourismList.length) return;
// 清除旧标记
markersRef.current.forEach((marker, key) => {
if (key.startsWith('tourism_')) {
marker.setMap(null);
markersRef.current.delete(key);
}
});
// 验证并过滤有效的景区坐标(只显示有经纬度的景区)
const validTourisms = tourismList.filter((tourism) => {
const lat = parseFloat(tourism.latitude);
const lng = parseFloat(tourism.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});
// 如果没有有效景区,不进行后续操作
if (validTourisms.length === 0) {
return;
}
// 添加景区标记
validTourisms.forEach((tourism) => {
const lng = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
// 根据 status 状态设置颜色:1=绿色(启用),0=红色(禁用)
const fillColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
const marker = new window.AMap.CircleMarker({
center: [lng, lat],
radius: 15,
fillColor: fillColor,
fillOpacity: 0.8,
strokeColor: '#fff',
strokeWeight: 3,
zIndex: 10,
cursor: 'pointer',
});
// 添加点击事件
marker.on('click', () => onTourismClick(tourism));
// 添加信息窗体
const infoWindow = new window.AMap.InfoWindow({
content: `<div style="padding: 8px;">
<h4 style="margin: 0 0 8px 0;">${tourism.tourismName || '景区'}</h4>
<p style="margin: 0; color: #666;">${tourism.tourismAddress || ''}</p>
</div>`,
offset: new window.AMap.Pixel(0, -30),
});
marker.on('mouseover', () => {
infoWindow.open(mapInstanceRef.current, marker.getCenter());
});
marker.on('mouseout', () => {
infoWindow.close();
});
marker.setMap(mapInstanceRef.current);
markersRef.current.set(`tourism_${tourism.id}`, marker);
});
}, [tourismList, onTourismClick]);
return <div ref={mapRef} style={{ width: '100%', height: '100%' }} />;
};
export default AmapContainer;
@@ -0,0 +1,250 @@
import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
// 动态导入Cesium
let Cesium: any = null;
interface CesiumContainerProps {
tourismList: any[];
onTourismClick: (tourism: any) => void;
}
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const { tourismList, onTourismClick } = props;
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const [loading, setLoading] = useState(true);
// 初始化Cesium
useEffect(() => {
const initCesium = async () => {
try {
// 动态导入Cesium
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
// 动态加载Cesium样式(使用CDN,稳定可靠)
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/cesium@1.110.0/Build/Cesium/Widgets/widgets.css';
document.head.appendChild(link);
}
}
if (!containerRef.current) return;
// 配置Cesium Ion Token(使用默认的,或配置自己的)
// Cesium.Ion.defaultAccessToken = process.env.REACT_APP_CESIUM_TOKEN || '';
// 创建Viewer
viewerRef.current = new Cesium.Viewer(containerRef.current, {
// 使用天地图或高德作为底图(国内访问)
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
minimumLevel: 3,
maximumLevel: 18,
}),
// 地形设置 - 使用默认地形(平坦)
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
// UI组件配置
animation: false, // 不显示动画控件
timeline: false, // 不显示时间轴
fullscreenButton: false, // 不显示全屏按钮
geocoder: false, // 不显示地理位置搜索
homeButton: true, // 显示主页按钮
sceneModePicker: true, // 显示2D/3D切换
baseLayerPicker: false, // 不显示底图选择器
navigationHelpButton: false,// 不显示帮助按钮
// 性能优化
requestRenderMode: true, // 请求渲染模式
maximumRenderTimeChange: Infinity,
});
// 设置初始视角(中国中心,可以看到全国范围)
viewerRef.current.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 5000000), // 提高高度到5000km
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-60), // 俯视角度
roll: 0.0,
},
});
// 移除Cesium Logo和版权信息的点击事件
const creditContainer = viewerRef.current.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
}
setLoading(false);
message.success('3D地图加载完成');
} catch (error) {
console.error('Cesium初始化失败:', error);
message.error('3D地图加载失败');
setLoading(false);
}
};
initCesium();
return () => {
// 清理
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.destroy();
}
};
}, []);
// 更新景区标记
useEffect(() => {
if (!viewerRef.current || !Cesium || !tourismList.length) return;
const viewer = viewerRef.current;
// 清除旧标记
entitiesRef.current.forEach((entity, key) => {
if (key.startsWith('tourism_')) {
viewer.entities.remove(entity);
entitiesRef.current.delete(key);
}
});
// 验证并过滤有效的景区坐标(只显示有经纬度的景区)
const validTourisms = tourismList.filter((tourism) => {
const lat = parseFloat(tourism.latitude);
const lng = parseFloat(tourism.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});
// 如果没有有效景区,不进行后续操作
if (validTourisms.length === 0) {
return;
}
// 添加景区标记
const positions: any[] = [];
validTourisms.forEach((tourism) => {
const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
// 根据 status 状态设置颜色:1=绿色(启用),0=红色(禁用)
const pointColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
positions.push(Cesium.Cartesian3.fromDegrees(lon, lat));
// 创建实体标记
const entity = viewer.entities.add({
id: `tourism_${tourism.id}`,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
// 点标记
point: {
pixelSize: 20,
color: Cesium.Color.fromCssColorString(pointColor),
outlineColor: Cesium.Color.WHITE,
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
// 标签
label: {
text: tourism.tourismName || '景区',
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -25),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
// 存储景区数据
properties: {
tourismData: tourism,
},
});
entitiesRef.current.set(`tourism_${tourism.id}`, entity);
});
}, [tourismList]);
// 点击事件
useEffect(() => {
if (!viewerRef.current || !Cesium) return;
const viewer = viewerRef.current;
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// 左键点击
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const tourismData = entity.properties?.tourismData?.getValue();
if (tourismData) {
onTourismClick(tourismData);
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 鼠标移动悬停效果
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.endPosition);
if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.point) {
// 鼠标悬停时放大点
pickedObject.id.point.pixelSize = 25;
document.body.style.cursor = 'pointer';
} else {
// 恢复所有点的大小
entitiesRef.current.forEach((entity) => {
if (entity.point) {
entity.point.pixelSize = 20;
}
});
document.body.style.cursor = 'default';
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
return () => {
handler.destroy();
document.body.style.cursor = 'default';
};
}, [onTourismClick]);
return (
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
{loading && (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
color: '#fff',
fontSize: 16,
background: 'rgba(0,0,0,0.5)',
padding: '10px 20px',
borderRadius: 4,
}}
>
加载3D地图中...
</div>
)}
</div>
);
};
export default CesiumContainer;
@@ -0,0 +1,5 @@
.mapContainer {
width: 100%;
height: 100%;
position: relative;
}
@@ -0,0 +1,26 @@
import React from 'react';
import AmapContainer from './AmapContainer';
import CesiumContainer from './CesiumContainer';
import styles from './index.less';
interface MapContainerProps {
mode: '2d' | '3d';
tourismList: any[];
onTourismClick: (tourism: any) => void;
}
const MapContainer: React.FC<MapContainerProps> = (props) => {
const { mode, ...otherProps } = props;
return (
<div className={styles.mapContainer}>
{/* 2D地图 - 高德 */}
{mode === '2d' && <AmapContainer {...otherProps} />}
{/* 3D地图 - Cesium */}
{mode === '3d' && <CesiumContainer {...otherProps} />}
</div>
);
};
export default MapContainer;