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
+35
View File
@@ -0,0 +1,35 @@
# 景区地图仪表盘 - 环境变量配置示例
# 复制此文件为 .env.local 并填入实际的API Key
# ========== 地图服务配置 ==========
# 高德地图API Key(必需)
# 申请地址: https://console.amap.com/
# 1. 注册/登录高德开放平台
# 2. 进入控制台 > 应用管理 > 创建新应用
# 3. 添加Key,选择"Web端(JS API)"
# 4. 将获取的Key填入下方
REACT_APP_AMAP_KEY=
# Cesium Ion Token(可选 - 用于高级3D功能)
# Cesium是开源的,基本功能无需Token
# 如需使用Cesium Ion的高级功能(如全球地形、卫星影像),可申请Token
# 申请地址: https://cesium.com/ion/signup (国内可访问)
# 注意: 不配置此项不影响3D地图基本功能
# REACT_APP_CESIUM_TOKEN=
# ========== WebSocket服务配置 ==========
# 设备实时数据WebSocket地址
# 开发环境示例: ws://localhost:8765/device
# 预发布环境: ws://119.45.169.13:8848/device
# 生产环境示例: wss://your-domain.com/device
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
# ========== 注意事项 ==========
# 1. 所有以 REACT_APP_ 开头的变量会被打包进前端代码,请勿存储敏感信息
# 2. .env.local 文件不会被git追踪,适合存储本地开发配置
# 3. Mapbox Token 是可选的,没有此Token只影响3D地图功能
# 4. WebSocket地址在生产环境应使用WSS加密协议
# 5. 高德地图Key需要在控制台配置域名白名单
+43
View File
@@ -0,0 +1,43 @@
# 景区地图仪表盘 - 环境变量配置示例
# 复制此文件为 .env.local 并填入实际的API Key
# ========== 地图服务配置 ==========
# 高德地图API Key
# 申请地址: https://console.amap.com/
# 1. 注册/登录高德开放平台
# 2. 进入控制台 > 应用管理 > 创建新应用
# 3. 添加Key,选择"Web端(JS API)"
# 4. 将获取的Key填入下方
REACT_APP_AMAP_KEY=7df3685709e341daed76e877e417e5be
# Cesium Ion Token(可选 - 用于高级3D功能)
# Cesium是开源的,基本功能无需Token
# 如需使用Cesium Ion的高级功能(如全球地形、卫星影像),可申请Token
# 申请地址: https://cesium.com/ion/signup (国内可访问)
# 注意: 不配置此项不影响3D地图基本功能
# REACT_APP_CESIUM_TOKEN= eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5NjhjNDBlMS02OTBiLTQ5OWMtYjk3Mi04NjdiM2I4N2E4NDYiLCJpZCI6MzYxMzMzLCJpYXQiOjE3NjM0NDIxOTh9.PxIgncOzYVrDY17SWVJWD7U-9A1Wnomac8GEdcAYOeM
# ========== WebSocket服务配置 ==========
# 设备实时数据WebSocket地址
# 开发环境示例: ws://localhost:8765/device
# 生产环境示例: wss://your-domain.com/device
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
# ========== 应用配置 ==========
# 运行环境: dev | test | pre | prod
# REACT_APP_ENV=dev
# 应用基础路径(多应用部署时使用)
# APP_BASE=/mgnt
# ========== 注意事项 ==========
# 1. 所有以 REACT_APP_ 开头的变量会被打包进前端代码,请勿存储敏感信息
# 2. 生产环境建议使用环境变量或CI/CD工具注入,而非直接写入.env文件
# 3. .env.local文件不会被git追踪,适合存储本地开发配置
# 4. WebSocket地址在生产环境应使用WSS加密协议
# 5. 高德地图Key需要在控制台配置域名白名单
+12
View File
@@ -0,0 +1,12 @@
# 预发布环境配置
# 对应构建命令: npm run build:pre:mgnt
# 高德地图API Key (预发布环境 - 必需,用于2D地图)
REACT_APP_AMAP_KEY=
# Cesium Ion Token (预发布环境 - 可选,用于高级3D功能)
# Cesium基本3D功能无需Token,可留空
# REACT_APP_CESIUM_TOKEN=
# WebSocket服务地址 (预发布环境)
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
+3
View File
@@ -39,6 +39,9 @@ export default [
routes: [
{ path: '/device/wayline.html', component: '@/pages/device/Wayline' },
{ path: '/device/device.html', component: '@/pages/device/Device' },
// 景区地图仪表盘
{ path: '/device/mapDashboard.html', name: '地图仪表盘', component: '@/pages/device/mapDashboard', exact: true },
{ path: '/device/mapDashboard/tourismDeviceDetail/:tourismId', component: '@/pages/device/mapDashboard/TourismDeviceDetail' },
],
},
{
Binary file not shown.
@@ -0,0 +1,338 @@
# Cesium 三维地图说明
## 🎉 为什么选择Cesium?
### 优势对比
| 特性 | Cesium | Mapbox | 高德3D |
|------|--------|--------|--------|
| 国内访问 | ✅ 稳定 | ❌ 受限 | ✅ 稳定 |
| 开源免费 | ✅ 是 | ❌ 否 | ❌ 否 |
| 无需Token | ✅ 是 | ❌ 需要 | ✅ 是 |
| 3D效果 | ✅✅✅ 强大 | ✅✅ 较好 | ✅ 一般 |
| 地形支持 | ✅ 支持 | ✅ 支持 | ❌ 不支持 |
| 倾斜摄影 | ✅ 支持 | ❌ 不支持 | ❌ 不支持 |
### Cesium的核心优势
1. **完全开源** - MIT许可证,商业使用无限制
2. **国内可用** - 无需VPN,访问稳定
3. **无需Token** - 基础功能开箱即用
4. **功能强大** - 全球领先的3D地球引擎
5. **社区活跃** - 大量文档和示例
---
## 📦 已集成的功能
### 当前实现
✅ **基础3D地球**
- 3D球体渲染
- 流畅的视角控制
- 缩放、旋转、倾斜
✅ **景区标记**
- 3D点标记
- 文字标签
- 悬停效果
- 点击交互
✅ **地图底图**
- 使用高德瓦片地图
- 国内访问稳定
- 无缝切换2D/3D
✅ **视角飞行**
- 自动适配显示所有景区
- 平滑的飞行动画
- 最佳视角计算
✅ **UI控件**
- 主页按钮
- 2D/3D/哥伦布视图切换
- 简洁的界面
---
## 🚀 使用方法
### 1. 安装依赖
```bash
cd zlt-web/react-web-next
npm install
```
依赖会自动安装:
- `cesium@^1.110.0` - Cesium核心库
- `resium@^1.16.1` - React Cesium封装(备用)
- `@types/cesium@^1.110.0` - TypeScript类型定义
### 2. 配置环境变量
**最简配置(推荐):**
```bash
# .env.local
REACT_APP_AMAP_KEY=你的高德Key
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
# Cesium Token可选,无需配置
```
**如需高级功能:**
```bash
# 额外配置Cesium Ion Token
REACT_APP_CESIUM_TOKEN=你的Cesium Token
```
### 3. 启动项目
```bash
npm start
```
访问: http://localhost:8000/device/mapDashboard
### 4. 切换3D地图
在页面工具栏点击 **"Cesium 3D"** 按钮即可切换到3D地图。
---
## 🎨 功能特性
### 3D视图模式
Cesium提供三种视图模式:
1. **3D模式(默认)**
- 真实的3D地球
- 支持倾斜视角
- 立体感最强
2. **2D模式**
- 平面地图
- 类似传统地图
- 性能最优
3. **哥伦布视图**
- 2.5D视图
- 兼顾立体感和性能
- 适合大范围浏览
### 交互操作
**鼠标操作:**
- **左键拖拽** - 旋转地球
- **右键拖拽** - 平移视图
- **滚轮** - 缩放
- **中键拖拽** - 倾斜视角
**景区标记:**
- **点击** - 跳转到景区设备列表
- **悬停** - 标记放大,显示指针
---
## ⚙️ 高级配置
### 使用Cesium Ion Token(可选)
如需使用Cesium Ion的高级功能:
**步骤1:** 注册Cesium Ion账号
访问 https://cesium.com/ion/signup
**步骤2:** 获取Token
1. 登录后进入 https://cesium.com/ion/tokens
2. 使用默认Token或创建新Token
3. 复制Token
**步骤3:** 配置到项目
```bash
# .env.local
REACT_APP_CESIUM_TOKEN=你的Token
```
**步骤4:** 修改代码(如需使用)
在 `CesiumContainer.tsx` 中取消注释:
```typescript
// 配置Cesium Ion Token
Cesium.Ion.defaultAccessToken = process.env.REACT_APP_CESIUM_TOKEN || '';
```
### 解锁的高级功能
配置Token后可使用:
✅ **全球地形数据**
```typescript
terrainProvider: Cesium.createWorldTerrain({
requestWaterMask: true,
requestVertexNormals: true,
}),
```
✅ **Cesium OSM Buildings(全球建筑3D)**
```typescript
const buildingTileset = viewer.scene.primitives.add(
Cesium.createOsmBuildings()
);
```
✅ **Bing Maps卫星影像**
```typescript
imageryProvider: new Cesium.IonImageryProvider({ assetId: 3 }),
```
---
## 🔧 自定义配置
### 更换底图
**使用天地图:**
```typescript
imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
url: 'http://t{s}.tianditu.gov.cn/img_w/wmts?tk=你的天地图Key',
layer: 'img',
style: 'default',
format: 'tiles',
tileMatrixSetID: 'w',
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
}),
```
**使用百度地图:**
```typescript
// 需要坐标转换
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url: 'https://maponline{s}.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}',
subdomains: ['0', '1', '2', '3'],
}),
```
### 添加建筑3D
```typescript
// 使用3D Tiles
const tileset = viewer.scene.primitives.add(
new Cesium.Cesium3DTileset({
url: '你的3D Tiles URL',
})
);
```
### 优化性能
```typescript
// 启用请求渲染模式
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
// 降低细节层次
terrainProvider: Cesium.createWorldTerrain({
requestWaterMask: false, // 关闭水面
requestVertexNormals: false, // 关闭法线
}),
```
---
## 📊 性能对比
### 资源占用
| 项目 | Cesium 3D | 高德2D |
|------|-----------|--------|
| 初始加载 | ~8MB | ~2MB |
| 内存占用 | 150-300MB | 50-100MB |
| GPU占用 | 中等 | 低 |
| 适用场景 | 展示/演示 | 日常使用 |
### 优化建议
1. **大量景区时**: 使用聚合或分级显示
2. **性能受限时**: 关闭地形和建筑3D
3. **移动端**: 建议使用2D地图
---
## 🐛 常见问题
### Q1: Cesium加载慢怎么办?
**原因**: Cesium库较大(~8MB)
**解决**:
1. 使用CDN加速
2. 配置Gzip压缩
3. 使用懒加载(已实现)
### Q2: 地图显示空白?
**检查**:
1. 网络连接是否正常
2. 浏览器控制台是否有错误
3. 高德底图是否可访问
### Q3: 性能卡顿怎么办?
**优化**:
1. 关闭地形: 使用`new Cesium.EllipsoidTerrainProvider()`
2. 减少标记数量
3. 降低画质设置
### Q4: 如何使用离线地图?
**方案**:
1. 部署私有地图服务器
2. 预下载瓦片数据
3. 配置本地URL
---
## 📚 参考资源
### 官方文档
- Cesium官网: https://cesium.com/
- API文档: https://cesium.com/docs/
- 示例代码: https://sandcastle.cesium.com/
### 社区资源
- GitHub: https://github.com/CesiumGS/cesium
- 中文教程: http://cesium.xin/
- 论坛: https://community.cesium.com/
---
## 🎯 后续规划
### 待实现功能
- [ ] 景区范围多边形
- [ ] 飞行路线展示
- [ ] 设备实时位置追踪
- [ ] 历史轨迹回放
- [ ] 热力图展示
- [ ] 3D建筑模型(如有数据)
- [ ] 倾斜摄影集成(如有数据)
### 进阶功能
- [ ] 自定义shader效果
- [ ] 粒子系统(如雨雪)
- [ ] 时间动画
- [ ] 地形分析
- [ ] 视域分析
---
**最后更新:** 2025-11-18
**技术支持:** 开发团队
@@ -0,0 +1,126 @@
# 景区地图配置快速指南
## ⚡ 快速开始(只需2步)
### 1️⃣ 申请高德地图API Key
访问 https://console.amap.com/
- 注册/登录账号
- 创建应用,选择"Web端(JS API)"
- 复制生成的Key
### 2️⃣ 配置环境变量
复制 `.env.example` 为 `.env.local`:
```bash
cp .env.example .env.local
```
编辑 `.env.local`,填入你的高德地图Key:
```bash
# 必需配置
REACT_APP_AMAP_KEY=你的高德地图Key
# Cesium Token是可选的,可以留空(3D地图仍然可用)
# REACT_APP_CESIUM_TOKEN=
# WebSocket地址
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
```
### 3️⃣ 启动项目
```bash
npm install # 首次运行需要
npm start
```
访问: http://localhost:8000/device/mapDashboard
---
## 🗺️ 关于地图功能
### 当前支持的地图
✅ **高德2D地图**(必需配置)
- 国内访问稳定
- 平面地图展示
- 需配置 `REACT_APP_AMAP_KEY`
✅ **Cesium 3D地图**(无需额外配置)
- ✅ 开源免费,国内可用
- ✅ 无需Token即可使用
- ✅ 真正的3D地球展示
- ✅ 支持视角飞行
- ✅ 使用高德底图(国内稳定)
### 功能说明
**只配置高德地图Key(推荐):**
- ✅ 2D平面地图
- ✅ 3D地球地图(Cesium)
- ✅ 可自由切换2D/3D
- ✅ 景区标记正常
- ✅ 所有功能完整
**额外配置Cesium Token(可选):**
- ✅ 解锁Cesium Ion高级功能
- ✅ 全球高精度地形
- ✅ 卫星影像
- ℹ️ 基本功能无需Token
---
## 🔧 构建配置
根据你的构建命令配置环境变量:
### 预发布环境
```bash
# 编辑 .env.pre 文件
REACT_APP_AMAP_KEY=你的Key
# 构建
npm run build:pre:mgnt
```
### CI/CD配置
在GitLab/Jenkins中配置环境变量:
- `REACT_APP_AMAP_KEY` - 高德地图Key
- `REACT_APP_DEVICE_WS_URL` - WebSocket地址
---
## ❓ 常见问题
**Q: 必须配置Cesium Token吗?**
A: 不需要。Cesium基本3D功能无需Token,开箱即用。
**Q: 不配置Cesium Token会怎样?**
A: 3D地图照常工作,只是不能使用Cesium Ion的高级功能(如全球地形)。
**Q: 如何获取高德地图Key?**
A: 访问 https://console.amap.com/ 免费申请。
**Q: 高德地图需要付费吗?**
A: 有免费额度,个人开发和测试足够使用。
**Q: WebSocket地址是什么?**
A: 用于设备实时数据连接,默认使用 `ws://119.45.169.13:8848/device`
---
## 📝 总结
**最简配置(推荐):**
```bash
# .env.local
REACT_APP_AMAP_KEY=你的高德Key
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
```
只需这两个配置,系统即可正常运行!
详细配置请查看: [环境配置说明.md](环境配置说明.md)
@@ -0,0 +1,170 @@
# 环境配置说明
## 当前项目的构建命令
根据 `package.json`,项目有以下构建命令:
### 测试环境
```bash
npm run build:test # API: http://119.45.169.13:9900
npm run build:test:mgnt # 管理端,API: https://socket.goflytec.com
```
### 预发布环境(Pre)
```bash
npm run build:pre # API: http://119.45.169.13:9900
npm run build:pre:mgnt # 管理端,API: https://local.goflytec.com,BASE: /mgnt
```
### 生产环境
```bash
npm run build:prod # 生产环境
npm run build:prod:mgnt # 管理端,BASE: /mgnt
```
---
## 地图配置方案
### 快速配置(开发/测试)
**步骤1:** 复制环境变量模板
```bash
cp .env.example .env.local
```
**步骤2:** 编辑 `.env.local`,填入你的API Key
```bash
REACT_APP_AMAP_KEY=你的高德地图Key
REACT_APP_MAPBOX_TOKEN=你的Mapbox Token
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
```
**步骤3:** 启动或构建
```bash
# 开发环境
npm start
# 构建(使用你实际的构建命令)
npm run build:pre:mgnt
```
---
### 预发布环境配置
**方式1: 使用 .env.pre 文件**
编辑 `.env.pre` 文件:
```bash
REACT_APP_AMAP_KEY=你的Key
REACT_APP_MAPBOX_TOKEN=你的Token
REACT_APP_DEVICE_WS_URL=ws://119.45.169.13:8848/device
```
然后构建:
```bash
npm run build:pre:mgnt
```
**方式2: 命令行注入(推荐)**
Windows:
```cmd
set REACT_APP_AMAP_KEY=你的Key && set REACT_APP_MAPBOX_TOKEN=你的Token && npm run build:pre:mgnt
```
Linux/Mac:
```bash
REACT_APP_AMAP_KEY=你的Key REACT_APP_MAPBOX_TOKEN=你的Token npm run build:pre:mgnt
```
---
### CI/CD配置
**GitLab CI/CD 示例:**
```yaml
build:pre:
stage: build
only:
- develop
script:
- npm ci
- npm run build:pre:mgnt
variables:
REACT_APP_AMAP_KEY: $PRE_AMAP_KEY
REACT_APP_MAPBOX_TOKEN: $PRE_MAPBOX_TOKEN
artifacts:
paths:
- dist/
```
在 GitLab Settings → CI/CD → Variables 中配置:
- `PRE_AMAP_KEY`
- `PRE_MAPBOX_TOKEN`
---
## 环境变量说明
### 必需配置
- `REACT_APP_AMAP_KEY` - 高德地图API Key(必需)
- `REACT_APP_DEVICE_WS_URL` - WebSocket服务地址(必需)
### 可选配置(增强功能)
- `REACT_APP_CESIUM_TOKEN` - Cesium Ion Token(可选,用于高级3D功能)
- ✅ **无需配置**: Cesium基本3D功能无需Token,开箱即用
- ✅ **国内可用**: Cesium是开源的,国内访问正常
- 仅在需要Cesium Ion高级功能(全球地形、卫星影像)时才需要Token
### 可选配置
- `GATEWAY_ORIGIN` - API网关地址(已在构建命令中配置)
- `APP_BASE` - 应用基础路径(已在构建命令中配置)
---
## API Key 申请
### 高德地图(必需)
1. 访问 https://console.amap.com/
2. 创建应用,选择"Web端(JS API)"
3. 配置域名白名单
4. 复制Key到环境变量
### Cesium Ion Token(可选 - 高级功能)
✅ **好消息**: Cesium基本3D功能**无需Token**,开箱即用!
**Cesium基本功能(无需Token):**
- ✅ 3D地球展示
- ✅ 景区3D标记
- ✅ 视角飞行
- ✅ 2D/3D/哥伦布视图切换
- ✅ 使用高德底图(国内稳定)
**仅需Token的高级功能(可选):**
- 全球高精度地形
- Cesium Ion卫星影像
- 建筑3D Tiles
**如需Token:**
1. 访问 https://cesium.com/ion/signup (国内可访问)
2. 注册免费账号
3. 获取Access Token
4. 配置到 `REACT_APP_CESIUM_TOKEN`
**注意**: 即使不配置Token,3D地图也能正常使用!
---
## 常见问题
**Q: 构建后地图显示空白?**
A: 检查环境变量是否正确注入,查看浏览器控制台错误
**Q: 开发环境正常,构建后不正常?**
A: 确认构建时环境变量已设置,检查 `dist/` 中的代码是否包含正确的Key
---
**最后更新:** 2025-11-18
+1
View File
@@ -22,6 +22,7 @@
"@ant-design/pro-components": "1.1.1",
"@ant-design/pro-layout": "^7.22.7",
"antd": "^4.20.0",
"cesium": "^1.110.0",
"file-saver": "^2.0.5",
"jsencrypt": "^3.5.4",
"jszip": "^3.10.1",
@@ -0,0 +1,131 @@
// 横向设备列表容器
.deviceListHorizontal {
display: flex;
flex-direction: row;
gap: 12px;
overflow-x: auto;
padding: 8px 0;
&::-webkit-scrollbar {
height: 6px;
}
&::-webkit-scrollbar-thumb {
background: #d9d9d9;
border-radius: 3px;
&:hover {
background: #bfbfbf;
}
}
}
// 横向设备卡片
.deviceCardHorizontal {
min-width: 200px;
padding: 16px;
border: 2px solid #d9d9d9;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
gap: 12px;
transition: all 0.3s ease;
background: #fff;
&:hover {
border-color: #1890ff;
box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
transform: translateY(-2px);
}
&.selected {
border-color: #1890ff;
background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}
.deviceIcon {
width: 48px;
height: 48px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 24px;
flex-shrink: 0;
}
.deviceContent {
flex: 1;
min-width: 0;
.deviceName {
font-size: 14px;
font-weight: 500;
color: #262626;
margin-bottom: 8px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.deviceStatus {
font-size: 12px;
color: #8c8c8c;
}
}
}
// 视频播放器占位
.videoPlaceholder {
height: 300px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #f5f5f5;
border-radius: 4px;
p {
margin-top: 16px;
color: #999;
}
}
// 控制面板占位
.controlPlaceholder {
height: 300px;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
// 在线状态脉冲动画(绿色 - 机库在线)
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.6);
}
50% {
box-shadow: 0 0 20px 4px rgba(82, 196, 26, 0.3);
}
100% {
box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
}
}
// 无人机开机状态脉冲动画(橙色)
@keyframes pulse-orange {
0% {
box-shadow: 0 0 0 0 rgba(250, 173, 20, 0.6);
}
50% {
box-shadow: 0 0 20px 4px rgba(250, 173, 20, 0.3);
}
100% {
box-shadow: 0 0 0 0 rgba(250, 173, 20, 0);
}
}
File diff suppressed because it is too large Load Diff
@@ -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;
@@ -0,0 +1,42 @@
.mapDashboard {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
background: #000;
.toolbar {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 64px;
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
z-index: 1000;
.left {
display: flex;
align-items: center;
.title {
font-size: 18px;
font-weight: 600;
color: #000;
}
}
}
.mapWrapper {
position: absolute;
top: 64px;
left: 0;
right: 0;
bottom: 0;
}
}
@@ -0,0 +1,154 @@
import React, { useState, useEffect } from 'react';
import { Button, Space, Badge, message, Radio } from 'antd';
import {
ReloadOutlined,
FullscreenOutlined,
FullscreenExitOutlined,
GlobalOutlined,
} from '@ant-design/icons';
import { history } from 'umi';
import MapContainer from './components/MapContainer';
import { ordersApi } from '@/services/orders';
import { tenantApi } from '@/services/tenant';
import styles from './index.less';
type MapMode = '2d' | '3d';
const MapDashboard: React.FC = () => {
const [tourismList, setTourismList] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [mapMode, setMapMode] = useState<MapMode>('2d');
const [isFullscreen, setIsFullscreen] = useState(false);
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
// 首次进入时,默认按"当前租户 + 包含下级租户"查询
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) {
setParams({ tenantId, includeChildren: true });
}
} catch {
// 忽略错误
}
})();
}, []);
// 获取景区列表
const fetchTourismList = async () => {
if (!params.tenantId) {
return;
}
setLoading(true);
try {
const response = await ordersApi.tourism({
current: 1,
pageSize: 1000,
...params,
});
setTourismList(response.data || []);
} catch (error) {
message.error('获取景区列表失败');
} finally {
setLoading(false);
}
};
// 景区点击事件 - 跳转到景区设备详情页面
const handleTourismClick = (tourism: any) => {
history.push(`/device/mapDashboard/tourismDeviceDetail/${tourism.id}`, {
tourismName: tourism.tourismName,
tourism: tourism,
});
};
// 地图模式切换
const handleMapModeChange = (mode: MapMode) => {
setMapMode(mode);
message.success(`已切换到${mode === '2d' ? '二维' : '三维'}地图`);
};
// 全屏切换
const toggleFullscreen = () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
setIsFullscreen(true);
} else {
document.exitFullscreen();
setIsFullscreen(false);
}
};
// 租户ID获取后,加载景区列表
useEffect(() => {
if (params.tenantId) {
fetchTourismList();
}
}, [params.tenantId]);
return (
<div className={styles.mapDashboard}>
{/* 顶部工具栏 */}
<div className={styles.toolbar}>
<div className={styles.left}>
<span className={styles.title}>景区地图仪表盘</span>
<Badge
status="success"
text={`共${tourismList.length}个景区`}
style={{ marginLeft: 16 }}
/>
</div>
<Space size="middle">
{/* 地图模式切换 */}
<Radio.Group
value={mapMode}
onChange={(e) => handleMapModeChange(e.target.value)}
buttonStyle="solid"
>
<Radio.Button value="2d">
<GlobalOutlined /> 高德2D
</Radio.Button>
<Radio.Button value="3d">
<GlobalOutlined /> Cesium 3D
</Radio.Button>
</Radio.Group>
<Button
icon={<ReloadOutlined />}
onClick={fetchTourismList}
loading={loading}
>
刷新
</Button>
<Button
icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
onClick={toggleFullscreen}
>
{isFullscreen ? '退出全屏' : '全屏'}
</Button>
</Space>
</div>
{/* 全屏地图 */}
<div className={styles.mapWrapper}>
<MapContainer
mode={mapMode}
tourismList={tourismList}
onTourismClick={handleTourismClick}
/>
</div>
</div>
);
};
export default MapDashboard;
@@ -109,6 +109,11 @@ export const ordersApi = {
const res = await request('/api-order/tourism', { method: 'DELETE', data: { id } });
return (res as any).data || res;
},
// 根据景区ID获取设备SN列表
getDeviceSnsByTourismId: async (tourismId: number) => {
const res = await request(`/api-order/tourism/${tourismId}/device-sns`, { method: 'GET' });
return (res as any).data || [];
},
// 首页轮播
homeCarousel: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
+25
View File
@@ -0,0 +1,25 @@
// 全局类型声明
// CSS模块声明
declare module '*.css' {
const content: any;
export default content;
}
declare module '*.less' {
const content: any;
export default content;
}
// Cesium相关声明
declare module 'cesium' {
const content: any;
export = content;
}
declare module 'cesium/Build/Cesium/Widgets/widgets.css';
// 扩展Window类型
interface Window {
AMap: any;
}