| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271 |
- <template>
- <div class="map-wrapper">
- <div ref="mapContainer" class="map-container"></div>
- <div class="map-legend" :style="privateStyle.legend" v-if="(!mode || mode === '路口')"
- :class="{ 'legend-hidden': !legendVisible }">
- <div class="legend-header">
- <div class="legend-title">图例</div>
- <div class="legend-close-btn" @click="toggleLegend">✕</div>
- </div>
- <div class="legend-list">
- <div class="legend-item all-select" @click="toggleAll">
- <div class="legend-dot"
- :style="{ backgroundColor: isAllSelected ? '#fff' : 'transparent', border: '1px solid #fff' }"></div>
- <div class="legend-label" style="font-weight: bold;">全选</div>
- </div>
- <div v-for="item in legendStatusConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
- :class="{ 'is-inactive': !activeLegends.includes(item.name) }">
- <div class="legend-dot"
- :style="{ backgroundColor: ['离线', '降级', '故障'].includes(item.name) ? 'transparent' : item.color }"
- :class="{ 'special-route': ['干线协调', '勤务路线'].includes(item.name), 'is-status-wrapper': ['离线', '降级', '故障'].includes(item.name) }">
- <span v-if="!['离线', '降级', '故障'].includes(item.name)">
- {{ item.name.charAt(0) }}
- </span>
- <img v-else
- :src="require(`@/assets/images/icon_${item.name === '离线' ? 'lixian' : item.name === '降级' ? 'jiangji' : 'guzhang'}.png`)"
- class="status-icon" />
- </div>
- <div class="legend-label">{{ item.name }}</div>
- </div>
- </div>
- </div>
- <div class="legend-show-btn" v-if="(!mode || mode === '路口') && !legendVisible" @click="toggleLegend">
- <div class="legend-show-icon">☰</div>
- </div>
- </div>
- </template>
- <script>
- import AMapLoader from '@amap/amap-jsapi-loader';
- export default {
- name: "TrafficMap",
- props: {
- amapKey: { type: String, default: '您的Key' },
- securityJsCode: { type: String, default: '您的安全密钥' },
- mode: { type: String, default: '', validator: (value) => ['', '路口', '干线', '特勤'].includes(value) }
- },
- data() {
- return {
- AMap: null,
- map: null,
- infoWindow: null,
- routeGroups: {},
- polylines: [],
- privateStyle: {
- legend: {}
- },
- legendVisible: true,
- activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"],
- // 核心修正:增加生命周期标识,防止组件销毁后异步回调继续执行
- isComponentDestroyed: false,
- drawSeq: 0,
- driving: null,
- // 状态类型配置
- statusConfig: [
- { name: "中心计划", color: "#004CDE", type: "normal" },
- { name: "干线协调", color: "#13C373", type: "route" },
- { name: "勤务路线", color: "#BC301D", type: "route" },
- { name: "定周期控制", color: "#3296FA", type: "normal" },
- { name: "感应控制", color: "#FF864C", type: "normal" },
- { name: "自适应控制", color: "#9F6EFE", type: "normal" },
- { name: "手动控制", color: "#EB9F36", type: "normal" },
- { name: "特殊控制", color: "#A26218", type: "normal" },
- { name: "离线", color: "#7A7A7A", type: "abnormal" },
- { name: "降级", color: "#D9C13B", type: "abnormal" },
- { name: "故障", color: "#FF3938", type: "abnormal" }
- ],
- // 真实路口数据
- intersectionData: [],
- // 按状态分类的路口数据
- statusIntersections: {},
- };
- },
- mounted() {
- this.isComponentDestroyed = false; // 重置标识
- this.loadMapData().then(() => {
- this.classifyIntersectionsByStatus();
- this.updateMapByMode();
- this.initAMap();
- });
- if (this.$route.path === '/home') {
- this.privateStyle.legend = { right: "25%" };
- }
- },
- watch: {
- mode: {
- handler() {
- this.updateMapByMode();
- this.updateMapDisplay();
- },
- immediate: false
- }
- },
- beforeDestroy() {
- // 1. 立即设置销毁状态
- this.isComponentDestroyed = true;
- this.drawSeq += 1;
- // 2. 关闭弹窗
- if (this.infoWindow) {
- try {
- this.infoWindow.close();
- } catch (e) {
- console.warn('关闭信息窗口时出错:', e);
- }
- this.infoWindow = null;
- }
- // 3. 清理覆盖物引用
- if (this.routeGroups) {
- Object.values(this.routeGroups).forEach(overlays => {
- if (Array.isArray(overlays)) {
- overlays.forEach(o => {
- try {
- if (o.setMap) o.setMap(null);
- } catch (e) {
- console.warn('清理覆盖物时出错:', e);
- }
- });
- }
- });
- this.routeGroups = {};
- }
- // 4. 销毁地图实例并清空引用
- if (this.map) {
- try {
- this.map.destroy();
- } catch (e) {
- console.warn('销毁地图实例时出错:', e);
- }
- this.map = null;
- }
- // 5. 清理其他引用
- this.AMap = null;
- this.driving = null;
- },
- computed: {
- isAllSelected() {
- return this.activeLegends.length === this.statusConfig.length;
- },
- legendStatusConfig() {
- if (!this.mode) return this.statusConfig;
- if (this.mode === '路口') {
- return this.statusConfig.filter(item => !['干线协调', '勤务路线'].includes(item.name));
- }
- return [];
- }
- },
- methods: {
- // 动态加载地图数据
- async loadMapData() {
- try {
- const mapDataModule = await import('@/mock/map_data_gaode.json');
- this.intersectionData = mapDataModule.default || [];
- console.log('地图数据加载成功,共', this.intersectionData.length, '个路口');
- } catch (error) {
- console.error('地图数据加载失败:', error);
- this.intersectionData = [];
- }
- },
- // 检查地图环境是否安全可用
- isMapReady() {
- return !this.isComponentDestroyed && this.map && typeof this.map.add === 'function';
- },
- // 将真实路口数据按状态类型分类
- classifyIntersectionsByStatus() {
- const remainingData = this.intersectionData;
- const normalStatusCount = 6;
- const abnormalStatusCount = 3;
- const chunkSize = Math.floor(remainingData.length / (normalStatusCount + abnormalStatusCount));
- const maxAbnormalCount = 10;
- this.statusIntersections = {
- "中心计划": remainingData.slice(0, 20),
- "干线协调": [], // 清空,改为动态生成
- "勤务路线": [], // 清空,改为动态生成
- "定周期控制": remainingData.slice(chunkSize, chunkSize * 2),
- "感应控制": remainingData.slice(chunkSize * 2, chunkSize * 3),
- "自适应控制": remainingData.slice(chunkSize * 3, chunkSize * 4),
- "手动控制": remainingData.slice(chunkSize * 4, chunkSize * 5),
- "特殊控制": remainingData.slice(chunkSize * 5, chunkSize * 6),
- "离线": remainingData.slice(chunkSize * 6, Math.min(chunkSize * 7, chunkSize * 6 + maxAbnormalCount)),
- "降级": remainingData.slice(chunkSize * 7, Math.min(chunkSize * 8, chunkSize * 7 + maxAbnormalCount)),
- "故障": remainingData.slice(chunkSize * 8, Math.min(chunkSize * 9, chunkSize * 8 + maxAbnormalCount))
- };
- },
- updateMapByMode() {
- switch (this.mode) {
- case '路口':
- this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "特殊控制", "离线", "降级", "故障"];
- break;
- case '干线':
- this.activeLegends = ["干线协调"];
- break;
- case '特勤':
- this.activeLegends = ["勤务路线"];
- break;
- default:
- this.activeLegends = this.statusConfig.map(item => item.name);
- }
- },
- updateMapDisplay() {
- if (this.infoWindow) this.infoWindow.close();
- if (!this.isMapReady()) return;
- Object.keys(this.routeGroups).forEach(name => {
- const overlays = this.routeGroups[name];
- if (overlays && overlays.length > 0) {
- if (this.activeLegends.includes(name)) {
- this.map.add(overlays);
- } else {
- this.map.remove(overlays);
- }
- }
- });
- },
- async initAMap() {
- if (this.isComponentDestroyed) return;
- // 确保在加载前注入
- window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
- try {
- const AMap = await AMapLoader.load({
- key: this.amapKey,
- version: "2.0",
- // 核心:确保 Driving 插件在此加载
- plugins: ['AMap.Driving']
- });
- if (this.isComponentDestroyed) return;
- this.AMap = AMap;
- this.map = new AMap.Map(this.$refs.mapContainer, {
- zoom: 15,
- mapStyle: "amap://styles/darkblue",
- center: [116.663, 39.905], // 通州区中心
- });
- this.driving = new AMap.Driving({ map: null, hideMarkers: true });
- // 建议在地图加载完成后再画线
- this.map.on('complete', () => {
- if (!this.isComponentDestroyed) {
- this.drawStaticRoutes();
- // 临时方案,实际项目中删除 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
- this.storeStatusCoordsToLocalStorage();
- }
- });
- } catch (err) {
- console.error('地图加载失败:', err);
- }
- },
- // 绘制静态路线和标记
- // 对于普通状态,从 mock 数据加载路口标记
- // 对于路线类(干线协调和勤务路线),使用高德地图路线规划绘制路线和密集点位
- async drawStaticRoutes() {
- if (!this.isMapReady()) return;
- this.drawSeq += 1;
- const drawSeq = this.drawSeq;
- this.clearAllRouteOverlays();
- const realRouteConfigs = {
- "干线协调": [
- { start: [116.6421, 39.9172], end: [116.6825, 39.9172], color: "#13C373" },
- { start: [116.6426, 39.9121], end: [116.6830, 39.9121], color: "#13C373" },
- { start: [116.6432, 39.9071], end: [116.6833, 39.9071], color: "#13C373" },
- { start: [116.6438, 39.9023], end: [116.6841, 39.9023], color: "#13C373" },
- { start: [116.6445, 39.8975], end: [116.6846, 39.8975], color: "#13C373" }
- ],
- "勤务路线": [
- { start: [116.6400, 39.9225], end: [116.6400, 39.8971], color: "#BC301D" },
- { start: [116.6465, 39.9225], end: [116.6465, 39.8971], color: "#BC301D" },
- { start: [116.6521, 39.9225], end: [116.6521, 39.8971], color: "#BC301D" },
- { start: [116.6620, 39.9225], end: [116.6620, 39.8971], color: "#BC301D" },
- { start: [116.6734, 39.9225], end: [116.6734, 39.8971], color: "#BC301D" },
- { start: [116.6790, 39.9225], end: [116.6790, 39.8971], color: "#BC301D" },
- { start: [116.6850, 39.9170], end: [116.6850, 39.9000], color: "#BC301D" }
- ]
- };
- for (const config of this.statusConfig) {
- if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
- // 1. 处理普通非路线状态(从 mock 数据加载)
- if (!realRouteConfigs[config.name]) {
- const intersections = this.statusIntersections[config.name] || [];
- const markers = intersections.map(item =>
- this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], config)
- ).filter(Boolean);
- this.routeGroups[config.name] = markers;
- if (this.activeLegends.includes(config.name)) this.map.add(markers);
- continue;
- }
- // 2. 处理路线类(干线/特勤)
- this.routeGroups[config.name] = [];
- const lines = realRouteConfigs[config.name] || [];
- for (let lineIdx = 0; lineIdx < lines.length; lineIdx += 1) {
- if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
- const line = lines[lineIdx];
- let path = null;
- try {
- path = await this.searchDrivingPathWithRetry(line.start, line.end);
- } catch (e) {
- path = null;
- }
- const overlays = this.buildRouteOverlaysFromPath({
- config,
- configName: config.name,
- line,
- lineIdx,
- path
- });
- if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
- if (overlays.length > 0) {
- this.routeGroups[config.name].push(...overlays);
- if (this.activeLegends.includes(config.name)) this.map.add(overlays);
- }
- await this.sleep(80);
- }
- }
- },
- clearAllRouteOverlays() {
- if (!this.isMapReady()) return;
- try {
- if (this.infoWindow) this.infoWindow.close();
- } catch (e) {
- void e;
- }
- Object.values(this.routeGroups || {}).forEach(overlays => {
- if (!Array.isArray(overlays) || overlays.length === 0) return;
- try {
- this.map.remove(overlays);
- } catch (e) {
- void e;
- }
- overlays.forEach(o => {
- try {
- if (o && typeof o.setMap === 'function') o.setMap(null);
- } catch (e) {
- void e;
- }
- });
- });
- this.routeGroups = {};
- },
- sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- },
- async searchDrivingPathWithRetry(start, end) {
- if (!this.AMap || !this.driving || typeof this.driving.search !== 'function') {
- throw new Error('Driving not ready');
- }
- const maxAttempts = 3;
- let lastErr = null;
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
- try {
- return await this.withTimeout(this.searchDrivingPathOnce(start, end), 8000);
- } catch (e) {
- lastErr = e;
- await this.sleep(250 * attempt);
- }
- }
- throw lastErr || new Error('Driving search failed');
- },
- searchDrivingPathOnce(start, end) {
- return new Promise((resolve, reject) => {
- this.driving.search(start, end, (status, result) => {
- const route = result && result.routes && result.routes[0];
- if (status === 'complete' && route && Array.isArray(route.steps)) {
- const fullPath = [];
- route.steps.forEach(step => {
- if (step && Array.isArray(step.path)) fullPath.push(...step.path);
- });
- if (fullPath.length >= 2) resolve(fullPath);
- else reject(new Error('empty_path'));
- return;
- }
- reject(new Error(typeof status === 'string' ? status : 'driving_error'));
- });
- });
- },
- withTimeout(promise, timeoutMs) {
- return Promise.race([
- promise,
- new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
- ]);
- },
- buildRouteOverlaysFromPath({ config, configName, line, lineIdx, path }) {
- if (!this.AMap || !this.map) return [];
- let basePath = path;
- if (!Array.isArray(basePath) || basePath.length < 2) {
- basePath = this.buildFallbackLinePath(line.start, line.end, 30);
- }
- const segments = this.extractMainStraightSegments(basePath);
- const overlays = [];
- segments.forEach((segmentPath, segmentIdx) => {
- if (!Array.isArray(segmentPath) || segmentPath.length < 2) return;
- const polyline = new this.AMap.Polyline({
- path: segmentPath,
- strokeColor: line.color,
- strokeWeight: 6,
- strokeOpacity: 0.8,
- zIndex: 15
- });
- overlays.push(polyline);
- const totalPoints = segmentPath.length;
- const indices = this.pickEvenlySpacedIndices(totalPoints, 8);
- for (const i of indices) {
- const p = segmentPath[i];
- const lng = p && typeof p.lng === 'number' ? p.lng : (Array.isArray(p) ? Number(p[0]) : NaN);
- const lat = p && typeof p.lat === 'number' ? p.lat : (Array.isArray(p) ? Number(p[1]) : NaN);
- if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
- const marker = this.createTrafficLightMarker([lng, lat], {
- ...config,
- id: `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${i}`,
- road: `${configName}路口-${lineIdx}-${segmentIdx}-${i}`
- });
- if (marker) overlays.push(marker);
- }
- });
- return overlays;
- },
- pickEvenlySpacedIndices(totalPoints, count) {
- const total = Math.max(Number(totalPoints) || 0, 0);
- const target = Math.max(Number(count) || 0, 0);
- if (total <= 0) return [];
- if (target <= 0) return [];
- if (target >= total) return Array.from({ length: total }, (_, i) => i);
- if (target === 1) return [0];
- const set = new Set();
- const last = total - 1;
- for (let k = 0; k < target; k += 1) {
- const idx = Math.round((k * last) / (target - 1));
- set.add(idx);
- }
- return Array.from(set).sort((a, b) => a - b);
- },
- buildFallbackLinePath(start, end, pointCount) {
- const sLng = Number(start && start[0]);
- const sLat = Number(start && start[1]);
- const eLng = Number(end && end[0]);
- const eLat = Number(end && end[1]);
- const n = Math.max(Number(pointCount) || 2, 2);
- const path = [];
- if ([sLng, sLat, eLng, eLat].some(v => Number.isNaN(v))) return path;
- for (let i = 0; i < n; i += 1) {
- const t = n === 1 ? 0 : i / (n - 1);
- const lng = sLng + (eLng - sLng) * t;
- const lat = sLat + (eLat - sLat) * t;
- path.push({ lng, lat });
- }
- return path;
- },
- extractMainStraightSegments(path) {
- const points = (path || []).filter(p => p && typeof p.lng === 'number' && typeof p.lat === 'number');
- if (points.length < 2) return [];
- const thresholdDeg = 18;
- const segments = [];
- let curStart = 0;
- let curAngle = null;
- let curLen = 0;
- const pushSegment = (endIdx) => {
- if (endIdx <= curStart) return;
- segments.push({
- start: curStart,
- end: endIdx,
- len: curLen
- });
- };
- for (let i = 0; i < points.length - 1; i += 1) {
- const a = points[i];
- const b = points[i + 1];
- const len = this.calcApproxDistance(a, b);
- if (len <= 0) continue;
- const angle = this.calcBearingDeg(a, b);
- if (curAngle === null) {
- curStart = i;
- curAngle = angle;
- curLen = len;
- continue;
- }
- const diff = this.calcAngleDiffDeg(curAngle, angle);
- if (diff <= thresholdDeg) {
- curLen += len;
- } else {
- pushSegment(i);
- curStart = i;
- curAngle = angle;
- curLen = len;
- }
- }
- pushSegment(points.length - 2);
- if (segments.length === 0) return [points];
- segments.sort((s1, s2) => s2.len - s1.len);
- const maxLen = segments[0].len || 0;
- const filtered = segments.filter(s => s.len >= maxLen * 0.55).slice(0, 3);
- const finalSegments = filtered.map(s => points.slice(s.start, s.end + 2));
- return finalSegments.length > 0 ? finalSegments : [points];
- },
- calcBearingDeg(a, b) {
- const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
- const dx = (b.lng - a.lng) * Math.cos(latRad);
- const dy = (b.lat - a.lat);
- let deg = Math.atan2(dy, dx) * 180 / Math.PI;
- if (deg < 0) deg += 360;
- return deg;
- },
- calcAngleDiffDeg(a, b) {
- let diff = Math.abs(a - b);
- if (diff > 180) diff = 360 - diff;
- return diff;
- },
- calcApproxDistance(a, b) {
- const latRad = ((a.lat + b.lat) / 2) * Math.PI / 180;
- const dx = (b.lng - a.lng) * Math.cos(latRad);
- const dy = (b.lat - a.lat);
- return Math.sqrt(dx * dx + dy * dy);
- },
- createTrafficLightMarker(position, config, type = 'normal') {
- if (!position || !config) return null;
- try {
- const lng = Number(position[0] || position.lng);
- const lat = Number(position[1] || position.lat);
- if (isNaN(lng) || isNaN(lat)) return null;
- // 状态文字:起、终、或者状态配置的首字母
- let displayText = config.name ? config.name.charAt(0) : '';
- if (type === 'start') displayText = '起';
- if (type === 'end') displayText = '终';
- const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
- const isRoute = ["干线协调", "勤务路线"].includes(config.name);
- // 动态计算尺寸:起终点最大,异常点次之,普通点最小
- const size = (type === 'start' || type === 'end') ? '22px' : (isAbnormal ? '30px' : '14px');
- const sizeNumber = parseInt(size, 10);
- const paddingNumber = (isAbnormal || type === 'start' || type === 'end') ? 0 : 2;
- const outerSizeNumber = sizeNumber + paddingNumber * 2;
- // 边框样式:起终点用实白边框
- const borderStyle = (type === 'start' || type === 'end')
- ? '2px solid #fff'
- : '1.5px solid rgba(255,255,255,0.7)';
- // 生成异常状态的图标路径
- let markerContent = '';
- if (isAbnormal) {
- const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
- markerContent = `
- <div class="pure-light-node ${isAbnormal ? 'breathe' : ''}"
- style="
- width: ${size};
- height: ${size};
- background: transparent;
- box-shadow: none;
- border: none;
- box-sizing: content-box;
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- padding: ${paddingNumber}px;
- ">
- <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
- </div>
- `;
- } else {
- markerContent = `
- <div class="pure-light-node ${isAbnormal ? 'breathe' : ''} ${isRoute ? 'route-node' : ''}"
- style="
- width: ${size};
- height: ${size};
- background: ${config.color || '#999'};
- box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`};
- border: ${isRoute ? 'none' : borderStyle};
- box-sizing: content-box;
- display: flex;
- justify-content: center;
- align-items: center;
- color: #fff;
- border-radius: 50%;
- cursor: pointer;
- padding: ${paddingNumber}px;
- ">
- <span style="transform: scale(0.8); font-weight: bold; font-size: 12px;">${displayText}</span>
- </div>
- `;
- }
- const marker = new this.AMap.Marker({
- position: [lng, lat],
- // 这里的 type 已经从参数拿到了,不会报错了
- zIndex: (type === 'start' || type === 'end') ? 120 : (isAbnormal ? 110 : 100),
- content: markerContent,
- offset: new this.AMap.Pixel(-Math.round(outerSizeNumber / 2), -Math.round(outerSizeNumber / 2)),
- extData: {
- ...config,
- position: [lng, lat],
- statusColor: config.color || '#999',
- statusLabel: isAbnormal ? config.name : "正常运行",
- road: config.road || '规划路口',
- timestamp: Date.now(),
- time: this.formatEventTime(Date.now())
- }
- });
- marker.on('click', (e) => {
- if (!this.isComponentDestroyed) {
- this.openLightInfo(e.target.getExtData(), e.lnglat);
- this.$emit('map-crossing-click', e.target.getExtData(), e.lnglat);
- }
- });
- return marker;
- } catch (e) {
- console.warn('创建标记时出错:', e);
- return null;
- }
- },
- openLightInfo(data, position) {
- if (!this.isMapReady()) return;
- const infoWindowId = `info-window-${Date.now()}`;
- const isAbnormal = ["离线", "降级", "故障"].includes(data.name);
- const deviceStatusText = isAbnormal ? data.name : '正常';
- const alarmInfoText = isAbnormal ? this.getAlarmInfoText(data.name) : '';
- const eventTimeText = this.formatEventTime(data.timestamp || data.time);
- let statusDotContent = '';
-
- if (isAbnormal) {
- const iconName = data.name === '离线' ? 'lixian' : data.name === '降级' ? 'jiangji' : 'guzhang';
- statusDotContent = `<img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />`;
- } else {
- statusDotContent = `<span>${data.name.charAt(0)}</span>`;
- }
-
- const content = `
- <div class="custom-info-card" id="${infoWindowId}">
- <div class="close-btn" data-id="${infoWindowId}">✕</div>
- <div class="card-header">
- <div class="status-dot ${isAbnormal ? 'breathe' : ''}" style="background: ${isAbnormal ? 'transparent' : data.statusColor}; border: ${isAbnormal ? 'none' : ''}">
- ${statusDotContent}
- </div>
- <span class="status-text">${data.statusLabel}</span>
- </div>
- <div class="card-body">
- ${isAbnormal
- ? `
- <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
- <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
- <div class="info-line"><span class="label">报警信息:</span><span class="value">${alarmInfoText}</span></div>
- <div class="info-line"><span class="label">发生时间:</span><span class="value digital">${eventTimeText}</span></div>
- `
- : `
- <div class="info-line"><span class="label">中(干/勤/定/感/自/手/特):</span><span class="value">${data.name}</span></div>
- <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
- <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
- `
- }
- </div>
- </div>
- `;
- if (!this.infoWindow) {
- this.infoWindow = new this.AMap.InfoWindow({
- isCustom: true,
- offset: new this.AMap.Pixel(0, -20)
- });
- }
- this.infoWindow.setContent(content);
- this.infoWindow.open(this.map, position);
- // 添加关闭按钮事件监听器
- setTimeout(() => {
- const closeBtn = document.querySelector(`#${infoWindowId} .close-btn`);
- if (closeBtn) {
- closeBtn.addEventListener('click', () => {
- if (this.infoWindow) this.infoWindow.close();
- });
- }
- }, 100);
- },
- getAlarmInfoText(statusName) {
- if (statusName === '离线') return '通讯中断设备离线';
- if (statusName === '降级') return '降级定周期控制';
- if (statusName === '故障') return '东向左转信号灯红绿同亮';
- return '设备异常';
- },
- formatEventTime(input) {
- let d = null;
- if (input instanceof Date) d = input;
- else if (typeof input === 'number') d = new Date(input);
- else if (typeof input === 'string') {
- const t = Date.parse(input);
- if (!Number.isNaN(t)) d = new Date(t);
- }
- if (!d || Number.isNaN(d.getTime())) d = new Date();
- const y = d.getFullYear();
- const m = d.getMonth() + 1;
- const day = d.getDate();
- const hh = String(d.getHours()).padStart(2, '0');
- const mm = String(d.getMinutes()).padStart(2, '0');
- return `${y}.${m}.${day} ${hh}:${mm}`;
- },
- toggleAll() {
- const targetState = !this.isAllSelected;
- if (!this.isMapReady()) return;
- if (targetState) {
- this.activeLegends = this.statusConfig.map(item => item.name);
- Object.values(this.routeGroups).forEach(overlays => {
- if (overlays && overlays.length > 0) this.map.add(overlays);
- });
- } else {
- this.activeLegends = [];
- Object.values(this.routeGroups).forEach(overlays => {
- if (overlays && overlays.length > 0) this.map.remove(overlays);
- });
- if (this.infoWindow) this.infoWindow.close();
- }
- },
- toggleRouteVisible(name) {
- if (!this.isMapReady()) return;
- const overlays = this.routeGroups[name] || [];
- const index = this.activeLegends.indexOf(name);
- if (index > -1) {
- this.activeLegends.splice(index, 1);
- this.map.remove(overlays);
- if (this.infoWindow) this.infoWindow.close();
- } else {
- this.activeLegends.push(name);
- this.map.add(overlays);
- }
- },
- focusByLocation(targetPos) {
- if (!this.isMapReady() || !targetPos || targetPos.length !== 2) return;
- let foundMarker = null;
- Object.values(this.routeGroups).forEach(group => {
- const marker = group.find(item => {
- if (!(item instanceof this.AMap.Marker)) return false;
- const pos = item.getExtData().position;
- return Math.abs(pos[0] - targetPos[0]) < 0.0001 && Math.abs(pos[1] - targetPos[1]) < 0.0001;
- });
- if (marker) foundMarker = marker;
- });
- if (foundMarker) {
- const finalPos = foundMarker.getPosition();
- this.map.setZoomAndCenter(17, finalPos, false, 500);
- setTimeout(() => {
- if (!this.isComponentDestroyed) this.openLightInfo(foundMarker.getExtData(), finalPos);
- }, 600);
- }
- },
- toggleLegend() {
- this.legendVisible = !this.legendVisible;
- },
- // 按4:3:3比例提取故障、离线、降级坐标点并存储到localStorage
- storeStatusCoordsToLocalStorage() {
- // 故障、离线、降级坐标点(按4:3:3比例)
- const faultCoords = [
- [116.723317, 39.907606],
- [116.703624, 39.89801],
- [116.661252, 39.924948],
- [116.708958, 39.899609]
- ];
-
- const offlineCoords = [
- [116.677855, 39.895636],
- [116.656673, 39.856063],
- [116.656485, 39.90118]
- ];
-
- const degradedCoords = [
- [116.713356, 39.952856],
- [116.665391, 39.934546],
- [116.697784, 39.891312]
- ];
- // 组合成10个元素的数组
- const statusCoords = [...faultCoords, ...offlineCoords, ...degradedCoords];
- // 存储到localStorage
- statusCoords.forEach((coords, index) => {
- localStorage.setItem(`pos${index + 1}`, coords.join(','));
- });
- console.log('状态坐标已存储到localStorage');
- }
- }
- };
- </script>
- <style scoped>
- .map-wrapper {
- width: 100%;
- height: 100vh;
- position: relative;
- background: #010813;
- }
- .map-container {
- width: 100%;
- height: 100%;
- }
- ::v-deep .pure-light-node.breathe {
- animation: light-breathe 2s infinite ease-in-out;
- }
- ::v-deep .pure-light-node span {
- display: flex;
- transform: scale(0.75);
- align-items: center;
- }
- ::v-deep .pure-light-node:hover {
- transform: scale(1.4);
- filter: brightness(1.2);
- }
- @keyframes light-breathe {
- 0% {
- transform: scale(0.9);
- opacity: 0.8;
- }
- 50% {
- transform: scale(1.1);
- opacity: 1;
- }
- 100% {
- transform: scale(0.9);
- opacity: 0.8;
- }
- }
- ::v-deep .close-btn {
- position: absolute;
- top: 10px;
- right: 12px;
- color: #8da6c7;
- cursor: pointer;
- font-size: 16px;
- transition: color 0.3s;
- line-height: 1;
- z-index: 10;
- }
- ::v-deep .close-btn:hover {
- color: #ffffff;
- }
- ::v-deep .custom-info-card {
- position: relative;
- background: rgba(10, 15, 24, 0.95);
- border-radius: 10px;
- padding: 12px 16px;
- min-width: 200px;
- border: 1px solid rgba(255, 255, 255, 0.1);
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
- color: #fff;
- }
- ::v-deep .card-header {
- display: flex;
- align-items: center;
- margin-bottom: 10px;
- }
- ::v-deep .status-dot {
- width: 30px;
- height: 30px;
- border-radius: 50%;
- display: flex;
- justify-content: center;
- align-items: center;
- margin-right: 8px;
- font-size: 14px;
- padding: 0;
- box-sizing: border-box;
- }
- ::v-deep .status-dot.breathe {
- animation: light-breathe 2s infinite ease-in-out;
- }
- ::v-deep .status-dot span {
- transform: scale(0.75);
- }
- ::v-deep .status-dot img {
- width: 100%;
- height: 100%;
- object-fit: contain;
- display: block;
- }
- ::v-deep .status-text {
- font-size: 15px;
- font-weight: bold;
- }
- ::v-deep .info-line {
- display: flex;
- margin-bottom: 6px;
- font-size: 13px;
- align-items: center;
- }
- ::v-deep .label {
- color: #8da6c7;
- white-space: nowrap;
- }
- ::v-deep .value {
- color: #ffffff;
- }
- ::v-deep .digital {
- font-family: 'Consolas', monospace;
- }
- .map-legend {
- position: absolute;
- bottom: 30px;
- right: 40px;
- background: rgba(5, 22, 45, 0.9);
- border: 1px solid #1e4d8e;
- padding: 15px;
- border-radius: 6px;
- z-index: 100;
- transition: all 0.3s ease-in-out;
- opacity: 1;
- max-width: 200px;
- overflow: hidden;
- }
- .map-legend.legend-hidden {
- opacity: 0;
- transform: translateX(calc(100% + 20px));
- pointer-events: none;
- }
- .legend-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 12px;
- border-bottom: 1px solid #1e4d8e;
- padding-bottom: 8px;
- }
- .legend-close-btn {
- color: #8da6c7;
- cursor: pointer;
- font-size: 16px;
- transition: color 0.3s;
- line-height: 1;
- }
- .legend-close-btn:hover {
- color: #ffffff;
- }
- .legend-show-btn {
- position: absolute;
- bottom: 30px;
- right: 20px;
- background: rgba(5, 22, 45, 0.9);
- border: 1px solid #1e4d8e;
- width: 40px;
- height: 40px;
- border-radius: 6px 0 0 6px;
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- z-index: 99;
- transition: all 0.3s ease-in-out;
- }
- .legend-show-btn:hover {
- background: rgba(10, 30, 60, 0.9);
- border-color: #3a75c4;
- }
- .legend-show-icon {
- color: #8da6c7;
- font-size: 18px;
- transition: color 0.3s;
- }
- .legend-show-btn:hover .legend-show-icon {
- color: #ffffff;
- }
- .legend-title {
- color: #fff;
- font-size: 14px;
- }
- .legend-item {
- display: flex;
- align-items: center;
- margin-bottom: 10px;
- cursor: pointer;
- transition: 0.3s;
- }
- .legend-item.is-inactive {
- opacity: 0.2;
- filter: grayscale(1);
- }
- .legend-dot {
- margin-right: 10px;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .legend-dot:not(.is-status-wrapper) {
- width: 20px;
- height: 20px;
- border-radius: 50%;
- }
- .legend-dot span {
- display: inline-block;
- width: 20px;
- height: 20px;
- font-size: 12px;
- color: #FFF;
- text-align: center;
- transform: scale(0.75);
- line-height: 20px;
- }
- .legend-dot.special-route {
- position: relative;
- overflow: visible !important;
- z-index: 1;
- border: none !important;
- border-radius: 50%;
- }
- .legend-dot.special-route span {
- position: relative;
- z-index: 3;
- font-weight: bold;
- }
- .legend-dot.special-route::after {
- content: "";
- position: absolute;
- top: 50%;
- left: 50%;
- width: 150%;
- height: 3px;
- background-color: inherit;
- opacity: 0.8;
- transform: translate(-50%, -50%) rotate(-45deg);
- pointer-events: none;
- z-index: 0;
- }
- .legend-dot.special-route::before {
- content: "";
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- border-radius: 50%;
- z-index: 2;
- background-color: inherit;
- opacity: 1;
- }
- .legend-label {
- flex: 1;
- color: #d0d9e2;
- font-size: 13px;
- }
- .legend-status {
- font-size: 11px;
- color: #5b7da8;
- }
- .all-select {
- border-bottom: 1px solid rgba(255, 255, 255, 0.2);
- padding-bottom: 12px;
- margin-bottom: 12px !important;
- }
- .all-select .legend-dot {
- border-radius: 2px;
- transition: all 0.3s;
- width: 10px;
- height: 10px;
- }
- .legend-dot.is-status-wrapper {
- width: 28px;
- height: 28px;
- background-color: transparent !important;
- box-shadow: none !important;
- border: none !important;
- margin-right: 0;
- transform: translateX(-15%);
- }
- .status-icon {
- width: 100%;
- height: 100%;
- object-fit: contain;
- display: block;
- }
- ::v-deep .pure-light-node {
- width: 16px;
- height: 16px;
- border-radius: 50%;
- border: 2px solid rgba(255, 255, 255, 0.8);
- cursor: pointer;
- transition: all 0.3s;
- display: flex;
- justify-content: center;
- align-items: center;
- color: #fff;
- pointer-events: auto;
- }
- ::v-deep .pure-light-node.route-node {
- position: relative;
- overflow: visible;
- }
- ::v-deep .pure-light-node.route-node::after {
- content: "";
- position: absolute;
- top: 50%;
- left: 50%;
- width: 150%;
- height: 3px;
- background-color: inherit;
- opacity: 0.8;
- transform: translate(-50%, -50%) rotate(-45deg);
- pointer-events: none;
- }
- ::v-deep .pure-light-node.route-node span {
- position: relative;
- z-index: 1;
- }
- /* 异常状态增加稍微剧烈一点的呼吸感,但缩小范围 */
- @keyframes light-breathe {
- 0% {
- transform: scale(0.9);
- opacity: 0.8;
- }
- 50% {
- transform: scale(1.1);
- opacity: 1;
- }
- 100% {
- transform: scale(0.9);
- opacity: 0.8;
- }
- }
- /* 首页展示时,如果觉得还是太密,可以给非异常节点降权 */
- ::v-deep .pure-light-node:not(.abnormal-node) {
- border: 1px solid rgba(255, 255, 255, 0.4);
- }
- </style>
|