TongzhouTrafficMap.vue 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  1. <template>
  2. <div class="map-wrapper" :style="mapCssVars">
  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 all-select-dot" :class="{ 'is-checked': isAllSelected }">
  13. <i class="check-icon" v-if="isAllSelected"></i>
  14. </div>
  15. <div class="legend-label" style="font-weight: bold;">全选</div>
  16. </div>
  17. <div v-for="item in legendStatusConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
  18. :class="{ 'is-inactive': !activeLegends.includes(item.name) }">
  19. <div class="legend-dot"
  20. :style="{ backgroundColor: ['离线', '降级', '故障'].includes(item.name) ? 'transparent' : item.color }"
  21. :class="{ 'special-route': ['干线协调', '勤务路线'].includes(item.name), 'is-status-wrapper': ['离线', '降级', '故障'].includes(item.name) }">
  22. <span v-if="!['离线', '降级', '故障'].includes(item.name)">
  23. {{ item.name.charAt(0) }}
  24. </span>
  25. <img v-else
  26. :src="require(`@/assets/images/icon_${item.name === '离线' ? 'lixian' : item.name === '降级' ? 'jiangji' : 'guzhang'}.png`)"
  27. class="status-icon" />
  28. </div>
  29. <div class="legend-label">{{ item.name }}</div>
  30. </div>
  31. </div>
  32. </div>
  33. <div class="legend-show-btn" v-if="(!mode || mode === '路口') && !legendVisible" @click="toggleLegend" :style="legendShowBtnStyle" title="显示图例">
  34. <div class="legend-show-icon">☰</div>
  35. </div>
  36. <div v-if="showSearch" class="map-search-wrap" :style="searchBoxStyle">
  37. <MapSearchBox :data-source="intersectionData" @select="onSearchSelect" />
  38. </div>
  39. </div>
  40. </template>
  41. <script>
  42. import AMapLoader from '@amap/amap-jsapi-loader';
  43. import { getIntersectionCategory } from '@/mock/api';
  44. import MapSearchBox from '@/components/ui/MapSearchBox.vue';
  45. import { amap as amapConfig } from '@/utils/brand';
  46. export default {
  47. name: "TrafficMap",
  48. components: { MapSearchBox },
  49. props: {
  50. amapKey: { type: String, default: () => amapConfig.key },
  51. securityJsCode: { type: String, default: () => amapConfig.securityCode },
  52. mode: { type: String, default: '', validator: (value) => ['', '路口', '干线', '特勤'].includes(value) },
  53. // 是否渲染地图搜索框。默认关闭,仅 Home 显式开启。
  54. showSearch: { type: Boolean, default: false },
  55. // 搜索框相对屏幕右侧的偏移;默认 490px 适配 Home 的 400px 右侧栏。
  56. searchOffsetRight: { type: Number, default: 490 },
  57. searchOffsetTop: { type: Number, default: 110 },
  58. },
  59. data() {
  60. return {
  61. AMap: null,
  62. map: null,
  63. infoWindow: null,
  64. routeGroups: {},
  65. dotMarkers: [],
  66. privateStyle: {
  67. legend: {}
  68. },
  69. legendVisible: true,
  70. activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "黄闪", "全红", "关灯", "离线", "降级", "故障"],
  71. isComponentDestroyed: false,
  72. drawSeq: 0,
  73. driving: null,
  74. infoCloseTimer: null,
  75. activeInfoWindowId: null,
  76. isInfoWindowHovered: false,
  77. statusConfig: [
  78. { name: "中心计划", color: "#004CDE", type: "normal" },
  79. { name: "干线协调", color: "#13C373", type: "route" },
  80. { name: "勤务路线", color: "#BC301D", type: "route" },
  81. { name: "定周期控制", color: "#3296FA", type: "normal" },
  82. { name: "感应控制", color: "#FF864C", type: "normal" },
  83. { name: "自适应控制", color: "#9F6EFE", type: "normal" },
  84. { name: "手动控制", color: "#EB9F36", type: "normal" },
  85. { name: "黄闪", color: "#F4D03F", type: "normal" },
  86. { name: "全红", color: "#E74C3C", type: "normal" },
  87. { name: "关灯", color: "#5B6B7A", type: "normal" },
  88. { name: "离线", color: "#7A7A7A", type: "abnormal" },
  89. // 降级 仍参与数据分类与地图绘制,但不出现在图例(hideInLegend: true)
  90. { name: "降级", color: "#D9C13B", type: "abnormal", hideInLegend: true },
  91. { name: "故障", color: "#FF3938", type: "abnormal" }
  92. ],
  93. intersectionData: [],
  94. statusIntersections: {},
  95. currentZoomSize: 20, // 保存当前的动态尺寸(与 zoom=15 基准一致)
  96. markerById: {}, // ID → marker 索引,加速 focusById 查找
  97. startEndMarkers: [], // 起点/终点 marker 引用,缩放时需重建
  98. subAreaOverlays: [], // 子区蒙层覆盖物
  99. _subAreaParams: null, // 子区绘制参数,缩放时重绘用
  100. // ── 视口裁剪相关(详见 pyscripts/AMap路口marker视口加载与聚合设计.md Phase 1)──
  101. mountedMarkerSet: new Set(), // 当前已挂载到 map 的 overlay 引用
  102. _viewportRefreshTimer: null, // moveend/zoomend 合并 debounce 句柄
  103. viewportBufferRatio: 0.15, // 视口外扩比例
  104. viewportRefreshDebounceMs: 100, // 拖图停下后多久执行一次重算
  105. _infoWindowProtectedMarker: null, // InfoWindow 打开时的 marker,期间不参与裁剪
  106. };
  107. },
  108. mounted() {
  109. this.isComponentDestroyed = false;
  110. this.loadMapData().then(() => {
  111. this.classifyIntersectionsByStatus();
  112. this.updateMapByMode();
  113. this.initAMap();
  114. this.storeStatusCoordsToLocalStorage();
  115. });
  116. if (this.$route.path === '/home' || this.$route.path === '/watch') {
  117. this.privateStyle.legend = { right: "25%" };
  118. }
  119. },
  120. watch: {
  121. mode: {
  122. handler() {
  123. this.updateMapByMode();
  124. this.updateMapDisplay();
  125. },
  126. immediate: false
  127. }
  128. },
  129. beforeDestroy() {
  130. // 1. 立即设置销毁状态
  131. this.isComponentDestroyed = true;
  132. this.drawSeq += 1;
  133. // 1.5 清理视口裁剪 debounce 句柄与挂载集
  134. if (this._viewportRefreshTimer) {
  135. clearTimeout(this._viewportRefreshTimer);
  136. this._viewportRefreshTimer = null;
  137. }
  138. if (this.mountedMarkerSet) this.mountedMarkerSet.clear();
  139. this._infoWindowProtectedMarker = null;
  140. // 2. 关闭弹窗
  141. if (this.infoWindow) {
  142. try {
  143. this.infoWindow.close();
  144. } catch (e) {
  145. console.warn('关闭信息窗口时出错:', e);
  146. }
  147. this.infoWindow = null;
  148. }
  149. // 3. 清理覆盖物引用
  150. if (this.routeGroups) {
  151. Object.values(this.routeGroups).forEach(overlays => {
  152. if (Array.isArray(overlays)) {
  153. overlays.forEach(o => {
  154. try {
  155. if (o.setMap) o.setMap(null);
  156. } catch (e) {
  157. console.warn('清理覆盖物时出错:', e);
  158. }
  159. });
  160. }
  161. });
  162. this.routeGroups = {};
  163. this.startEndMarkers = [];
  164. }
  165. // 4. 清理子区蒙层
  166. this.clearSubAreaOverlays();
  167. // 6. 销毁地图实例并清空引用
  168. if (this.map) {
  169. try {
  170. this.map.destroy();
  171. } catch (e) {
  172. console.warn('销毁地图实例时出错:', e);
  173. }
  174. this.map = null;
  175. }
  176. // 7. 清理其他引用
  177. this.AMap = null;
  178. this.driving = null;
  179. if (this.infoCloseTimer) {
  180. clearTimeout(this.infoCloseTimer);
  181. this.infoCloseTimer = null;
  182. }
  183. this.activeInfoWindowId = null;
  184. this.isInfoWindowHovered = false;
  185. },
  186. computed: {
  187. // 全选状态:仅判断"图例上可见的项"是否全部启用,不受常隐项(如降级)影响
  188. isAllSelected() {
  189. const visible = this.legendStatusConfig.map(i => i.name);
  190. if (visible.length === 0) return false;
  191. return visible.every(n => this.activeLegends.includes(n));
  192. },
  193. isHomePage() {
  194. return this.$route && (this.$route.path === '/home' || this.$route.path === '/surve');
  195. },
  196. legendShowBtnStyle() {
  197. if (!this.isHomePage) return {};
  198. const right = (this.privateStyle.legend && this.privateStyle.legend.right) ? this.privateStyle.legend.right : '25%';
  199. return { right, borderRadius: '6px' };
  200. },
  201. searchBoxStyle() {
  202. return {
  203. position: 'fixed',
  204. top: `${this.searchOffsetTop}px`,
  205. right: `${this.searchOffsetRight}px`,
  206. zIndex: 999,
  207. };
  208. },
  209. legendStatusConfig() {
  210. // 1. 按 mode 过滤
  211. let list = this.statusConfig;
  212. if (this.mode === '路口') {
  213. list = list.filter(item => !['干线协调', '勤务路线'].includes(item.name));
  214. } else if (this.mode && this.mode !== '路口') {
  215. return [];
  216. }
  217. // 2. hideInLegend 项一律不进图例(数据与地图绘制不受影响)
  218. list = list.filter(item => !item.hideInLegend);
  219. // 3. 仅展示路口/路线实际存在的控制模式:
  220. // - 路线类(type: route)固定有线段配置,始终显示
  221. // - 其余按 statusIntersections[name] 是否非空过滤
  222. list = list.filter(item => {
  223. if (item.type === 'route') return true;
  224. const ints = this.statusIntersections && this.statusIntersections[item.name];
  225. return ints && ints.length > 0;
  226. });
  227. return list;
  228. },
  229. // 自动计算并下发给所有 CSS 的变量字典
  230. mapCssVars() {
  231. const size = this.currentZoomSize;
  232. const specialSize = Math.max(12, size * 1.2);
  233. return {
  234. '--dot-size': `${size}px`,
  235. '--dot-padding': size >= 14 ? '4px' : '0px',
  236. '--text-display': size >= 14 ? 'flex' : 'none',
  237. '--text-size': `${Math.max(10, size - 4)}px`,
  238. '--special-size': `${specialSize}px`
  239. };
  240. }
  241. },
  242. methods: {
  243. // 视口裁剪(Phase 1,详见 pyscripts/AMap路口marker视口加载与聚合设计.md)
  244. /**
  245. * 单一调度入口:根据 map.getBounds() 与 activeLegends 计算应显示的 marker 集合,
  246. * 与已挂载集合做 diff,批量 add/remove。
  247. */
  248. computeVisibleMarkers() {
  249. if (!this.isMapReady()) return;
  250. const bounds = this.map.getBounds();
  251. if (!bounds) return;
  252. // 视口外扩 buffer,避免边缘 marker 在拖动停下时立刻消失
  253. const expanded = this.expandBounds(bounds, this.viewportBufferRatio);
  254. const visibleLegendNames = new Set(this.activeLegends);
  255. const shouldShow = new Set();
  256. // 收集应显示的 overlay
  257. Object.keys(this.routeGroups).forEach(name => {
  258. const overlays = this.routeGroups[name];
  259. if (!overlays || overlays.length === 0) return;
  260. if (!visibleLegendNames.has(name)) return;
  261. for (const o of overlays) {
  262. // 路线(折线/弧线/装饰)—— 不参与视口裁剪
  263. if (!this.isMarkerNode(o)) {
  264. shouldShow.add(o);
  265. continue;
  266. }
  267. // 起终点 marker —— 不参与视口裁剪(数量极少)
  268. if (this.isStartEndMarker(o)) {
  269. shouldShow.add(o);
  270. continue;
  271. }
  272. // 普通路口 marker —— 按视口判定
  273. const pos = this.getOverlayPosition(o);
  274. if (pos && this.boundsContains(expanded, pos)) {
  275. shouldShow.add(o);
  276. }
  277. }
  278. });
  279. // InfoWindow 打开期间 marker 豁免:始终保留以避免底层 marker 被移除导致弹窗错位
  280. if (this._infoWindowProtectedMarker) {
  281. shouldShow.add(this._infoWindowProtectedMarker);
  282. }
  283. // diff
  284. const toAdd = [];
  285. const toRemove = [];
  286. shouldShow.forEach(o => {
  287. if (!this.mountedMarkerSet.has(o)) toAdd.push(o);
  288. });
  289. this.mountedMarkerSet.forEach(o => {
  290. if (!shouldShow.has(o)) toRemove.push(o);
  291. });
  292. if (toAdd.length) {
  293. try { this.map.add(toAdd); } catch (e) { void e; }
  294. toAdd.forEach(o => this.mountedMarkerSet.add(o));
  295. }
  296. if (toRemove.length) {
  297. try { this.map.remove(toRemove); } catch (e) { void e; }
  298. toRemove.forEach(o => this.mountedMarkerSet.delete(o));
  299. }
  300. },
  301. /**
  302. * 拖图/缩放后合并触发的视口刷新;100ms 内多次调用合并为一次。
  303. */
  304. scheduleViewportRefresh() {
  305. if (this._viewportRefreshTimer) return;
  306. this._viewportRefreshTimer = setTimeout(() => {
  307. this._viewportRefreshTimer = null;
  308. this.computeVisibleMarkers();
  309. }, this.viewportRefreshDebounceMs);
  310. },
  311. /**
  312. * 视口外扩 ratio 比例,避免在边界处 marker 闪入闪出。
  313. */
  314. expandBounds(bounds, ratio) {
  315. const sw = bounds.getSouthWest();
  316. const ne = bounds.getNorthEast();
  317. const dLng = (ne.lng - sw.lng) * ratio;
  318. const dLat = (ne.lat - sw.lat) * ratio;
  319. return new this.AMap.Bounds(
  320. [sw.lng - dLng, sw.lat - dLat],
  321. [ne.lng + dLng, ne.lat + dLat]
  322. );
  323. },
  324. /**
  325. * 兼容多种 position 形态([lng,lat] 数组 / LngLat 对象)的 contains 判定。
  326. */
  327. boundsContains(bounds, pos) {
  328. try {
  329. if (Array.isArray(pos)) {
  330. return bounds.contains(new this.AMap.LngLat(pos[0], pos[1]));
  331. }
  332. return bounds.contains(pos);
  333. } catch (e) {
  334. return false;
  335. }
  336. },
  337. isMarkerNode(o) {
  338. return this.AMap && o instanceof this.AMap.Marker;
  339. },
  340. isStartEndMarker(o) {
  341. if (!o || !this.startEndMarkers || this.startEndMarkers.length === 0) return false;
  342. for (const s of this.startEndMarkers) {
  343. if (s.marker === o) return true;
  344. }
  345. return false;
  346. },
  347. /**
  348. * 取 overlay 经纬位置:优先用 marker.getPosition(),回退到 extData.position。
  349. */
  350. getOverlayPosition(o) {
  351. if (!o) return null;
  352. if (typeof o.getPosition === 'function') {
  353. const p = o.getPosition();
  354. if (p) return p;
  355. }
  356. const ext = (typeof o.getExtData === 'function') ? o.getExtData() : null;
  357. return ext && ext.position;
  358. },
  359. /**
  360. * 动态加载地图数据
  361. * @returns {Promise<void>}
  362. */
  363. async loadMapData() {
  364. try {
  365. const mapDataModule = await import('@/mock/map_data_gaode.json');
  366. this.intersectionData = mapDataModule.default || [];
  367. console.log('地图数据加载成功,共', this.intersectionData.length, '个路口');
  368. } catch (error) {
  369. console.error('地图数据加载失败:', error);
  370. this.intersectionData = [];
  371. }
  372. },
  373. /**
  374. * 检查地图环境是否安全可用
  375. * @returns {boolean}
  376. */
  377. isMapReady() {
  378. return !this.isComponentDestroyed && this.map && typeof this.map.add === 'function';
  379. },
  380. /**
  381. * 将真实路口数据按状态类型分类
  382. */
  383. classifyIntersectionsByStatus() {
  384. const categories = {
  385. "中心计划": [], "干线协调": [], "勤务路线": [],
  386. "定周期控制": [], "感应控制": [], "自适应控制": [],
  387. "手动控制": [],
  388. "黄闪": [], "全红": [], "关灯": [],
  389. "离线": [], "降级": [], "故障": []
  390. };
  391. for (const item of this.intersectionData) {
  392. const category = getIntersectionCategory(item["路口编号"]);
  393. if (categories[category]) {
  394. categories[category].push(item);
  395. }
  396. }
  397. this.statusIntersections = categories;
  398. },
  399. /**
  400. * 根据模式更新地图显示
  401. */
  402. updateMapByMode() {
  403. switch (this.mode) {
  404. case '路口':
  405. this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "黄闪", "全红", "关灯", "离线", "降级", "故障"];
  406. break;
  407. case '干线':
  408. this.activeLegends = ["干线协调"];
  409. break;
  410. case '特勤':
  411. this.activeLegends = ["勤务路线"];
  412. break;
  413. default:
  414. this.activeLegends = this.statusConfig.map(item => item.name);
  415. }
  416. },
  417. /**
  418. * 更新地图显示状态:统一委托给视口裁剪调度器,
  419. * 由 computeVisibleMarkers 综合 activeLegends + bounds 决定 add/remove。
  420. */
  421. updateMapDisplay() {
  422. if (this.infoWindow) this.infoWindow.close();
  423. if (!this.isMapReady()) return;
  424. this.computeVisibleMarkers();
  425. },
  426. /**
  427. * 初始化高德地图
  428. * @returns {Promise<void>}
  429. */
  430. async initAMap() {
  431. if (this.isComponentDestroyed) return;
  432. window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
  433. try {
  434. const AMap = await AMapLoader.load({
  435. key: this.amapKey,
  436. version: "2.0",
  437. plugins: ['AMap.Driving']
  438. });
  439. if (this.isComponentDestroyed) return;
  440. this.AMap = AMap;
  441. this.map = new AMap.Map(this.$refs.mapContainer, {
  442. zoom: 15,
  443. mapStyle: "amap://styles/darkblue",
  444. center: [116.663, 39.905]
  445. });
  446. this.driving = new AMap.Driving({ map: null, hideMarkers: true });
  447. this.map.on('complete', () => {
  448. if (!this.isComponentDestroyed) {
  449. this.currentZoomSize = this.getDotSizeByZoom();
  450. this.drawStaticRoutes();
  451. }
  452. });
  453. this.map.on('zoomend', () => {
  454. if (!this.isComponentDestroyed) {
  455. this.currentZoomSize = this.getDotSizeByZoom();
  456. this.rebuildStartEndMarkers();
  457. this.rebuildDotMarkers();
  458. this.rebuildSubAreaText();
  459. // 视口裁剪:缩放后重算视口内 marker
  460. this.scheduleViewportRefresh();
  461. }
  462. });
  463. // 视口裁剪:拖图停下后重算视口内 marker(debounce 100ms)
  464. this.map.on('moveend', () => {
  465. if (!this.isComponentDestroyed) {
  466. this.scheduleViewportRefresh();
  467. }
  468. });
  469. } catch (err) {
  470. console.error('地图加载失败:', err);
  471. }
  472. },
  473. /**
  474. * 绘制静态路线和标记
  475. * @returns {Promise<void>}
  476. */
  477. async drawStaticRoutes() {
  478. if (!this.isMapReady()) return;
  479. this.drawSeq += 1;
  480. const drawSeq = this.drawSeq;
  481. this.clearAllRouteOverlays();
  482. const realRouteConfigs = {
  483. "干线协调": [
  484. { start: [116.6421, 39.9272], end: [116.6623, 39.9272], color: "#13C373", trunkId: 'trunk_1', trunkName: '古城南路与古城大街' },
  485. { start: [116.6623, 39.9272], end: [116.6825, 39.9272], color: "#13C373", trunkId: 'trunk_2', trunkName: '古城西路东口南一过街' },
  486. { start: [116.6426, 39.9221], end: [116.6628, 39.9221], color: "#13C373", trunkId: 'trunk_3', trunkName: '古城大街与古城北路' },
  487. { start: [116.6628, 39.9221], end: [116.683, 39.9221], color: "#13C373", trunkId: 'trunk_4', trunkName: '八角北路与八角东街' },
  488. { start: [116.6432, 39.9171], end: [116.66325, 39.9171], color: "#13C373", trunkId: 'trunk_5', trunkName: '古城西路与古城大街' },
  489. { start: [116.66325, 39.9171], end: [116.6833, 39.9171], color: "#13C373", trunkId: 'trunk_6', trunkName: '张台路与湖亦路路口' },
  490. ],
  491. "勤务路线": [
  492. { start: [116.6400, 39.9270], end: [116.7000, 39.9270], color: "#BC301D", dutyState: 'pending', taskId: 1 },
  493. { start: [116.6400, 39.9120], end: [116.7000, 39.9120], color: "#BC301D", dutyState: 'active', progress: 0.45, taskId: 3 },
  494. { start: [116.6700, 39.8970], end: [116.7300, 39.8970], color: "#BC301D", dutyState: 'done', taskId: 2 },
  495. { start: [116.6400, 39.8820], end: [116.7000, 39.8820], color: "#BC301D", dutyState: 'done', taskId: 4 },
  496. { start: [116.6400, 39.8670], end: [116.7000, 39.8670], color: "#BC301D", dutyState: 'pending', taskId: 5 }
  497. ]
  498. };
  499. for (const config of this.statusConfig) {
  500. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  501. if (!realRouteConfigs[config.name]) {
  502. const intersections = this.statusIntersections[config.name] || [];
  503. const markers = intersections.map(item =>
  504. this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], {
  505. ...config,
  506. id: item["路口编号"],
  507. road: item["路口名称"] || '规划路口'
  508. })
  509. ).filter(Boolean);
  510. this.routeGroups[config.name] = markers;
  511. // 视口裁剪:不直接 add,由 computeVisibleMarkers 统一处理
  512. continue;
  513. }
  514. this.routeGroups[config.name] = [];
  515. const lines = realRouteConfigs[config.name] || [];
  516. const trunkSegments = [];
  517. for (let lineIdx = 0; lineIdx < lines.length; lineIdx += 1) {
  518. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  519. const line = lines[lineIdx];
  520. let path = null;
  521. try {
  522. path = await this.searchDrivingPathWithRetry(line.start, line.end);
  523. } catch (e) {
  524. path = null;
  525. }
  526. const overlays = this.buildRouteOverlaysFromPath({
  527. config,
  528. configName: config.name,
  529. line,
  530. lineIdx,
  531. path
  532. });
  533. if (config.name === '干线协调' && overlays.length > 0) {
  534. const name = line.trunkName || ('干线' + (lineIdx + 1));
  535. trunkSegments.push({
  536. id: line.trunkId || ('trunk_' + (lineIdx + 1)),
  537. label: name,
  538. intersections: Array.from({ length: 6 }, (_, k) => name + '_路口' + (k + 1)),
  539. distances: Array.from({ length: 6 }, (_, k) => k * 500),
  540. _lineIdx: lineIdx
  541. });
  542. }
  543. if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;
  544. if (overlays.length > 0) {
  545. this.routeGroups[config.name].push(...overlays);
  546. // 视口裁剪:每批新覆盖物入组后触发一次重算,让线/路口逐步出现在视口
  547. this.computeVisibleMarkers();
  548. }
  549. await this.sleep(80);
  550. }
  551. if (config.name === '干线协调' && trunkSegments.length > 0) {
  552. this.$emit('bindTrunkMenuTree', trunkSegments);
  553. }
  554. }
  555. // 全部 routeGroups 准备好后再做一次终态刷新
  556. this.computeVisibleMarkers();
  557. },
  558. /**
  559. * 清除所有路线覆盖物
  560. */
  561. clearAllRouteOverlays() {
  562. if (!this.isMapReady()) return;
  563. try {
  564. if (this.infoWindow) this.infoWindow.close();
  565. } catch (e) {
  566. void e;
  567. }
  568. Object.values(this.routeGroups || {}).forEach(overlays => {
  569. if (!Array.isArray(overlays) || overlays.length === 0) return;
  570. try {
  571. this.map.remove(overlays);
  572. } catch (e) {
  573. void e;
  574. }
  575. overlays.forEach(o => {
  576. try {
  577. if (o && typeof o.setMap === 'function') o.setMap(null);
  578. } catch (e) {
  579. void e;
  580. }
  581. });
  582. });
  583. this.routeGroups = {};
  584. this.startEndMarkers = [];
  585. this.dotMarkers = [];
  586. // 重置视口裁剪挂载集(已 map.remove 过,这里只清引用)
  587. this.mountedMarkerSet.clear();
  588. },
  589. /**
  590. * 休眠函数
  591. * @param {number} ms - 休眠毫秒数
  592. * @returns {Promise<void>}
  593. */
  594. sleep(ms) {
  595. return new Promise(resolve => setTimeout(resolve, ms));
  596. },
  597. /**
  598. * 带重试机制的路径规划
  599. * @param {Array<number>} start - 起点坐标 [lng, lat]
  600. * @param {Array<number>} end - 终点坐标 [lng, lat]
  601. * @returns {Promise<Array>} 路径点数组
  602. */
  603. async searchDrivingPathWithRetry(start, end) {
  604. if (!this.AMap || !this.driving || typeof this.driving.search !== 'function') {
  605. throw new Error('Driving not ready');
  606. }
  607. const maxAttempts = 3;
  608. let lastErr = null;
  609. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
  610. try {
  611. return await this.withTimeout(this.searchDrivingPathOnce(start, end), 8000);
  612. } catch (e) {
  613. lastErr = e;
  614. await this.sleep(250 * attempt);
  615. }
  616. }
  617. throw lastErr || new Error('Driving search failed');
  618. },
  619. /**
  620. * 单次路径规划
  621. * @param {Array<number>} start - 起点坐标 [lng, lat]
  622. * @param {Array<number>} end - 终点坐标 [lng, lat]
  623. * @returns {Promise<Array>} 路径点数组
  624. */
  625. searchDrivingPathOnce(start, end) {
  626. return new Promise((resolve, reject) => {
  627. this.driving.search(start, end, (status, result) => {
  628. const route = result && result.routes && result.routes[0];
  629. if (status === 'complete' && route && Array.isArray(route.steps)) {
  630. const fullPath = [];
  631. route.steps.forEach(step => {
  632. if (step && Array.isArray(step.path)) fullPath.push(...step.path);
  633. });
  634. if (fullPath.length >= 2) resolve(fullPath);
  635. else reject(new Error('empty_path'));
  636. return;
  637. }
  638. reject(new Error(typeof status === 'string' ? status : 'driving_error'));
  639. });
  640. });
  641. },
  642. /**
  643. * 为Promise添加超时机制
  644. * @param {Promise} promise - 要执行的Promise
  645. * @param {number} timeoutMs - 超时毫秒数
  646. * @returns {Promise} 带超时的Promise
  647. */
  648. withTimeout(promise, timeoutMs) {
  649. return Promise.race([
  650. promise,
  651. new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
  652. ]);
  653. },
  654. /**
  655. * 从路径构建路线覆盖物
  656. * @param {Object} params - 参数对象
  657. * @param {Object} params.config - 配置对象
  658. * @param {string} params.configName - 配置名称
  659. * @param {Object} params.line - 路线配置
  660. * @param {number} params.lineIdx - 路线索引
  661. * @param {Array} params.path - 路径点数组
  662. * @returns {Array} 覆盖物数组
  663. */
  664. buildRouteOverlaysFromPath({ config, configName, line, lineIdx, path }) {
  665. if (!this.AMap || !this.map) return [];
  666. let basePath = path;
  667. if (!Array.isArray(basePath) || basePath.length < 2) {
  668. basePath = this.buildFallbackLinePath(line.start, line.end, 30);
  669. }
  670. const offsetVal = 0;
  671. const applyOffset = (p) => {
  672. const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
  673. const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
  674. return [lng + offsetVal, lat + offsetVal];
  675. };
  676. const allSegments = this.extractMainStraightSegments(basePath);
  677. const segments = configName === '干线协调'
  678. ? allSegments.slice(0, 1)
  679. : configName === '勤务路线'
  680. ? [basePath]
  681. : allSegments;
  682. const overlays = [];
  683. segments.forEach((rawSegmentPath, segmentIdx) => {
  684. if (!Array.isArray(rawSegmentPath) || rawSegmentPath.length < 2) return;
  685. const segmentPath = rawSegmentPath.map(p => applyOffset(p));
  686. if (configName === '勤务路线' && line.dutyState) {
  687. const state = line.dutyState; // 'pending' | 'active' | 'done'
  688. const progress = (state === 'active') ? Math.min(Math.max(Number(line.progress) || 0.5, 0), 1) : (state === 'done' ? 1 : 0);
  689. // 计算整段累计距离
  690. const dists = [0];
  691. let totalDist = 0;
  692. for (let j = 0; j < segmentPath.length - 1; j++) {
  693. totalDist += this.calcApproxDistance(segmentPath[j], segmentPath[j + 1]);
  694. dists.push(totalDist);
  695. }
  696. const splitDist = totalDist * progress;
  697. // 找切割点坐标(线性插值)
  698. let splitIdx = segmentPath.length - 1;
  699. let splitPoint = segmentPath[segmentPath.length - 1];
  700. for (let j = 0; j < dists.length - 1; j++) {
  701. if (splitDist >= dists[j] && splitDist <= dists[j + 1]) {
  702. const ratio = dists[j + 1] === dists[j] ? 0 : (splitDist - dists[j]) / (dists[j + 1] - dists[j]);
  703. const p1 = segmentPath[j], p2 = segmentPath[j + 1];
  704. splitPoint = [
  705. Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio,
  706. Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio
  707. ];
  708. splitIdx = j;
  709. break;
  710. }
  711. }
  712. // 已过段(灰色)
  713. const passedPath = [...segmentPath.slice(0, splitIdx + 1), splitPoint];
  714. if (passedPath.length >= 2) {
  715. overlays.push(new this.AMap.Polyline({
  716. path: passedPath,
  717. strokeColor: '#5A5A5A',
  718. strokeWeight: 6,
  719. strokeOpacity: 0.45,
  720. zIndex: 15
  721. }));
  722. }
  723. // 未过段(原红色),done 状态不绘制
  724. const remainPath = [splitPoint, ...segmentPath.slice(splitIdx + 1)];
  725. if (state !== 'done' && remainPath.length >= 2) {
  726. overlays.push(new this.AMap.Polyline({
  727. path: remainPath,
  728. strokeColor: line.color,
  729. strokeWeight: 6,
  730. strokeOpacity: 0.8,
  731. zIndex: 15
  732. }));
  733. }
  734. // 执行中:进度点脉冲 marker
  735. if (state === 'active') {
  736. overlays.push(new this.AMap.Marker({
  737. position: splitPoint,
  738. zIndex: 150,
  739. anchor: 'center',
  740. bubble: true,
  741. content: `<div class="duty-progress-node" style="width:var(--special-size);height:var(--special-size);border-radius:50%;background:#BC301D;border:3px solid #fff;box-shadow:0 0 0 3px rgba(188,48,29,0.4);display:flex;justify-content:center;align-items:center;cursor:default;"><div style="width:30%;height:30%;border-radius:50%;background:#fff;"></div></div>`
  742. }));
  743. }
  744. // 方向箭头:已过段灰色低透明,未过段正常
  745. const targetSpacing = 0.0036;
  746. let arrowDist = targetSpacing / 2;
  747. while (arrowDist < totalDist) {
  748. let foundIdx = 0;
  749. for (let j = 0; j < dists.length - 1; j++) {
  750. if (arrowDist >= dists[j] && arrowDist <= dists[j + 1]) { foundIdx = j; break; }
  751. }
  752. const p1 = segmentPath[foundIdx], p2 = segmentPath[foundIdx + 1];
  753. if (p1 && p2) {
  754. const ratio = (arrowDist - dists[foundIdx]) / (dists[foundIdx + 1] - dists[foundIdx]);
  755. const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
  756. const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
  757. const isPassed = arrowDist <= splitDist;
  758. const rotation = this.calcBearingDeg(p1, p2) - 90;
  759. overlays.push(new this.AMap.Marker({
  760. position: [midLng, midLat],
  761. content: `<div style="transform:rotate(${rotation}deg);width:20px;height:10px;display:flex;align-items:center;pointer-events:none;opacity:${isPassed ? 0.2 : 0.85};filter:${isPassed ? 'grayscale(1)' : 'none'};"><img src="${require('@/assets/map/direction.png')}" style="width:100%;height:auto;" /></div>`,
  762. offset: new this.AMap.Pixel(-10, -5),
  763. zIndex: 20,
  764. bubble: true
  765. }));
  766. }
  767. arrowDist += targetSpacing;
  768. }
  769. // 路口圆点:已过置灰,未过正常
  770. const indices = this.pickEvenlySpacedIndices(segmentPath.length, 6);
  771. for (let i = 0; i < indices.length; i++) {
  772. const idx = indices[i];
  773. const p = segmentPath[idx];
  774. const lng = Number(p[0]), lat = Number(p[1]);
  775. if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
  776. const dotDist = dists[idx] || 0;
  777. let markerType = 'normal';
  778. if (i === 0) markerType = 'start';
  779. else if (i === indices.length - 1) markerType = 'end';
  780. const isPastDot = dotDist <= splitDist;
  781. const dotConfig = isPastDot
  782. ? { ...config, color: '#5A5A5A', id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}`, taskId: line.taskId, dutyState: line.dutyState }
  783. : { ...config, id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}`, taskId: line.taskId, dutyState: line.dutyState };
  784. const dotType = isPastDot && markerType === 'normal' ? 'passed' : markerType;
  785. const marker = this.createTrafficLightMarker([lng, lat], dotConfig, dotType);
  786. if (marker) overlays.push(marker);
  787. }
  788. } else {
  789. // 非勤务路线 或 无 dutyState:原有逻辑
  790. const polyline = new this.AMap.Polyline({
  791. path: segmentPath,
  792. strokeColor: line.color,
  793. strokeWeight: 6,
  794. strokeOpacity: 0.8,
  795. zIndex: 15
  796. });
  797. overlays.push(polyline);
  798. const totalPoints = segmentPath.length;
  799. const pathDistances = [0];
  800. let totalPathDist = 0;
  801. for (let j = 0; j < totalPoints - 1; j++) {
  802. const d = this.calcApproxDistance(segmentPath[j], segmentPath[j+1]);
  803. totalPathDist += d;
  804. pathDistances.push(totalPathDist);
  805. }
  806. if (configName !== '干线协调') {
  807. const targetSpacing = configName === '勤务路线' ? 0.0036 : 0.0018;
  808. let currentTargetDist = targetSpacing / 2;
  809. while (currentTargetDist < totalPathDist) {
  810. let foundIdx = 0;
  811. for (let j = 0; j < pathDistances.length - 1; j++) {
  812. if (currentTargetDist >= pathDistances[j] && currentTargetDist <= pathDistances[j + 1]) {
  813. foundIdx = j;
  814. break;
  815. }
  816. }
  817. const p1 = segmentPath[foundIdx];
  818. const p2 = segmentPath[foundIdx + 1];
  819. if (p1 && p2) {
  820. const ratio = (currentTargetDist - pathDistances[foundIdx]) / (pathDistances[foundIdx + 1] - pathDistances[foundIdx]);
  821. const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
  822. const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
  823. const bearing = this.calcBearingDeg(p1, p2);
  824. const rotation = bearing - 90;
  825. const directionMarker = new this.AMap.Marker({
  826. position: [midLng, midLat],
  827. content: `
  828. <div style="transform: rotate(${rotation}deg); width: 20px; height: 10px; display: flex; align-items: center; pointer-events: none; opacity: 0.85;">
  829. <img src="${require('@/assets/map/direction.png')}" style="width: 100%; height: auto;" />
  830. </div>
  831. `,
  832. offset: new this.AMap.Pixel(-10, -5),
  833. zIndex: 20,
  834. bubble: true
  835. });
  836. overlays.push(directionMarker);
  837. }
  838. currentTargetDist += targetSpacing;
  839. }
  840. }
  841. const indices = this.pickEvenlySpacedIndices(totalPoints, 6);
  842. for (let i = 0; i < indices.length; i++) {
  843. const idx = indices[i];
  844. const p = segmentPath[idx];
  845. const lng = Number(p[0]);
  846. const lat = Number(p[1]);
  847. if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
  848. let markerType = 'normal';
  849. if (configName !== '干线协调') {
  850. if (i === 0) markerType = 'start';
  851. else if (i === indices.length - 1) markerType = 'end';
  852. }
  853. // 干线协调:id 用干线编号,road 用干线名称(与菜单标题一致)
  854. const markerId = (configName === '干线协调' && line.trunkId)
  855. ? `${line.trunkId}_point_${i + 1}`
  856. : `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${idx}`;
  857. const markerRoad = (configName === '干线协调' && line.trunkName)
  858. ? line.trunkName
  859. : `${configName}路口-${lineIdx}-${segmentIdx}-${idx}`;
  860. const marker = this.createTrafficLightMarker([lng, lat], {
  861. ...config,
  862. id: markerId,
  863. road: markerRoad
  864. }, markerType);
  865. if (marker) overlays.push(marker);
  866. }
  867. } // end else
  868. }); // end segments.forEach
  869. return overlays;
  870. },
  871. /**
  872. * 均匀选取点的索引
  873. * @param {number} totalPoints - 总点数
  874. * @param {number} count - 要选取的点数
  875. * @returns {Array<number>} 索引数组
  876. */
  877. pickEvenlySpacedIndices(totalPoints, count) {
  878. const total = Math.max(Number(totalPoints) || 0, 0);
  879. const target = Math.max(Number(count) || 0, 0);
  880. if (total <= 0 || target <= 0) return [];
  881. if (target >= total) return Array.from({ length: total }, (_, i) => i);
  882. if (target === 1) return [0];
  883. return Array.from({ length: target }, (_, k) => Math.round((k * (total - 1)) / (target - 1)));
  884. },
  885. /**
  886. * 构建备选线路路径
  887. * @param {Array<number>} start - 起点坐标 [lng, lat]
  888. * @param {Array<number>} end - 终点坐标 [lng, lat]
  889. * @param {number} pointCount - 点数量
  890. * @returns {Array} 路径点数组
  891. */
  892. buildFallbackLinePath(start, end, pointCount) {
  893. const sLng = Number(start && start[0]);
  894. const sLat = Number(start && start[1]);
  895. const eLng = Number(end && end[0]);
  896. const eLat = Number(end && end[1]);
  897. const n = Math.max(Number(pointCount) || 2, 2);
  898. const path = [];
  899. if ([sLng, sLat, eLng, eLat].some(v => Number.isNaN(v))) return path;
  900. for (let i = 0; i < n; i += 1) {
  901. const t = n === 1 ? 0 : i / (n - 1);
  902. const lng = sLng + (eLng - sLng) * t;
  903. const lat = sLat + (eLat - sLat) * t;
  904. path.push({ lng, lat });
  905. }
  906. return path;
  907. },
  908. /**
  909. * 提取主要直线段
  910. * @param {Array} path - 路径点数组
  911. * @returns {Array} 直线段数组
  912. */
  913. extractMainStraightSegments(path) {
  914. const getCoord = (p) => {
  915. if (!p) return { lng: NaN, lat: NaN };
  916. if (Array.isArray(p)) return { lng: Number(p[0]), lat: Number(p[1]) };
  917. if (p.getLng) return { lng: p.getLng(), lat: p.getLat() };
  918. return { lng: Number(p.lng), lat: Number(p.lat) };
  919. };
  920. const points = (path || []).map(p => getCoord(p)).filter(p => !isNaN(p.lng) && !isNaN(p.lat));
  921. if (points.length < 2) return [];
  922. const thresholdDeg = 18;
  923. const segments = [];
  924. let curStart = 0;
  925. let curAngle = null;
  926. let curLen = 0;
  927. const pushSegment = (endIdx) => {
  928. if (endIdx <= curStart) return;
  929. segments.push({
  930. start: curStart,
  931. end: endIdx,
  932. len: curLen
  933. });
  934. };
  935. for (let i = 0; i < points.length - 1; i += 1) {
  936. const a = points[i];
  937. const b = points[i + 1];
  938. const len = this.calcApproxDistance(a, b);
  939. if (len <= 0) continue;
  940. const angle = this.calcBearingDeg(a, b);
  941. if (curAngle === null) {
  942. curStart = i;
  943. curAngle = angle;
  944. curLen = len;
  945. continue;
  946. }
  947. const diff = this.calcAngleDiffDeg(curAngle, angle);
  948. if (diff <= thresholdDeg) {
  949. curLen += len;
  950. } else {
  951. pushSegment(i);
  952. curStart = i;
  953. curAngle = angle;
  954. curLen = len;
  955. }
  956. }
  957. pushSegment(points.length - 2);
  958. if (segments.length === 0) return [points];
  959. segments.sort((s1, s2) => s2.len - s1.len);
  960. const maxLen = segments[0].len || 0;
  961. const filtered = segments.filter(s => s.len >= maxLen * 0.55).slice(0, 3);
  962. const finalSegments = filtered.map(s => points.slice(s.start, s.end + 2));
  963. return finalSegments.length > 0 ? finalSegments : [points];
  964. },
  965. /**
  966. * 从不同格式的点中提取经纬度数组 [lng, lat]
  967. * @param {Object|Array} p - 点对象或数组
  968. * @returns {Array<number>} 经纬度数组
  969. */
  970. _getCoords(p) {
  971. if (!p) return [0, 0];
  972. const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
  973. const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
  974. return [lng, lat];
  975. },
  976. /**
  977. * 计算两点之间的方位角(度)
  978. * @param {Object|Array} a - 起点
  979. * @param {Object|Array} b - 终点
  980. * @returns {number} 方位角
  981. */
  982. calcBearingDeg(a, b) {
  983. const [alng, alat] = this._getCoords(a);
  984. const [blng, blat] = this._getCoords(b);
  985. const latRad = ((alat + blat) / 2) * Math.PI / 180;
  986. const dx = (blng - alng) * Math.cos(latRad);
  987. const dy = (blat - alat);
  988. const mathAngle = Math.atan2(dy, dx) * 180 / Math.PI;
  989. return (90 - mathAngle + 360) % 360;
  990. },
  991. /**
  992. * 计算两个角度的差值
  993. * @param {number} a - 角度1
  994. * @param {number} b - 角度2
  995. * @returns {number} 角度差
  996. */
  997. calcAngleDiffDeg(a, b) {
  998. let diff = Math.abs(a - b);
  999. if (diff > 180) diff = 360 - diff;
  1000. return diff;
  1001. },
  1002. /**
  1003. * 计算两点之间的近似距离
  1004. * @param {Object|Array} a - 点1
  1005. * @param {Object|Array} b - 点2
  1006. * @returns {number} 距离
  1007. */
  1008. calcApproxDistance(a, b) {
  1009. const [alng, alat] = this._getCoords(a);
  1010. const [blng, blat] = this._getCoords(b);
  1011. const latRad = ((alat + blat) / 2) * Math.PI / 180;
  1012. const dx = (blng - alng) * Math.cos(latRad);
  1013. const dy = (blat - alat);
  1014. return Math.sqrt(dx * dx + dy * dy);
  1015. },
  1016. /**
  1017. * 根据当前缩放级别计算普通圆点的尺寸(px)
  1018. * @returns {number} 圆点尺寸
  1019. */
  1020. getDotSizeByZoom() {
  1021. if (!this.map) return 14;
  1022. const zoom = this.map.getZoom();
  1023. // 基准:zoom=15时是20px。每缩小一级减小3px。
  1024. const size = 20 + (zoom - 15) * 3;
  1025. return Math.min(Math.max(6, size), 32); // 最小值设为 6px
  1026. },
  1027. /**
  1028. * 缩放后重建起点/终点 marker,让高德重新计算 anchor 偏移
  1029. */
  1030. rebuildStartEndMarkers() {
  1031. if (!this.map || this.startEndMarkers.length === 0) return;
  1032. for (const entry of this.startEndMarkers) {
  1033. const { marker, position, config, type } = entry;
  1034. // 生成新的 content HTML(此时 CSS 变量已更新)
  1035. const size = this.currentZoomSize;
  1036. const specialSize = Math.max(12, size * 1.2);
  1037. const newContent = `
  1038. <div class="pure-light-node start-end-node" style="width: ${specialSize}px; height: ${specialSize + 6}px; background: transparent; border: none; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transform-origin: bottom center;">
  1039. <img src="${require(`@/assets/map/${type}.png`)}" style="width: 100%; height: auto; object-fit: contain; pointer-events: none;" />
  1040. </div>
  1041. `;
  1042. marker.setContent(newContent);
  1043. }
  1044. },
  1045. rebuildDotMarkers() {
  1046. if (!this.map || this.dotMarkers.length === 0) return;
  1047. const size = this.currentZoomSize;
  1048. const textDisplay = size >= 14 ? 'flex' : 'none';
  1049. const textSize = `${Math.max(10, size - 4)}px`;
  1050. for (const entry of this.dotMarkers) {
  1051. const { marker, config, isPassed } = entry;
  1052. if (isPassed) {
  1053. marker.setContent(`
  1054. <div class="pure-light-node" style="width: ${size}px; height: ${size}px; background: #5A5A5A; border: 1.5px solid rgba(255,255,255,0.25); box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; opacity: 0.55;">
  1055. <span style="display: ${textDisplay}; font-weight: bold; font-size: ${textSize};">勤</span>
  1056. </div>
  1057. `);
  1058. } else {
  1059. const displayText = config.name ? config.name.charAt(0) : '';
  1060. marker.setContent(`
  1061. <div class="pure-light-node route-node" style="width: ${size}px; height: ${size}px; background: ${config.color || '#999'}; box-shadow: none; border: none; box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer;">
  1062. <span style="display: ${textDisplay}; font-weight: bold; font-size: ${textSize};">${displayText}</span>
  1063. </div>
  1064. `);
  1065. }
  1066. }
  1067. },
  1068. /**
  1069. * 创建交通信号灯标记
  1070. * @param {Array<number>|Object} position - 位置坐标
  1071. * @param {Object} config - 配置对象
  1072. * @param {string} [type='normal'] - 标记类型
  1073. * @returns {Object|null} 标记对象
  1074. */
  1075. createTrafficLightMarker(position, config, type = 'normal') {
  1076. if (!position || !config) return null;
  1077. try {
  1078. const lng = position.getLng ? position.getLng() : Number(position[0] !== undefined ? position[0] : position.lng);
  1079. const lat = position.getLat ? position.getLat() : Number(position[1] !== undefined ? position[1] : position.lat);
  1080. if (isNaN(lng) || isNaN(lat)) return null;
  1081. let displayText = config.name ? config.name.charAt(0) : '';
  1082. if (type === 'start') displayText = '起';
  1083. if (type === 'end') displayText = '终';
  1084. const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
  1085. const isRoute = ["干线协调", "勤务路线"].includes(config.name);
  1086. const isStartEnd = type === 'start' || type === 'end';
  1087. const isPassed = type === 'passed';
  1088. let markerContent = '';
  1089. // --- 核心优化:尺寸全部使用 var(--xxx) CSS变量接管 ---
  1090. if (isStartEnd) {
  1091. markerContent = `
  1092. <div class="pure-light-node start-end-node" style="width: var(--special-size); height: calc(var(--special-size) + 6px); background: transparent; border: none; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transform-origin: bottom center;">
  1093. <img src="${require(`@/assets/map/${type}.png`)}" style="width: 100%; height: auto; object-fit: contain; pointer-events: none;" />
  1094. </div>
  1095. `;
  1096. } else if (isPassed) {
  1097. markerContent = `
  1098. <div class="pure-light-node" style="width: var(--dot-size); height: var(--dot-size); background: #5A5A5A; border: 1.5px solid rgba(255,255,255,0.25); box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; opacity: 0.55;">
  1099. <span style="display: var(--text-display); font-weight: bold; font-size: var(--text-size);">勤</span>
  1100. </div>
  1101. `;
  1102. } else if (isAbnormal) {
  1103. const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
  1104. markerContent = `
  1105. <div class="pure-light-node breathe" style="width: var(--special-size); height: var(--special-size); background: transparent; border: none; display: flex; justify-content: center; align-items: center; cursor: pointer; padding: 0;">
  1106. <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
  1107. </div>
  1108. `;
  1109. } else {
  1110. markerContent = `
  1111. <div class="pure-light-node ${isRoute ? 'route-node' : ''}" style="width: var(--dot-size); height: var(--dot-size); background: ${config.color || '#999'}; box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`}; border: ${isRoute ? 'none' : '1.5px solid rgba(255,255,255,0.7)'}; box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; padding: var(--dot-padding);">
  1112. <span style="display: var(--text-display); font-weight: bold; font-size: var(--text-size);">${displayText}</span>
  1113. </div>
  1114. `;
  1115. }
  1116. const marker = new this.AMap.Marker({
  1117. position: [lng, lat],
  1118. zIndex: isStartEnd ? 120 : (isAbnormal ? 110 : 100),
  1119. content: markerContent,
  1120. // 核心优化:高德 2.0 原生支持 anchor 属性。代替手动计算 Offset!
  1121. anchor: isStartEnd ? 'bottom-center' : 'center',
  1122. extData: {
  1123. ...config,
  1124. position: [lng, lat],
  1125. statusColor: config.color || '#999',
  1126. statusLabel: config.name,
  1127. road: config.road || '规划路口',
  1128. timestamp: Date.now(),
  1129. time: this.formatEventTime(Date.now())
  1130. }
  1131. });
  1132. // 建立 ID 索引
  1133. if (config.id) this.markerById[config.id] = marker;
  1134. if (config['路口编号']) this.markerById[config['路口编号']] = marker;
  1135. // 记录起点/终点 marker,缩放时需重建以修正 anchor 偏移
  1136. if (isStartEnd) {
  1137. this.startEndMarkers.push({ marker, position: [lng, lat], config, type });
  1138. }
  1139. // 记录勤务路线上的圆点 marker(passed + normal route),缩放时需重建
  1140. if (!isStartEnd && isRoute) {
  1141. this.dotMarkers.push({ marker, config, type, isPassed });
  1142. }
  1143. marker.on('click', (e) => {
  1144. if (this.isComponentDestroyed) return;
  1145. const extData = e.target.getExtData();
  1146. if (this.$route && this.$route.path === '/home') {
  1147. this.cancelCloseInfoWindow();
  1148. // 视口裁剪:标记当前展开 InfoWindow 的 marker,期间豁免裁剪
  1149. this._infoWindowProtectedMarker = e.target;
  1150. this.openLightInfo(extData, e.lnglat);
  1151. }
  1152. const pixel = this.map.lngLatToContainer(e.lnglat);
  1153. this.$emit('map-crossing-click', extData, e.lnglat, pixel);
  1154. });
  1155. marker.on('mouseover', (e) => {
  1156. if (this.isComponentDestroyed) return;
  1157. if (this.$route && this.$route.path === '/home') {
  1158. this.cancelCloseInfoWindow();
  1159. this._infoWindowProtectedMarker = e.target;
  1160. this.openLightInfo(e.target.getExtData(), e.lnglat);
  1161. }
  1162. const pixel = this.map.lngLatToContainer(e.lnglat);
  1163. this.$emit('map-crossing-mouseover', e.target.getExtData(), e.lnglat, pixel);
  1164. });
  1165. marker.on('mouseout', (e) => {
  1166. if (this.isComponentDestroyed) return;
  1167. if (this.$route && this.$route.path === '/home') {
  1168. this.scheduleCloseInfoWindow();
  1169. }
  1170. this.$emit('map-crossing-mouseout', e.target.getExtData());
  1171. });
  1172. return marker;
  1173. } catch (e) {
  1174. console.warn('创建标记时出错:', e);
  1175. return null;
  1176. }
  1177. },
  1178. /**
  1179. * 打开信号灯信息窗口
  1180. * @param {Object} data - 信号灯数据
  1181. * @param {Array<number>} position - 位置坐标
  1182. */
  1183. openLightInfo(data, position) {
  1184. if (!this.isMapReady()) return;
  1185. const infoWindowId = `info-window-${Date.now()}`;
  1186. this.activeInfoWindowId = infoWindowId;
  1187. const isAbnormal = ["离线", "降级", "故障"].includes(data.name);
  1188. const deviceStatusText = isAbnormal ? data.name : '正常';
  1189. const alarmInfoText = isAbnormal ? this.getAlarmInfoText(data.name) : '';
  1190. const eventTimeText = this.formatEventTime(data.timestamp || data.time);
  1191. let statusDotContent = '';
  1192. if (isAbnormal) {
  1193. const iconName = data.name === '离线' ? 'lixian' : data.name === '降级' ? 'jiangji' : 'guzhang';
  1194. statusDotContent = `<img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />`;
  1195. } else {
  1196. statusDotContent = `<span>${data.name.charAt(0)}</span>`;
  1197. }
  1198. const content = `
  1199. <div class="custom-info-card" id="${infoWindowId}">
  1200. <div class="close-btn" data-id="${infoWindowId}">✕</div>
  1201. <div class="card-header">
  1202. <div class="status-dot ${isAbnormal ? 'breathe' : ''}" style="background: ${isAbnormal ? 'transparent' : data.statusColor}; border: ${isAbnormal ? 'none' : ''}">
  1203. ${statusDotContent}
  1204. </div>
  1205. <span class="status-text">${data.statusLabel}</span>
  1206. </div>
  1207. <div class="card-body">
  1208. ${isAbnormal
  1209. ? `
  1210. <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
  1211. <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
  1212. <div class="info-line"><span class="label">报警信息:</span><span class="value">${alarmInfoText}</span></div>
  1213. <div class="info-line"><span class="label">发生时间:</span><span class="value digital">${eventTimeText}</span></div>
  1214. `
  1215. : `
  1216. <div class="info-line"><span class="label">路口名称:</span><span class="value">${data.road}</span></div>
  1217. <div class="info-line"><span class="label">设备状态:</span><span class="value digital">${deviceStatusText}</span></div>
  1218. `
  1219. }
  1220. </div>
  1221. </div>
  1222. `;
  1223. if (!this.infoWindow) {
  1224. this.infoWindow = new this.AMap.InfoWindow({
  1225. isCustom: true,
  1226. offset: new this.AMap.Pixel(0, -20),
  1227. autoMove: false
  1228. });
  1229. // 视口裁剪:InfoWindow 关闭时解除 marker 保护
  1230. this.infoWindow.on('close', () => {
  1231. this._infoWindowProtectedMarker = null;
  1232. });
  1233. }
  1234. this.infoWindow.setContent(content);
  1235. this.infoWindow.open(this.map, position);
  1236. setTimeout(() => {
  1237. if (this.activeInfoWindowId !== infoWindowId) return;
  1238. const closeBtn = document.querySelector(`#${infoWindowId} .close-btn`);
  1239. if (closeBtn) {
  1240. closeBtn.addEventListener('click', () => {
  1241. if (this.infoWindow) this.infoWindow.close();
  1242. });
  1243. }
  1244. const root = document.querySelector(`#${infoWindowId}`);
  1245. if (root) {
  1246. root.addEventListener('mouseenter', () => {
  1247. if (this.activeInfoWindowId !== infoWindowId) return;
  1248. this.isInfoWindowHovered = true;
  1249. this.cancelCloseInfoWindow();
  1250. });
  1251. root.addEventListener('mouseleave', () => {
  1252. if (this.activeInfoWindowId !== infoWindowId) return;
  1253. this.isInfoWindowHovered = false;
  1254. this.scheduleCloseInfoWindow();
  1255. });
  1256. }
  1257. }, 100);
  1258. },
  1259. /**
  1260. * 取消关闭信息窗口
  1261. */
  1262. cancelCloseInfoWindow() {
  1263. if (this.infoCloseTimer) {
  1264. clearTimeout(this.infoCloseTimer);
  1265. this.infoCloseTimer = null;
  1266. }
  1267. },
  1268. /**
  1269. * 安排关闭信息窗口
  1270. */
  1271. scheduleCloseInfoWindow() {
  1272. this.cancelCloseInfoWindow();
  1273. this.infoCloseTimer = setTimeout(() => {
  1274. if (this.isComponentDestroyed) return;
  1275. if (this.isInfoWindowHovered) return;
  1276. if (this.infoWindow) this.infoWindow.close();
  1277. this.activeInfoWindowId = null;
  1278. }, 160);
  1279. },
  1280. /**
  1281. * 获取报警信息文本
  1282. * @param {string} statusName - 状态名称
  1283. * @returns {string} 报警信息
  1284. */
  1285. getAlarmInfoText(statusName) {
  1286. if (statusName === '离线') return '通讯中断设备离线';
  1287. if (statusName === '降级') return '降级定周期控制';
  1288. if (statusName === '故障') return '东向左转信号灯红绿同亮';
  1289. return '设备异常';
  1290. },
  1291. /**
  1292. * 格式化事件时间
  1293. * @param {Date|number|string} input - 时间输入
  1294. * @returns {string} 格式化后的时间
  1295. */
  1296. formatEventTime(input) {
  1297. let d = null;
  1298. if (input instanceof Date) d = input;
  1299. else if (typeof input === 'number') d = new Date(input);
  1300. else if (typeof input === 'string') {
  1301. const t = Date.parse(input);
  1302. if (!Number.isNaN(t)) d = new Date(t);
  1303. }
  1304. if (!d || Number.isNaN(d.getTime())) d = new Date();
  1305. const y = d.getFullYear();
  1306. const m = d.getMonth() + 1;
  1307. const day = d.getDate();
  1308. const hh = String(d.getHours()).padStart(2, '0');
  1309. const mm = String(d.getMinutes()).padStart(2, '0');
  1310. return `${y}.${m}.${day} ${hh}:${mm}`;
  1311. },
  1312. /**
  1313. * 切换"所有图例可见项"的开关。常隐项(hideInLegend,如 降级)始终保留显示。
  1314. * 视口裁剪:只更新 activeLegends,实际 add/remove 由 computeVisibleMarkers 统一处理。
  1315. */
  1316. toggleAll() {
  1317. if (!this.isMapReady()) return;
  1318. const visibleNames = this.legendStatusConfig.map(i => i.name);
  1319. const alwaysOnNames = this.statusConfig
  1320. .filter(i => i.hideInLegend)
  1321. .map(i => i.name);
  1322. const targetState = !this.isAllSelected;
  1323. if (targetState) {
  1324. this.activeLegends = Array.from(new Set([...alwaysOnNames, ...visibleNames]));
  1325. } else {
  1326. this.activeLegends = [...alwaysOnNames];
  1327. if (this.infoWindow) this.infoWindow.close();
  1328. }
  1329. this.computeVisibleMarkers();
  1330. },
  1331. /**
  1332. * 切换指定路线的可见性。视口裁剪:仅更新 activeLegends,由调度器决定 add/remove。
  1333. * @param {string} name - 路线名称
  1334. */
  1335. toggleRouteVisible(name) {
  1336. if (!this.isMapReady()) return;
  1337. const index = this.activeLegends.indexOf(name);
  1338. if (index > -1) {
  1339. this.activeLegends.splice(index, 1);
  1340. if (this.infoWindow) this.infoWindow.close();
  1341. } else {
  1342. this.activeLegends.push(name);
  1343. }
  1344. this.computeVisibleMarkers();
  1345. },
  1346. /**
  1347. * 根据位置聚焦地图
  1348. * @param {string|Array<number>} targetPos - 目标位置
  1349. */
  1350. focusByLocation(targetPos) {
  1351. if (!this.isMapReady() || !targetPos) return;
  1352. let pos = targetPos;
  1353. if (typeof targetPos === 'string') {
  1354. pos = targetPos.split(',').map(Number);
  1355. }
  1356. if (!Array.isArray(pos) || pos.length < 2) return;
  1357. const [targetLng, targetLat] = pos;
  1358. let bestMarker = null;
  1359. let minDistanceSq = Infinity;
  1360. Object.values(this.routeGroups).forEach(group => {
  1361. if (!Array.isArray(group)) return;
  1362. group.forEach(item => {
  1363. if (!(item instanceof this.AMap.Marker)) return;
  1364. const markerExt = item.getExtData();
  1365. const markerPos = markerExt.position;
  1366. if (!markerPos) return;
  1367. const dx = markerPos[0] - targetLng;
  1368. const dy = markerPos[1] - targetLat;
  1369. const distSq = dx * dx + dy * dy;
  1370. if (distSq < 0.000001) {
  1371. const isAbnormal = ["离线", "降级", "故障"].includes(markerExt.name);
  1372. const currentIsAbnormal = bestMarker ? ["离线", "降级", "故障"].includes(bestMarker.getExtData().name) : false;
  1373. if (distSq < minDistanceSq || (isAbnormal && !currentIsAbnormal)) {
  1374. minDistanceSq = distSq;
  1375. bestMarker = item;
  1376. }
  1377. }
  1378. });
  1379. });
  1380. if (bestMarker) {
  1381. const finalPos = bestMarker.getPosition();
  1382. this.map.setZoomAndCenter(17, finalPos, false, 500);
  1383. setTimeout(() => {
  1384. if (!this.isComponentDestroyed) this.openLightInfo(bestMarker.getExtData(), finalPos);
  1385. }, 600);
  1386. } else {
  1387. this.map.setZoomAndCenter(17, [targetLng, targetLat], false, 500);
  1388. }
  1389. },
  1390. /**
  1391. * 通过路口编号定位到对应的标记
  1392. * @param {string} id - 路口编号
  1393. * @returns {Array<number>|null} 位置坐标
  1394. */
  1395. focusById(id) {
  1396. if (!this.isMapReady() || !id) return null;
  1397. const marker = this.markerById[id];
  1398. if (marker) {
  1399. const finalPos = marker.getPosition();
  1400. this.map.setZoomAndCenter(17, finalPos, false, 500);
  1401. return finalPos;
  1402. }
  1403. return null;
  1404. },
  1405. /**
  1406. * 搜索框选中回调:定位 + 立即触发视口重算(避免 100ms debounce 延迟),
  1407. * 让目标 marker 在 setZoomAndCenter 动画期间就完成挂载。
  1408. * Home 页另在飞行结束后弹出该路口的 InfoWindow,与 marker click 行为一致。
  1409. */
  1410. onSearchSelect(item) {
  1411. if (!item) return;
  1412. const id = item['路口编号'];
  1413. const finalPos = this.focusById(id);
  1414. this.computeVisibleMarkers();
  1415. if (!finalPos) return;
  1416. if (!(this.$route && this.$route.path === '/home')) return;
  1417. const marker = this.markerById[id];
  1418. if (!marker) return;
  1419. setTimeout(() => {
  1420. if (this.isComponentDestroyed) return;
  1421. this._infoWindowProtectedMarker = marker;
  1422. this.openLightInfo(marker.getExtData(), finalPos);
  1423. }, 600);
  1424. },
  1425. /**
  1426. * 切换图例的可见性
  1427. */
  1428. toggleLegend() {
  1429. this.legendVisible = !this.legendVisible;
  1430. },
  1431. /**
  1432. * 按4:4:4比例提取故障、离线、降级路口信息并存储到localStorage
  1433. */
  1434. storeStatusCoordsToLocalStorage() {
  1435. const alarmTypes = [
  1436. { status: "故障", titles: ["通讯中断", "灯组故障", "相位冲突", "绿冲突"], level: "high", type: "error" },
  1437. { status: "离线", titles: ["信号机离线", "信号机离线", "通讯中断", "检测器异常"], level: "mid", type: "warning" },
  1438. { status: "降级", titles: ["降级黄闪", "降级黄闪", "方案切换异常", "检测器异常"], level: "mid", type: "warning" },
  1439. ];
  1440. const alarmList = [];
  1441. let id = 1;
  1442. alarmTypes.forEach(({ status, titles, level, type }) => {
  1443. (this.statusIntersections[status] || []).slice(0, 4).forEach((item, i) => {
  1444. const lng = item["位置-经度"];
  1445. const lat = item["位置-纬度"];
  1446. const name = item["路口名称"] || "";
  1447. if (!lng || !lat) return;
  1448. alarmList.push({
  1449. id: `A${String(id).padStart(3, "0")}`,
  1450. title: titles[i] || titles[0],
  1451. loc: name,
  1452. level,
  1453. type,
  1454. description: `${name}-${titles[i] || titles[0]}`,
  1455. position: [lng, lat],
  1456. });
  1457. localStorage.setItem(`pos${id}`, `${lng},${lat}`);
  1458. id++;
  1459. });
  1460. });
  1461. localStorage.setItem("alarmListFromMap", JSON.stringify(alarmList));
  1462. console.log('状态坐标及告警数据已存储到localStorage');
  1463. },
  1464. /**
  1465. * 将经纬度转换为像素坐标
  1466. * @param {number} lng - 经度
  1467. * @param {number} lat - 纬度
  1468. * @returns {Object|null} 像素坐标
  1469. */
  1470. lngLatToPixel(lng, lat) {
  1471. if (!this.map) return null;
  1472. return this.map.lngLatToContainer([lng, lat]);
  1473. },
  1474. /**
  1475. * 对外暴露:为指定子区路口列表绘制凸包多边形蒙层,点击不同子区时自动替换上一个
  1476. * @param {Array<{lng: number, lat: number}>} leaves - 子区内所有叶子路口节点
  1477. */
  1478. drawSubAreaCircle(leaves, label) {
  1479. if (!this.isMapReady() || !leaves || leaves.length === 0) return;
  1480. this._subAreaParams = { leaves, label };
  1481. this.clearSubAreaOverlays();
  1482. const pts = leaves.map(n => [Number(n.lng), Number(n.lat)]);
  1483. if (pts.length < 3) return;
  1484. const hull = this._convexHull(pts);
  1485. if (hull.length < 3) return;
  1486. // 以凸包重心为基准,向外扩展 10% 留出视觉间距
  1487. const cx = hull.reduce((s, p) => s + p[0], 0) / hull.length;
  1488. const cy = hull.reduce((s, p) => s + p[1], 0) / hull.length;
  1489. const paddedHull = hull.map(p => [
  1490. cx + (p[0] - cx) * 1.1,
  1491. cy + (p[1] - cy) * 1.1,
  1492. ]);
  1493. const polygon = new this.AMap.Polygon({
  1494. path: paddedHull,
  1495. fillColor: '#4A9EFF',
  1496. fillOpacity: 0.15,
  1497. strokeColor: '#4A9EFF',
  1498. strokeOpacity: 0.6,
  1499. strokeWeight: 1,
  1500. strokeStyle: 'dashed',
  1501. strokeDasharray: [4, 4],
  1502. zIndex: 10,
  1503. bubble: true,
  1504. });
  1505. this.subAreaOverlays.push(polygon);
  1506. this.map.add(polygon);
  1507. // 在凸包重心位置显示子区名称(水印风格,字号随区域大小缩放)
  1508. if (label) {
  1509. // 用地图坐标转像素,精确计算区域在屏幕上的实际大小
  1510. const lngs = paddedHull.map(p => p[0]);
  1511. const lats = paddedHull.map(p => p[1]);
  1512. const topLeft = this.map.lngLatToContainer([Math.min(...lngs), Math.max(...lats)]);
  1513. const bottomRight = this.map.lngLatToContainer([Math.max(...lngs), Math.min(...lats)]);
  1514. const pixelW = Math.abs(bottomRight.x - topLeft.x);
  1515. const pixelH = Math.abs(bottomRight.y - topLeft.y);
  1516. // 字号同时受宽度和高度约束,取较小值确保不超出区域
  1517. const charCount = label.length || 1;
  1518. const sizeByW = Math.round(pixelW * 0.8 / (charCount + 1));
  1519. const sizeByH = Math.round(pixelH * 0.6);
  1520. const fontSize = Math.min(Math.max(10, Math.min(sizeByW, sizeByH)), 48);
  1521. // 缩放过小时隐藏文字
  1522. if (fontSize < 10) {
  1523. // 不绘制文字
  1524. } else {
  1525. const text = new this.AMap.Text({
  1526. text: label,
  1527. position: [cx, cy],
  1528. anchor: 'center',
  1529. zIndex: 11,
  1530. style: {
  1531. 'background': 'transparent',
  1532. 'border': 'none',
  1533. 'color': 'rgba(255, 255, 255, 0.25)',
  1534. 'font-size': `${fontSize}px`,
  1535. 'font-weight': 'bold',
  1536. 'padding': '0',
  1537. 'letter-spacing': fontSize >= 16 ? '2px' : '0px',
  1538. 'white-space': 'nowrap',
  1539. 'pointer-events': 'none',
  1540. },
  1541. });
  1542. this.subAreaOverlays.push(text);
  1543. this.map.add(text);
  1544. }
  1545. }
  1546. },
  1547. /**
  1548. * Graham Scan 凸包算法
  1549. * @param {Array<[number, number]>} points - 经纬度点数组
  1550. * @returns {Array<[number, number]>} 凸包顶点(逆时针)
  1551. */
  1552. _convexHull(points) {
  1553. if (points.length < 3) return [...points];
  1554. const p0 = points.reduce((best, p) =>
  1555. p[1] < best[1] || (p[1] === best[1] && p[0] < best[0]) ? p : best
  1556. );
  1557. const cross = (o, a, b) =>
  1558. (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  1559. const dist2 = (a, b) =>
  1560. (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;
  1561. const sorted = points
  1562. .filter(p => p !== p0)
  1563. .sort((a, b) => {
  1564. const c = cross(p0, a, b);
  1565. if (c !== 0) return c > 0 ? -1 : 1;
  1566. return dist2(p0, a) - dist2(p0, b);
  1567. });
  1568. const hull = [p0];
  1569. for (const p of sorted) {
  1570. while (hull.length >= 2 && cross(hull[hull.length - 2], hull[hull.length - 1], p) <= 0) {
  1571. hull.pop();
  1572. }
  1573. hull.push(p);
  1574. }
  1575. return hull;
  1576. },
  1577. /**
  1578. * 清除子区圆形蒙层
  1579. */
  1580. rebuildSubAreaText() {
  1581. if (!this._subAreaParams) return;
  1582. const { leaves, label } = this._subAreaParams;
  1583. // 保留参数,重绘整个子区(包含字号重新计算)
  1584. this.drawSubAreaCircle(leaves, label);
  1585. },
  1586. clearSubAreaOverlays() {
  1587. if (this.map && this.subAreaOverlays.length > 0) {
  1588. try { this.map.remove(this.subAreaOverlays); } catch (e) { void e; }
  1589. this.subAreaOverlays = [];
  1590. }
  1591. },
  1592. }
  1593. };
  1594. </script>
  1595. <style scoped>
  1596. .map-wrapper {
  1597. width: 100%;
  1598. height: 100vh;
  1599. position: relative;
  1600. background: #010813;
  1601. }
  1602. .map-container {
  1603. width: 100%;
  1604. height: 100%;
  1605. }
  1606. ::v-deep .amap-logo,
  1607. ::v-deep .amap-copyright,
  1608. ::v-deep .amap-copyright-logo {
  1609. display: none !important;
  1610. }
  1611. ::v-deep .pure-light-node.breathe {
  1612. animation: light-breathe 2s infinite ease-in-out;
  1613. }
  1614. ::v-deep .pure-light-node span {
  1615. display: flex;
  1616. transform: scale(0.75);
  1617. align-items: center;
  1618. }
  1619. ::v-deep .pure-light-node:hover {
  1620. transform: scale(1.4);
  1621. filter: brightness(1.2);
  1622. }
  1623. @keyframes light-breathe {
  1624. 0% {
  1625. transform: scale(0.9);
  1626. opacity: 0.8;
  1627. }
  1628. 50% {
  1629. transform: scale(1.1);
  1630. opacity: 1;
  1631. }
  1632. 100% {
  1633. transform: scale(0.9);
  1634. opacity: 0.8;
  1635. }
  1636. }
  1637. ::v-deep .close-btn {
  1638. position: absolute;
  1639. top: 10px;
  1640. right: 12px;
  1641. color: #8da6c7;
  1642. cursor: pointer;
  1643. font-size: 16px;
  1644. transition: color 0.3s;
  1645. line-height: 1;
  1646. z-index: 10;
  1647. }
  1648. ::v-deep .close-btn:hover {
  1649. color: #ffffff;
  1650. }
  1651. ::v-deep .custom-info-card {
  1652. position: relative;
  1653. background: rgba(10, 15, 24, 0.95);
  1654. border-radius: 10px;
  1655. padding: 12px 16px;
  1656. min-width: 200px;
  1657. border: 1px solid rgba(255, 255, 255, 0.1);
  1658. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  1659. color: #fff;
  1660. }
  1661. ::v-deep .card-header {
  1662. display: flex;
  1663. align-items: center;
  1664. margin-bottom: 10px;
  1665. }
  1666. ::v-deep .status-dot {
  1667. width: 30px;
  1668. height: 30px;
  1669. border-radius: 50%;
  1670. display: flex;
  1671. justify-content: center;
  1672. align-items: center;
  1673. margin-right: 8px;
  1674. font-size: 14px;
  1675. padding: 0;
  1676. box-sizing: border-box;
  1677. }
  1678. ::v-deep .status-dot.breathe {
  1679. animation: light-breathe 2s infinite ease-in-out;
  1680. }
  1681. ::v-deep .status-dot span {
  1682. transform: scale(0.75);
  1683. }
  1684. ::v-deep .status-dot img {
  1685. width: 100%;
  1686. height: 100%;
  1687. object-fit: contain;
  1688. display: block;
  1689. }
  1690. ::v-deep .status-text {
  1691. font-size: 15px;
  1692. font-weight: bold;
  1693. }
  1694. ::v-deep .info-line {
  1695. display: flex;
  1696. margin-bottom: 6px;
  1697. font-size: 13px;
  1698. align-items: center;
  1699. }
  1700. ::v-deep .label {
  1701. color: #8da6c7;
  1702. white-space: nowrap;
  1703. }
  1704. ::v-deep .value {
  1705. color: #ffffff;
  1706. }
  1707. ::v-deep .digital {
  1708. font-family: 'Consolas', monospace;
  1709. }
  1710. .map-legend {
  1711. position: absolute;
  1712. bottom: 30px;
  1713. right: 40px;
  1714. background: rgba(5, 22, 45, 0.9);
  1715. border: 1px solid #1e4d8e;
  1716. padding: 15px;
  1717. border-radius: 6px;
  1718. z-index: 100;
  1719. transition: all 0.3s ease-in-out;
  1720. opacity: 1;
  1721. max-width: 200px;
  1722. overflow: hidden;
  1723. }
  1724. .map-legend.legend-hidden {
  1725. opacity: 0;
  1726. transform: translateX(calc(100% + 20px));
  1727. pointer-events: none;
  1728. }
  1729. .legend-header {
  1730. display: flex;
  1731. justify-content: space-between;
  1732. align-items: center;
  1733. margin-bottom: 12px;
  1734. border-bottom: 1px solid #1e4d8e;
  1735. padding-bottom: 8px;
  1736. }
  1737. .legend-close-btn {
  1738. color: #8da6c7;
  1739. cursor: pointer;
  1740. font-size: 16px;
  1741. transition: color 0.3s;
  1742. line-height: 1;
  1743. }
  1744. .legend-close-btn:hover {
  1745. color: #ffffff;
  1746. }
  1747. .legend-show-btn {
  1748. position: absolute;
  1749. bottom: 30px;
  1750. right: 20px;
  1751. background: rgba(30, 86, 168, 0.92);
  1752. border: 1px solid #5892ff;
  1753. width: 40px;
  1754. height: 40px;
  1755. border-radius: 6px 0 0 6px;
  1756. display: flex;
  1757. justify-content: center;
  1758. align-items: center;
  1759. cursor: pointer;
  1760. z-index: 99;
  1761. box-shadow: 0 0 12px rgba(88, 146, 255, 0.7);
  1762. transition: all 0.3s ease-in-out;
  1763. }
  1764. .legend-show-btn:hover {
  1765. background: rgba(58, 117, 196, 0.95);
  1766. border-color: #8db4ff;
  1767. box-shadow: 0 0 16px rgba(88, 146, 255, 0.9);
  1768. }
  1769. .legend-show-icon {
  1770. color: #ffffff;
  1771. font-size: 18px;
  1772. transition: color 0.3s;
  1773. }
  1774. .legend-show-btn:hover .legend-show-icon {
  1775. color: #ffffff;
  1776. }
  1777. .legend-title {
  1778. color: #fff;
  1779. font-size: 14px;
  1780. }
  1781. .legend-item {
  1782. display: flex;
  1783. align-items: center;
  1784. margin-bottom: 10px;
  1785. cursor: pointer;
  1786. transition: 0.3s;
  1787. }
  1788. .legend-item.is-inactive {
  1789. opacity: 0.7;
  1790. filter: grayscale(1);
  1791. }
  1792. .legend-dot {
  1793. margin-right: 10px;
  1794. display: flex;
  1795. justify-content: center;
  1796. align-items: center;
  1797. }
  1798. .legend-dot:not(.is-status-wrapper) {
  1799. width: 20px;
  1800. height: 20px;
  1801. border-radius: 50%;
  1802. }
  1803. .legend-dot span {
  1804. display: inline-block;
  1805. width: 20px;
  1806. height: 20px;
  1807. font-size: 12px;
  1808. color: #FFF;
  1809. text-align: center;
  1810. transform: scale(0.75);
  1811. line-height: 20px;
  1812. }
  1813. .legend-dot.special-route {
  1814. position: relative;
  1815. overflow: visible !important;
  1816. z-index: 1;
  1817. border: none !important;
  1818. border-radius: 50%;
  1819. }
  1820. .legend-dot.special-route span {
  1821. position: relative;
  1822. z-index: 3;
  1823. font-weight: bold;
  1824. }
  1825. .legend-dot.special-route::after {
  1826. content: "";
  1827. position: absolute;
  1828. top: 50%;
  1829. left: 50%;
  1830. width: 150%;
  1831. height: 3px;
  1832. background-color: inherit;
  1833. opacity: 0.8;
  1834. transform: translate(-50%, -50%) rotate(-45deg);
  1835. pointer-events: none;
  1836. z-index: 0;
  1837. }
  1838. .legend-dot.special-route::before {
  1839. content: "";
  1840. position: absolute;
  1841. top: 0;
  1842. left: 0;
  1843. width: 100%;
  1844. height: 100%;
  1845. border-radius: 50%;
  1846. z-index: 2;
  1847. background-color: inherit;
  1848. opacity: 1;
  1849. }
  1850. .legend-label {
  1851. flex: 1;
  1852. color: #d0d9e2;
  1853. font-size: 13px;
  1854. }
  1855. .legend-status {
  1856. font-size: 11px;
  1857. color: #5b7da8;
  1858. }
  1859. .all-select {
  1860. border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  1861. padding-bottom: 12px;
  1862. margin-bottom: 12px !important;
  1863. }
  1864. .all-select .legend-dot {
  1865. border-radius: 2px;
  1866. transition: all 0.3s;
  1867. width: 10px;
  1868. height: 10px;
  1869. }
  1870. .all-select .legend-dot.all-select-dot {
  1871. width: 14px;
  1872. height: 14px;
  1873. border-radius: 3px;
  1874. border: 1px solid #fff;
  1875. background: transparent;
  1876. display: flex;
  1877. justify-content: center;
  1878. align-items: center;
  1879. box-shadow: none;
  1880. }
  1881. .all-select .legend-dot.all-select-dot.is-checked {
  1882. background: #1890ff;
  1883. border-color: #1890ff;
  1884. }
  1885. .all-select .check-icon {
  1886. display: block;
  1887. width: 6px;
  1888. height: 9px;
  1889. border: solid #fff;
  1890. border-width: 0 2px 2px 0;
  1891. transform: translateY(-1px) rotate(45deg);
  1892. transform-origin: center;
  1893. }
  1894. .legend-dot.is-status-wrapper {
  1895. width: 28px;
  1896. height: 28px;
  1897. background-color: transparent !important;
  1898. box-shadow: none !important;
  1899. border: none !important;
  1900. margin-right: 0;
  1901. transform: translateX(-15%);
  1902. }
  1903. .status-icon {
  1904. width: 100%;
  1905. height: 100%;
  1906. object-fit: contain;
  1907. display: block;
  1908. }
  1909. ::v-deep .pure-light-node {
  1910. width: 16px;
  1911. height: 16px;
  1912. border-radius: 50%;
  1913. border: 2px solid rgba(255, 255, 255, 0.8);
  1914. cursor: pointer;
  1915. transition: all 0.3s;
  1916. display: flex;
  1917. justify-content: center;
  1918. align-items: center;
  1919. color: #fff;
  1920. pointer-events: auto;
  1921. }
  1922. ::v-deep .pure-light-node.route-node {
  1923. position: relative;
  1924. overflow: visible;
  1925. }
  1926. ::v-deep .pure-light-node.route-node::after {
  1927. content: "";
  1928. position: absolute;
  1929. top: 50%;
  1930. left: 50%;
  1931. width: 150%;
  1932. height: 3px;
  1933. background-color: inherit;
  1934. opacity: 0.8;
  1935. transform: translate(-50%, -50%) rotate(-45deg);
  1936. pointer-events: none;
  1937. }
  1938. ::v-deep .pure-light-node.route-node span {
  1939. position: relative;
  1940. z-index: 1;
  1941. }
  1942. ::v-deep .pure-light-node:not(.abnormal-node) {
  1943. border: 1px solid rgba(255, 255, 255, 0.4);
  1944. }
  1945. ::v-deep .duty-progress-node {
  1946. animation: duty-pulse 1.6s infinite ease-in-out;
  1947. }
  1948. @keyframes duty-pulse {
  1949. 0% { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
  1950. 50% { box-shadow: 0 0 0 9px rgba(188, 48, 29, 0.08); }
  1951. 100% { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
  1952. }
  1953. </style>