TongzhouTrafficMap.vue 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. <template>
  2. <div class="map-wrapper">
  3. <div ref="mapContainer" class="map-container"></div>
  4. <div class="map-legend" :style="privateStyle.legend" v-if="(!mode || mode === '路口')"
  5. :class="{ 'legend-hidden': !legendVisible }">
  6. <div class="legend-header">
  7. <div class="legend-title">图例</div>
  8. <div class="legend-close-btn" @click="toggleLegend">✕</div>
  9. </div>
  10. <div class="legend-list">
  11. <div class="legend-item all-select" @click="toggleAll">
  12. <div class="legend-dot"
  13. :style="{ backgroundColor: isAllSelected ? '#fff' : 'transparent', border: '1px solid #fff' }"></div>
  14. <div class="legend-label" style="font-weight: bold;">全选</div>
  15. </div>
  16. <div v-for="item in legendStatusConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
  17. :class="{ 'is-inactive': !activeLegends.includes(item.name) }">
  18. <div class="legend-dot"
  19. :style="{ backgroundColor: ['离线', '降级', '故障'].includes(item.name) ? 'transparent' : item.color }"
  20. :class="{ 'special-route': ['干线协调', '勤务路线'].includes(item.name), 'is-status-wrapper': ['离线', '降级', '故障'].includes(item.name) }">
  21. <span v-if="!['离线', '降级', '故障'].includes(item.name)">
  22. {{ item.name.charAt(0) }}
  23. </span>
  24. <img v-else
  25. :src="require(`@/assets/images/icon_${item.name === '离线' ? 'lixian' : item.name === '降级' ? 'jiangji' : 'guzhang'}.png`)"
  26. class="status-icon" />
  27. </div>
  28. <div class="legend-label">{{ item.name }}</div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="legend-show-btn" v-if="(!mode || mode === '路口') && !legendVisible" @click="toggleLegend">
  33. <div class="legend-show-icon">☰</div>
  34. </div>
  35. </div>
  36. </template>
  37. <script>
  38. import AMapLoader from '@amap/amap-jsapi-loader';
  39. export default {
  40. name: "TrafficMap",
  41. props: {
  42. amapKey: { type: String, default: '您的Key' },
  43. securityJsCode: { type: String, default: '您的安全密钥' },
  44. mode: { type: String, default: '', validator: (value) => ['', '路口', '干线', '特勤'].includes(value) }
  45. },
  46. data() {
  47. return {
  48. AMap: null,
  49. map: null,
  50. infoWindow: null,
  51. routeGroups: {},
  52. polylines: [],
  53. privateStyle: {
  54. legend: {}
  55. },
  56. legendVisible: true,
  57. activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"],
  58. // 核心修正:增加生命周期标识,防止组件销毁后异步回调继续执行
  59. isComponentDestroyed: false,
  60. drawSeq: 0,
  61. driving: null,
  62. // 状态类型配置
  63. statusConfig: [
  64. { name: "中心计划", color: "#004CDE", type: "normal" },
  65. { name: "干线协调", color: "#13C373", type: "route" },
  66. { name: "勤务路线", color: "#BC301D", type: "route" },
  67. { name: "定周期控制", color: "#3296FA", type: "normal" },
  68. { name: "感应控制", color: "#FF864C", type: "normal" },
  69. { name: "自适应控制", color: "#9F6EFE", type: "normal" },
  70. { name: "手动控制", color: "#EB9F36", type: "normal" },
  71. { name: "特殊控制", color: "#A26218", type: "normal" },
  72. { name: "离线", color: "#7A7A7A", type: "abnormal" },
  73. { name: "降级", color: "#D9C13B", type: "abnormal" },
  74. { name: "故障", color: "#FF3938", type: "abnormal" }
  75. ],
  76. // 真实路口数据
  77. intersectionData: [],
  78. // 按状态分类的路口数据
  79. statusIntersections: {},
  80. };
  81. },
  82. mounted() {
  83. this.isComponentDestroyed = false; // 重置标识
  84. this.loadMapData().then(() => {
  85. this.classifyIntersectionsByStatus();
  86. this.updateMapByMode();
  87. this.initAMap();
  88. });
  89. if (this.$route.path === '/home') {
  90. this.privateStyle.legend = { right: "25%" };
  91. }
  92. },
  93. watch: {
  94. mode: {
  95. handler() {
  96. this.updateMapByMode();
  97. this.updateMapDisplay();
  98. },
  99. immediate: false
  100. }
  101. },
  102. beforeDestroy() {
  103. // 1. 立即设置销毁状态
  104. this.isComponentDestroyed = true;
  105. this.drawSeq += 1;
  106. // 2. 关闭弹窗
  107. if (this.infoWindow) {
  108. try {
  109. this.infoWindow.close();
  110. } catch (e) {
  111. console.warn('关闭信息窗口时出错:', e);
  112. }
  113. this.infoWindow = null;
  114. }
  115. // 3. 清理覆盖物引用
  116. if (this.routeGroups) {
  117. Object.values(this.routeGroups).forEach(overlays => {
  118. if (Array.isArray(overlays)) {
  119. overlays.forEach(o => {
  120. try {
  121. if (o.setMap) o.setMap(null);
  122. } catch (e) {
  123. console.warn('清理覆盖物时出错:', e);
  124. }
  125. });
  126. }
  127. });
  128. this.routeGroups = {};
  129. }
  130. // 4. 销毁地图实例并清空引用
  131. if (this.map) {
  132. try {
  133. this.map.destroy();
  134. } catch (e) {
  135. console.warn('销毁地图实例时出错:', e);
  136. }
  137. this.map = null;
  138. }
  139. // 5. 清理其他引用
  140. this.AMap = null;
  141. this.driving = null;
  142. },
  143. computed: {
  144. isAllSelected() {
  145. return this.activeLegends.length === this.statusConfig.length;
  146. },
  147. legendStatusConfig() {
  148. if (!this.mode) return this.statusConfig;
  149. if (this.mode === '路口') {
  150. return this.statusConfig.filter(item => !['干线协调', '勤务路线'].includes(item.name));
  151. }
  152. return [];
  153. }
  154. },
  155. methods: {
  156. // 动态加载地图数据
  157. async loadMapData() {
  158. try {
  159. const mapDataModule = await import('@/mock/map_data_gaode.json');
  160. this.intersectionData = mapDataModule.default || [];
  161. console.log('地图数据加载成功,共', this.intersectionData.length, '个路口');
  162. } catch (error) {
  163. console.error('地图数据加载失败:', error);
  164. this.intersectionData = [];
  165. }
  166. },
  167. // 检查地图环境是否安全可用
  168. isMapReady() {
  169. return !this.isComponentDestroyed && this.map && typeof this.map.add === 'function';
  170. },
  171. // 将真实路口数据按状态类型分类
  172. classifyIntersectionsByStatus() {
  173. const remainingData = this.intersectionData;
  174. const normalStatusCount = 6;
  175. const abnormalStatusCount = 3;
  176. const chunkSize = Math.floor(remainingData.length / (normalStatusCount + abnormalStatusCount));
  177. const maxAbnormalCount = 10;
  178. this.statusIntersections = {
  179. "中心计划": remainingData.slice(0, 20),
  180. "干线协调": [], // 清空,改为动态生成
  181. "勤务路线": [], // 清空,改为动态生成
  182. "定周期控制": remainingData.slice(chunkSize, chunkSize * 2),
  183. "感应控制": remainingData.slice(chunkSize * 2, chunkSize * 3),
  184. "自适应控制": remainingData.slice(chunkSize * 3, chunkSize * 4),
  185. "手动控制": remainingData.slice(chunkSize * 4, chunkSize * 5),
  186. "特殊控制": remainingData.slice(chunkSize * 5, chunkSize * 6),
  187. "离线": remainingData.slice(chunkSize * 6, Math.min(chunkSize * 7, chunkSize * 6 + maxAbnormalCount)),
  188. "降级": remainingData.slice(chunkSize * 7, Math.min(chunkSize * 8, chunkSize * 7 + maxAbnormalCount)),
  189. "故障": remainingData.slice(chunkSize * 8, Math.min(chunkSize * 9, chunkSize * 8 + maxAbnormalCount))
  190. };
  191. },
  192. updateMapByMode() {
  193. switch (this.mode) {
  194. case '路口':
  195. this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"];
  196. break;
  197. case '干线':
  198. this.activeLegends = ["干线协调"];
  199. break;
  200. case '特勤':
  201. this.activeLegends = ["勤务路线"];
  202. break;
  203. default:
  204. this.activeLegends = this.statusConfig.map(item => item.name);
  205. }
  206. },
  207. updateMapDisplay() {
  208. if (this.infoWindow) this.infoWindow.close();
  209. if (!this.isMapReady()) return;
  210. Object.keys(this.routeGroups).forEach(name => {
  211. const overlays = this.routeGroups[name];
  212. if (overlays && overlays.length > 0) {
  213. if (this.activeLegends.includes(name)) {
  214. this.map.add(overlays);
  215. } else {
  216. this.map.remove(overlays);
  217. }
  218. }
  219. });
  220. },
  221. async initAMap() {
  222. if (this.isComponentDestroyed) return;
  223. // 确保在加载前注入
  224. window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
  225. try {
  226. const AMap = await AMapLoader.load({
  227. key: this.amapKey,
  228. version: "2.0",
  229. // 核心:确保 Driving 插件在此加载
  230. plugins: ['AMap.Driving']
  231. });
  232. if (this.isComponentDestroyed) return;
  233. this.AMap = AMap;
  234. this.map = new AMap.Map(this.$refs.mapContainer, {
  235. zoom: 15,
  236. mapStyle: "amap://styles/darkblue",
  237. center: [116.663, 39.905], // 通州区中心
  238. });
  239. this.driving = new AMap.Driving({ map: null, hideMarkers: true });
  240. // 建议在地图加载完成后再画线
  241. this.map.on('complete', () => {
  242. if (!this.isComponentDestroyed) {
  243. this.drawStaticRoutes();
  244. // 临时方案,实际项目中删除 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
  245. this.storeStatusCoordsToLocalStorage();
  246. }
  247. });
  248. } catch (err) {
  249. console.error('地图加载失败:', err);
  250. }
  251. },
  252. // 绘制静态路线和标记
  253. // 对于普通状态,从 mock 数据加载路口标记
  254. // 对于路线类(干线协调和勤务路线),使用高德地图路线规划绘制路线和密集点位
  255. async drawStaticRoutes() {
  256. if (!this.isMapReady()) return;
  257. this.drawSeq += 1;
  258. const drawSeq = this.drawSeq;
  259. this.clearAllRouteOverlays();
  260. const realRouteConfigs = {
  261. "干线协调": [
  262. { start: [116.6421, 39.9172], end: [116.6825, 39.9172], color: "#13C373" },
  263. { start: [116.6426, 39.9121], end: [116.6830, 39.9121], color: "#13C373" },
  264. { start: [116.6432, 39.9071], end: [116.6833, 39.9071], color: "#13C373" },
  265. { start: [116.6438, 39.9023], end: [116.6841, 39.9023], color: "#13C373" },
  266. { start: [116.6445, 39.8975], end: [116.6846, 39.8975], color: "#13C373" }
  267. ],
  268. "勤务路线": [
  269. { start: [116.6400, 39.9225], end: [116.6400, 39.8971], color: "#BC301D" },
  270. { start: [116.6465, 39.9225], end: [116.6465, 39.8971], color: "#BC301D" },
  271. { start: [116.6521, 39.9225], end: [116.6521, 39.8971], color: "#BC301D" },
  272. { start: [116.6620, 39.9225], end: [116.6620, 39.8971], color: "#BC301D" },
  273. { start: [116.6734, 39.9225], end: [116.6734, 39.8971], color: "#BC301D" },
  274. { start: [116.6790, 39.9225], end: [116.6790, 39.8971], color: "#BC301D" },
  275. { start: [116.6850, 39.9170], end: [116.6850, 39.9000], color: "#BC301D" }
  276. ]
  277. };
  278. for (const config of this.statusConfig) {
  279. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  280. // 1. 处理普通非路线状态(从 mock 数据加载)
  281. if (!realRouteConfigs[config.name]) {
  282. const intersections = this.statusIntersections[config.name] || [];
  283. const markers = intersections.map(item =>
  284. this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], config)
  285. ).filter(Boolean);
  286. this.routeGroups[config.name] = markers;
  287. if (this.activeLegends.includes(config.name)) this.map.add(markers);
  288. continue;
  289. }
  290. // 2. 处理路线类(干线/特勤)
  291. this.routeGroups[config.name] = [];
  292. const lines = realRouteConfigs[config.name] || [];
  293. for (let lineIdx = 0; lineIdx < lines.length; lineIdx += 1) {
  294. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  295. const line = lines[lineIdx];
  296. let path = null;
  297. try {
  298. path = await this.searchDrivingPathWithRetry(line.start, line.end);
  299. } catch (e) {
  300. path = null;
  301. }
  302. const overlays = this.buildRouteOverlaysFromPath({
  303. config,
  304. configName: config.name,
  305. line,
  306. lineIdx,
  307. path
  308. });
  309. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  310. if (overlays.length > 0) {
  311. this.routeGroups[config.name].push(...overlays);
  312. if (this.activeLegends.includes(config.name)) this.map.add(overlays);
  313. }
  314. await this.sleep(80);
  315. }
  316. }
  317. },
  318. clearAllRouteOverlays() {
  319. if (!this.isMapReady()) return;
  320. try {
  321. if (this.infoWindow) this.infoWindow.close();
  322. } catch (e) {
  323. void e;
  324. }
  325. Object.values(this.routeGroups || {}).forEach(overlays => {
  326. if (!Array.isArray(overlays) || overlays.length === 0) return;
  327. try {
  328. this.map.remove(overlays);
  329. } catch (e) {
  330. void e;
  331. }
  332. overlays.forEach(o => {
  333. try {
  334. if (o && typeof o.setMap === 'function') o.setMap(null);
  335. } catch (e) {
  336. void e;
  337. }
  338. });
  339. });
  340. this.routeGroups = {};
  341. },
  342. sleep(ms) {
  343. return new Promise(resolve => setTimeout(resolve, ms));
  344. },
  345. async searchDrivingPathWithRetry(start, end) {
  346. if (!this.AMap || !this.driving || typeof this.driving.search !== 'function') {
  347. throw new Error('Driving not ready');
  348. }
  349. const maxAttempts = 3;
  350. let lastErr = null;
  351. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
  352. try {
  353. return await this.withTimeout(this.searchDrivingPathOnce(start, end), 8000);
  354. } catch (e) {
  355. lastErr = e;
  356. await this.sleep(250 * attempt);
  357. }
  358. }
  359. throw lastErr || new Error('Driving search failed');
  360. },
  361. searchDrivingPathOnce(start, end) {
  362. return new Promise((resolve, reject) => {
  363. this.driving.search(start, end, (status, result) => {
  364. const route = result && result.routes && result.routes[0];
  365. if (status === 'complete' && route && Array.isArray(route.steps)) {
  366. const fullPath = [];
  367. route.steps.forEach(step => {
  368. if (step && Array.isArray(step.path)) fullPath.push(...step.path);
  369. });
  370. if (fullPath.length >= 2) resolve(fullPath);
  371. else reject(new Error('empty_path'));
  372. return;
  373. }
  374. reject(new Error(typeof status === 'string' ? status : 'driving_error'));
  375. });
  376. });
  377. },
  378. withTimeout(promise, timeoutMs) {
  379. return Promise.race([
  380. promise,
  381. new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
  382. ]);
  383. },
  384. buildRouteOverlaysFromPath({ config, configName, line, lineIdx, path }) {
  385. if (!this.AMap || !this.map) return [];
  386. let basePath = path;
  387. if (!Array.isArray(basePath) || basePath.length < 2) {
  388. basePath = this.buildFallbackLinePath(line.start, line.end, 30);
  389. }
  390. const segments = this.extractMainStraightSegments(basePath);
  391. const overlays = [];
  392. segments.forEach((segmentPath, segmentIdx) => {
  393. if (!Array.isArray(segmentPath) || segmentPath.length < 2) return;
  394. const polyline = new this.AMap.Polyline({
  395. path: segmentPath,
  396. strokeColor: line.color,
  397. strokeWeight: 6,
  398. strokeOpacity: 0.8,
  399. zIndex: 15
  400. });
  401. overlays.push(polyline);
  402. const totalPoints = segmentPath.length;
  403. const indices = this.pickEvenlySpacedIndices(totalPoints, 8);
  404. for (const i of indices) {
  405. const p = segmentPath[i];
  406. const lng = p && typeof p.lng === 'number' ? p.lng : (Array.isArray(p) ? Number(p[0]) : NaN);
  407. const lat = p && typeof p.lat === 'number' ? p.lat : (Array.isArray(p) ? Number(p[1]) : NaN);
  408. if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
  409. const marker = this.createTrafficLightMarker([lng, lat], {
  410. ...config,
  411. id: `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${i}`,
  412. road: `${configName}路口-${lineIdx}-${segmentIdx}-${i}`
  413. });
  414. if (marker) overlays.push(marker);
  415. }
  416. });
  417. return overlays;
  418. },
  419. pickEvenlySpacedIndices(totalPoints, count) {
  420. const total = Math.max(Number(totalPoints) || 0, 0);
  421. const target = Math.max(Number(count) || 0, 0);
  422. if (total <= 0) return [];
  423. if (target <= 0) return [];
  424. if (target >= total) return Array.from({ length: total }, (_, i) => i);
  425. if (target === 1) return [0];
  426. const set = new Set();
  427. const last = total - 1;
  428. for (let k = 0; k < target; k += 1) {
  429. const idx = Math.round((k * last) / (target - 1));
  430. set.add(idx);
  431. }
  432. return Array.from(set).sort((a, b) => a - b);
  433. },
  434. buildFallbackLinePath(start, end, pointCount) {
  435. const sLng = Number(start && start[0]);
  436. const sLat = Number(start && start[1]);
  437. const eLng = Number(end && end[0]);
  438. const eLat = Number(end && end[1]);
  439. const n = Math.max(Number(pointCount) || 2, 2);
  440. const path = [];
  441. if ([sLng, sLat, eLng, eLat].some(v => Number.isNaN(v))) return path;
  442. for (let i = 0; i < n; i += 1) {
  443. const t = n === 1 ? 0 : i / (n - 1);
  444. const lng = sLng + (eLng - sLng) * t;
  445. const lat = sLat + (eLat - sLat) * t;
  446. path.push({ lng, lat });
  447. }
  448. return path;
  449. },
  450. extractMainStraightSegments(path) {
  451. const points = (path || []).filter(p => p && typeof p.lng === 'number' && typeof p.lat === 'number');
  452. if (points.length < 2) return [];
  453. const thresholdDeg = 18;
  454. const segments = [];
  455. let curStart = 0;
  456. let curAngle = null;
  457. let curLen = 0;
  458. const pushSegment = (endIdx) => {
  459. if (endIdx <= curStart) return;
  460. segments.push({
  461. start: curStart,
  462. end: endIdx,
  463. len: curLen
  464. });
  465. };
  466. for (let i = 0; i < points.length - 1; i += 1) {
  467. const a = points[i];
  468. const b = points[i + 1];
  469. const len = this.calcApproxDistance(a, b);
  470. if (len <= 0) continue;
  471. const angle = this.calcBearingDeg(a, b);
  472. if (curAngle === null) {
  473. curStart = i;
  474. curAngle = angle;
  475. curLen = len;
  476. continue;
  477. }
  478. const diff = this.calcAngleDiffDeg(curAngle, angle);
  479. if (diff <= thresholdDeg) {
  480. curLen += len;
  481. } else {
  482. pushSegment(i);
  483. curStart = i;
  484. curAngle = angle;
  485. curLen = len;
  486. }
  487. }
  488. pushSegment(points.length - 2);
  489. if (segments.length === 0) return [points];
  490. segments.sort((s1, s2) => s2.len - s1.len);
  491. const maxLen = segments[0].len || 0;
  492. const filtered = segments.filter(s => s.len >= maxLen * 0.55).slice(0, 3);
  493. const finalSegments = filtered.map(s => points.slice(s.start, s.end + 2));
  494. return finalSegments.length > 0 ? finalSegments : [points];
  495. },
  496. calcBearingDeg(a, b) {
  497. const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
  498. const dx = (b.lng - a.lng) * Math.cos(latRad);
  499. const dy = (b.lat - a.lat);
  500. let deg = Math.atan2(dy, dx) * 180 / Math.PI;
  501. if (deg < 0) deg += 360;
  502. return deg;
  503. },
  504. calcAngleDiffDeg(a, b) {
  505. let diff = Math.abs(a - b);
  506. if (diff > 180) diff = 360 - diff;
  507. return diff;
  508. },
  509. calcApproxDistance(a, b) {
  510. const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
  511. const dx = (b.lng - a.lng) * Math.cos(latRad);
  512. const dy = (b.lat - a.lat);
  513. return Math.sqrt(dx * dx + dy * dy);
  514. },
  515. createTrafficLightMarker(position, config, type = 'normal') {
  516. if (!position || !config) return null;
  517. try {
  518. const lng = Number(position[0] || position.lng);
  519. const lat = Number(position[1] || position.lat);
  520. if (isNaN(lng) || isNaN(lat)) return null;
  521. // 状态文字:起、终、或者状态配置的首字母
  522. let displayText = config.name ? config.name.charAt(0) : '';
  523. if (type === 'start') displayText = '起';
  524. if (type === 'end') displayText = '终';
  525. const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
  526. const isRoute = ["干线协调", "勤务路线"].includes(config.name);
  527. // 动态计算尺寸:起终点最大,异常点次之,普通点最小
  528. const size = (type === 'start' || type === 'end') ? '22px' : (isAbnormal ? '30px' : '14px');
  529. const sizeNumber = parseInt(size, 10);
  530. const paddingNumber = (isAbnormal || type === 'start' || type === 'end') ? 0 : 2;
  531. const outerSizeNumber = sizeNumber + paddingNumber * 2;
  532. // 边框样式:起终点用实白边框
  533. const borderStyle = (type === 'start' || type === 'end')
  534. ? '2px solid #fff'
  535. : '1.5px solid rgba(255,255,255,0.7)';
  536. // 生成异常状态的图标路径
  537. let markerContent = '';
  538. if (isAbnormal) {
  539. const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
  540. markerContent = `
  541. <div class="pure-light-node ${isAbnormal ? 'breathe' : ''}"
  542. style="
  543. width: ${size};
  544. height: ${size};
  545. background: transparent;
  546. box-shadow: none;
  547. border: none;
  548. box-sizing: content-box;
  549. display: flex;
  550. justify-content: center;
  551. align-items: center;
  552. cursor: pointer;
  553. padding: ${paddingNumber}px;
  554. ">
  555. <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
  556. </div>
  557. `;
  558. } else {
  559. markerContent = `
  560. <div class="pure-light-node ${isAbnormal ? 'breathe' : ''} ${isRoute ? 'route-node' : ''}"
  561. style="
  562. width: ${size};
  563. height: ${size};
  564. background: ${config.color || '#999'};
  565. box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`};
  566. border: ${isRoute ? 'none' : borderStyle};
  567. box-sizing: content-box;
  568. display: flex;
  569. justify-content: center;
  570. align-items: center;
  571. color: #fff;
  572. border-radius: 50%;
  573. cursor: pointer;
  574. padding: ${paddingNumber}px;
  575. ">
  576. <span style="transform: scale(0.8); font-weight: bold; font-size: 12px;">${displayText}</span>
  577. </div>
  578. `;
  579. }
  580. const marker = new this.AMap.Marker({
  581. position: [lng, lat],
  582. // 这里的 type 已经从参数拿到了,不会报错了
  583. zIndex: (type === 'start' || type === 'end') ? 120 : (isAbnormal ? 110 : 100),
  584. content: markerContent,
  585. offset: new this.AMap.Pixel(-Math.round(outerSizeNumber / 2), -Math.round(outerSizeNumber / 2)),
  586. extData: {
  587. ...config,
  588. position: [lng, lat],
  589. statusColor: config.color || '#999',
  590. statusLabel: isAbnormal ? config.name : "正常运行",
  591. road: config.road || '规划路口',
  592. timestamp: Date.now(),
  593. time: this.formatEventTime(Date.now())
  594. }
  595. });
  596. marker.on('click', (e) => {
  597. if (!this.isComponentDestroyed) {
  598. this.openLightInfo(e.target.getExtData(), e.lnglat);
  599. this.$emit('map-crossing-click', e.target.getExtData(), e.lnglat);
  600. }
  601. });
  602. return marker;
  603. } catch (e) {
  604. console.warn('创建标记时出错:', e);
  605. return null;
  606. }
  607. },
  608. openLightInfo(data, position) {
  609. if (!this.isMapReady()) return;
  610. const infoWindowId = `info-window-${Date.now()}`;
  611. const isAbnormal = ["离线", "降级", "故障"].includes(data.name);
  612. const deviceStatusText = isAbnormal ? data.name : '正常';
  613. const alarmInfoText = isAbnormal ? this.getAlarmInfoText(data.name) : '';
  614. const eventTimeText = this.formatEventTime(data.timestamp || data.time);
  615. let statusDotContent = '';
  616. if (isAbnormal) {
  617. const iconName = data.name === '离线' ? 'lixian' : data.name === '降级' ? 'jiangji' : 'guzhang';
  618. statusDotContent = `<img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />`;
  619. } else {
  620. statusDotContent = `<span>${data.name.charAt(0)}</span>`;
  621. }
  622. const content = `
  623. <div class="custom-info-card" id="${infoWindowId}">
  624. <div class="close-btn" data-id="${infoWindowId}">✕</div>
  625. <div class="card-header">
  626. <div class="status-dot ${isAbnormal ? 'breathe' : ''}" style="background: ${isAbnormal ? 'transparent' : data.statusColor}; border: ${isAbnormal ? 'none' : ''}">
  627. ${statusDotContent}
  628. </div>
  629. <span class="status-text">${data.statusLabel}</span>
  630. </div>
  631. <div class="card-body">
  632. ${isAbnormal
  633. ? `
  634. <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
  635. <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
  636. <div class="info-line"><span class="label">报警信息:</span><span class="value">${alarmInfoText}</span></div>
  637. <div class="info-line"><span class="label">发生时间:</span><span class="value digital">${eventTimeText}</span></div>
  638. `
  639. : `
  640. <div class="info-line"><span class="label">中(干/勤/定/感/自/手/特):</span><span class="value">${data.name}</span></div>
  641. <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
  642. <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
  643. `
  644. }
  645. </div>
  646. </div>
  647. `;
  648. if (!this.infoWindow) {
  649. this.infoWindow = new this.AMap.InfoWindow({
  650. isCustom: true,
  651. offset: new this.AMap.Pixel(0, -20)
  652. });
  653. }
  654. this.infoWindow.setContent(content);
  655. this.infoWindow.open(this.map, position);
  656. // 添加关闭按钮事件监听器
  657. setTimeout(() => {
  658. const closeBtn = document.querySelector(`#${infoWindowId} .close-btn`);
  659. if (closeBtn) {
  660. closeBtn.addEventListener('click', () => {
  661. if (this.infoWindow) this.infoWindow.close();
  662. });
  663. }
  664. }, 100);
  665. },
  666. getAlarmInfoText(statusName) {
  667. if (statusName === '离线') return '通讯中断设备离线';
  668. if (statusName === '降级') return '降级定周期控制';
  669. if (statusName === '故障') return '东向左转信号灯红绿同亮';
  670. return '设备异常';
  671. },
  672. formatEventTime(input) {
  673. let d = null;
  674. if (input instanceof Date) d = input;
  675. else if (typeof input === 'number') d = new Date(input);
  676. else if (typeof input === 'string') {
  677. const t = Date.parse(input);
  678. if (!Number.isNaN(t)) d = new Date(t);
  679. }
  680. if (!d || Number.isNaN(d.getTime())) d = new Date();
  681. const y = d.getFullYear();
  682. const m = d.getMonth() + 1;
  683. const day = d.getDate();
  684. const hh = String(d.getHours()).padStart(2, '0');
  685. const mm = String(d.getMinutes()).padStart(2, '0');
  686. return `${y}.${m}.${day} ${hh}:${mm}`;
  687. },
  688. toggleAll() {
  689. const targetState = !this.isAllSelected;
  690. if (!this.isMapReady()) return;
  691. if (targetState) {
  692. this.activeLegends = this.statusConfig.map(item => item.name);
  693. Object.values(this.routeGroups).forEach(overlays => {
  694. if (overlays && overlays.length > 0) this.map.add(overlays);
  695. });
  696. } else {
  697. this.activeLegends = [];
  698. Object.values(this.routeGroups).forEach(overlays => {
  699. if (overlays && overlays.length > 0) this.map.remove(overlays);
  700. });
  701. if (this.infoWindow) this.infoWindow.close();
  702. }
  703. },
  704. toggleRouteVisible(name) {
  705. if (!this.isMapReady()) return;
  706. const overlays = this.routeGroups[name] || [];
  707. const index = this.activeLegends.indexOf(name);
  708. if (index > -1) {
  709. this.activeLegends.splice(index, 1);
  710. this.map.remove(overlays);
  711. if (this.infoWindow) this.infoWindow.close();
  712. } else {
  713. this.activeLegends.push(name);
  714. this.map.add(overlays);
  715. }
  716. },
  717. focusByLocation(targetPos) {
  718. if (!this.isMapReady() || !targetPos || targetPos.length !== 2) return;
  719. let foundMarker = null;
  720. Object.values(this.routeGroups).forEach(group => {
  721. const marker = group.find(item => {
  722. if (!(item instanceof this.AMap.Marker)) return false;
  723. const pos = item.getExtData().position;
  724. return Math.abs(pos[0] - targetPos[0]) < 0.0001 && Math.abs(pos[1] - targetPos[1]) < 0.0001;
  725. });
  726. if (marker) foundMarker = marker;
  727. });
  728. if (foundMarker) {
  729. const finalPos = foundMarker.getPosition();
  730. this.map.setZoomAndCenter(17, finalPos, false, 500);
  731. setTimeout(() => {
  732. if (!this.isComponentDestroyed) this.openLightInfo(foundMarker.getExtData(), finalPos);
  733. }, 600);
  734. }
  735. },
  736. toggleLegend() {
  737. this.legendVisible = !this.legendVisible;
  738. },
  739. // 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
  740. storeStatusCoordsToLocalStorage() {
  741. // 故障、离线、降级坐标点(按4:3:3比例)
  742. const faultCoords = [
  743. [116.723317, 39.907606],
  744. [116.703624, 39.89801],
  745. [116.661252, 39.924948],
  746. [116.708958, 39.899609]
  747. ];
  748. const offlineCoords = [
  749. [116.677855, 39.895636],
  750. [116.656673, 39.856063],
  751. [116.656485, 39.90118]
  752. ];
  753. const degradedCoords = [
  754. [116.713356, 39.952856],
  755. [116.665391, 39.934546],
  756. [116.697784, 39.891312]
  757. ];
  758. // 组合成10个元素的数组
  759. const statusCoords = [...faultCoords, ...offlineCoords, ...degradedCoords];
  760. // 存储到localStorage
  761. statusCoords.forEach((coords, index) => {
  762. localStorage.setItem(`pos${index + 1}`, coords.join(','));
  763. });
  764. console.log('状态坐标已存储到localStorage');
  765. }
  766. }
  767. };
  768. </script>
  769. <style scoped>
  770. .map-wrapper {
  771. width: 100%;
  772. height: 100vh;
  773. position: relative;
  774. background: #010813;
  775. }
  776. .map-container {
  777. width: 100%;
  778. height: 100%;
  779. }
  780. ::v-deep .pure-light-node.breathe {
  781. animation: light-breathe 2s infinite ease-in-out;
  782. }
  783. ::v-deep .pure-light-node span {
  784. display: flex;
  785. transform: scale(0.75);
  786. align-items: center;
  787. }
  788. ::v-deep .pure-light-node:hover {
  789. transform: scale(1.4);
  790. filter: brightness(1.2);
  791. }
  792. @keyframes light-breathe {
  793. 0% {
  794. transform: scale(0.9);
  795. opacity: 0.8;
  796. }
  797. 50% {
  798. transform: scale(1.1);
  799. opacity: 1;
  800. }
  801. 100% {
  802. transform: scale(0.9);
  803. opacity: 0.8;
  804. }
  805. }
  806. ::v-deep .close-btn {
  807. position: absolute;
  808. top: 10px;
  809. right: 12px;
  810. color: #8da6c7;
  811. cursor: pointer;
  812. font-size: 16px;
  813. transition: color 0.3s;
  814. line-height: 1;
  815. z-index: 10;
  816. }
  817. ::v-deep .close-btn:hover {
  818. color: #ffffff;
  819. }
  820. ::v-deep .custom-info-card {
  821. position: relative;
  822. background: rgba(10, 15, 24, 0.95);
  823. border-radius: 10px;
  824. padding: 12px 16px;
  825. min-width: 200px;
  826. border: 1px solid rgba(255, 255, 255, 0.1);
  827. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  828. color: #fff;
  829. }
  830. ::v-deep .card-header {
  831. display: flex;
  832. align-items: center;
  833. margin-bottom: 10px;
  834. }
  835. ::v-deep .status-dot {
  836. width: 30px;
  837. height: 30px;
  838. border-radius: 50%;
  839. display: flex;
  840. justify-content: center;
  841. align-items: center;
  842. margin-right: 8px;
  843. font-size: 14px;
  844. padding: 0;
  845. box-sizing: border-box;
  846. }
  847. ::v-deep .status-dot.breathe {
  848. animation: light-breathe 2s infinite ease-in-out;
  849. }
  850. ::v-deep .status-dot span {
  851. transform: scale(0.75);
  852. }
  853. ::v-deep .status-dot img {
  854. width: 100%;
  855. height: 100%;
  856. object-fit: contain;
  857. display: block;
  858. }
  859. ::v-deep .status-text {
  860. font-size: 15px;
  861. font-weight: bold;
  862. }
  863. ::v-deep .info-line {
  864. display: flex;
  865. margin-bottom: 6px;
  866. font-size: 13px;
  867. align-items: center;
  868. }
  869. ::v-deep .label {
  870. color: #8da6c7;
  871. white-space: nowrap;
  872. }
  873. ::v-deep .value {
  874. color: #ffffff;
  875. }
  876. ::v-deep .digital {
  877. font-family: 'Consolas', monospace;
  878. }
  879. .map-legend {
  880. position: absolute;
  881. bottom: 30px;
  882. right: 40px;
  883. background: rgba(5, 22, 45, 0.9);
  884. border: 1px solid #1e4d8e;
  885. padding: 15px;
  886. border-radius: 6px;
  887. z-index: 100;
  888. transition: all 0.3s ease-in-out;
  889. opacity: 1;
  890. max-width: 200px;
  891. overflow: hidden;
  892. }
  893. .map-legend.legend-hidden {
  894. opacity: 0;
  895. transform: translateX(calc(100% + 20px));
  896. pointer-events: none;
  897. }
  898. .legend-header {
  899. display: flex;
  900. justify-content: space-between;
  901. align-items: center;
  902. margin-bottom: 12px;
  903. border-bottom: 1px solid #1e4d8e;
  904. padding-bottom: 8px;
  905. }
  906. .legend-close-btn {
  907. color: #8da6c7;
  908. cursor: pointer;
  909. font-size: 16px;
  910. transition: color 0.3s;
  911. line-height: 1;
  912. }
  913. .legend-close-btn:hover {
  914. color: #ffffff;
  915. }
  916. .legend-show-btn {
  917. position: absolute;
  918. bottom: 30px;
  919. right: 20px;
  920. background: rgba(5, 22, 45, 0.9);
  921. border: 1px solid #1e4d8e;
  922. width: 40px;
  923. height: 40px;
  924. border-radius: 6px 0 0 6px;
  925. display: flex;
  926. justify-content: center;
  927. align-items: center;
  928. cursor: pointer;
  929. z-index: 99;
  930. transition: all 0.3s ease-in-out;
  931. }
  932. .legend-show-btn:hover {
  933. background: rgba(10, 30, 60, 0.9);
  934. border-color: #3a75c4;
  935. }
  936. .legend-show-icon {
  937. color: #8da6c7;
  938. font-size: 18px;
  939. transition: color 0.3s;
  940. }
  941. .legend-show-btn:hover .legend-show-icon {
  942. color: #ffffff;
  943. }
  944. .legend-title {
  945. color: #fff;
  946. font-size: 14px;
  947. }
  948. .legend-item {
  949. display: flex;
  950. align-items: center;
  951. margin-bottom: 10px;
  952. cursor: pointer;
  953. transition: 0.3s;
  954. }
  955. .legend-item.is-inactive {
  956. opacity: 0.2;
  957. filter: grayscale(1);
  958. }
  959. .legend-dot {
  960. margin-right: 10px;
  961. display: flex;
  962. justify-content: center;
  963. align-items: center;
  964. }
  965. .legend-dot:not(.is-status-wrapper) {
  966. width: 20px;
  967. height: 20px;
  968. border-radius: 50%;
  969. }
  970. .legend-dot span {
  971. display: inline-block;
  972. width: 20px;
  973. height: 20px;
  974. font-size: 12px;
  975. color: #FFF;
  976. text-align: center;
  977. transform: scale(0.75);
  978. line-height: 20px;
  979. }
  980. .legend-dot.special-route {
  981. position: relative;
  982. overflow: visible !important;
  983. z-index: 1;
  984. border: none !important;
  985. border-radius: 50%;
  986. }
  987. .legend-dot.special-route span {
  988. position: relative;
  989. z-index: 3;
  990. font-weight: bold;
  991. }
  992. .legend-dot.special-route::after {
  993. content: "";
  994. position: absolute;
  995. top: 50%;
  996. left: 50%;
  997. width: 150%;
  998. height: 3px;
  999. background-color: inherit;
  1000. opacity: 0.8;
  1001. transform: translate(-50%, -50%) rotate(-45deg);
  1002. pointer-events: none;
  1003. z-index: 0;
  1004. }
  1005. .legend-dot.special-route::before {
  1006. content: "";
  1007. position: absolute;
  1008. top: 0;
  1009. left: 0;
  1010. width: 100%;
  1011. height: 100%;
  1012. border-radius: 50%;
  1013. z-index: 2;
  1014. background-color: inherit;
  1015. opacity: 1;
  1016. }
  1017. .legend-label {
  1018. flex: 1;
  1019. color: #d0d9e2;
  1020. font-size: 13px;
  1021. }
  1022. .legend-status {
  1023. font-size: 11px;
  1024. color: #5b7da8;
  1025. }
  1026. .all-select {
  1027. border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  1028. padding-bottom: 12px;
  1029. margin-bottom: 12px !important;
  1030. }
  1031. .all-select .legend-dot {
  1032. border-radius: 2px;
  1033. transition: all 0.3s;
  1034. width: 10px;
  1035. height: 10px;
  1036. }
  1037. .legend-dot.is-status-wrapper {
  1038. width: 28px;
  1039. height: 28px;
  1040. background-color: transparent !important;
  1041. box-shadow: none !important;
  1042. border: none !important;
  1043. margin-right: 0;
  1044. transform: translateX(-15%);
  1045. }
  1046. .status-icon {
  1047. width: 100%;
  1048. height: 100%;
  1049. object-fit: contain;
  1050. display: block;
  1051. }
  1052. ::v-deep .pure-light-node {
  1053. width: 16px;
  1054. height: 16px;
  1055. border-radius: 50%;
  1056. border: 2px solid rgba(255, 255, 255, 0.8);
  1057. cursor: pointer;
  1058. transition: all 0.3s;
  1059. display: flex;
  1060. justify-content: center;
  1061. align-items: center;
  1062. color: #fff;
  1063. pointer-events: auto;
  1064. }
  1065. ::v-deep .pure-light-node.route-node {
  1066. position: relative;
  1067. overflow: visible;
  1068. }
  1069. ::v-deep .pure-light-node.route-node::after {
  1070. content: "";
  1071. position: absolute;
  1072. top: 50%;
  1073. left: 50%;
  1074. width: 150%;
  1075. height: 3px;
  1076. background-color: inherit;
  1077. opacity: 0.8;
  1078. transform: translate(-50%, -50%) rotate(-45deg);
  1079. pointer-events: none;
  1080. }
  1081. ::v-deep .pure-light-node.route-node span {
  1082. position: relative;
  1083. z-index: 1;
  1084. }
  1085. /* 异常状态增加稍微剧烈一点的呼吸感,但缩小范围 */
  1086. @keyframes light-breathe {
  1087. 0% {
  1088. transform: scale(0.9);
  1089. opacity: 0.8;
  1090. }
  1091. 50% {
  1092. transform: scale(1.1);
  1093. opacity: 1;
  1094. }
  1095. 100% {
  1096. transform: scale(0.9);
  1097. opacity: 0.8;
  1098. }
  1099. }
  1100. /* 首页展示时,如果觉得还是太密,可以给非异常节点降权 */
  1101. ::v-deep .pure-light-node:not(.abnormal-node) {
  1102. border: 1px solid rgba(255, 255, 255, 0.4);
  1103. }
  1104. </style>