map.vue
62.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
<!--
* @Date: 2023-05-19 14:54:27
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-10-11 10:14:44
* @FilePath: /map-demo/src/views/checkin/map.vue
* @Description: 公众地图主体页面
-->
<template>
<div ref="root" :style="{ height: mapHeight, position: 'relative', overflow: 'hidden' }">
<!-- 地图加载状态提示 -->
<div v-if="mapLoadingState.isLoading" class="map-loading-overlay">
<div class="loading-content">
<van-loading size="24px" color="#DD7850">地图加载中...</van-loading>
<p class="loading-text">正在初始化地图,请稍候</p>
<!-- 队列信息显示 -->
<div v-if="mapLoadingState.queuePosition > 0" class="queue-info">
<p class="queue-text">当前排队位置:第 {{ mapLoadingState.queuePosition }} 位</p>
<p v-if="mapLoadingState.estimatedWaitTime > 0" class="wait-time">
预计等待时间:{{ Math.ceil(mapLoadingState.estimatedWaitTime / 1000) }} 秒
</p>
</div>
<!-- 重试进度显示 -->
<div v-if="mapLoadingState.retryCount > 0" class="retry-info">
<p class="retry-text">重试中... ({{ mapLoadingState.retryCount }}/{{ getRetryStrategy(mapLoadingState.lastError || new Error()).maxRetries }})</p>
</div>
</div>
</div>
<!-- 地图加载错误提示 -->
<div v-if="mapLoadingState.isError" class="map-error-overlay">
<div class="error-content">
<van-icon name="warning-o" size="48px" color="#ff4444" />
<p class="error-title">请求太火爆, 请稍后再试!</p>
<p class="error-message">{{ mapLoadingState.errorMessage }}</p>
<van-button
type="primary"
color="#DD7850"
@click="retryLoadMap"
:loading="mapLoadingState.isLoading"
>
重新加载
</van-button>
</div>
</div>
<div id="container"></div>
<!-- 添加导航面板容器 -->
<div id="walking-panel" style="position: absolute; bottom: 1rem; left: 1rem; padding: 1rem;"></div>
<div style="position: absolute; top: 2rem; right: 1rem; display: flex; flex-direction: column;">
<!-- <van-icon size="2rem" name="search" color="#DD7850" style="margin-bottom: 1rem;" /> -->
<van-image
width="2rem"
height="2rem"
fit="contain"
src="https://cdn.ipadbiz.cn/bieyuan/map/icon/NAV@3x.png"
/>
</div>
<div v-if="data_logo" style="position: absolute; top: 2rem; left: calc(50% - 1.5rem); opacity: 0.5;">
<van-image
width="3rem"
height="3rem"
fit="contain"
:src="data_logo"
/>
</div>
<!-- <div @click="scanQrcode" style="position: absolute; bottom: 1rem; left: calc(50% - 2.5rem);">
<van-image
width="5rem"
height="5rem"
fit="contain"
src="https://cdn.ipadbiz.cn/bieyuan/map/icon/scan@3x.png"
/>
</div> -->
<van-config-provider :theme-vars="themeVars">
<van-floating-panel v-model:height="info_height" :anchors="anchors" @height-change="onHeightChange">
<!-- <template #header>
<div class="custom-header">
<h3>自定义标题</h3>
<button @click="show = false">关闭</button>
</div>
</template> -->
<page-info ref="pageInfo" :info="itemInfo" :height="info_height" @close-float="onCloseFloat" @route="onRoute" @walk-route="onWalkRoute"></page-info>
<!-- <div v-if="showClose" @click="closeFloatPanel" class="close-float-panel">
<van-icon name="arrow-left" color="#FFF" size="1.5rem" />
</div> -->
</van-floating-panel>
</van-config-provider>
<div v-if="!show_walk_route" @click="removeSafeRoute({ name: '参观路径' })" class="walk-nav-text">
关闭步行导航
</div>
<!-- 新增关闭导航按钮 -->
<div v-if="walking && !show_walk_route" class="walk-nav-text" @click="closeWalkingRoute">
关闭步行导航
</div>
<van-dialog v-model:show="dialog_show" title="温馨提示" confirm-button-text="知道了">
<div style="padding: 1rem; text-align: center;">{{ dialog_text }}</div>
</van-dialog>
<!-- 背景音乐控制 -->
<!-- <audioBackground1></audioBackground1> -->
<!-- <div class="operate-bar-wrapper">
<div class="box-wrapper">
<div v-if="open_current_location" class="item" @click="handleLocation(true)">
<van-icon name="https://cdn.ipadbiz.cn/xys/map/%E5%AE%9A%E4%BD%8Dloc@2x.png" size="1.5rem"
style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);;" />
</div>
<div v-else class="item" @click="handleLocation(false)">
<van-icon name="https://cdn.ipadbiz.cn/xys/map/%E5%AE%9A%E4%BD%8Dloc@2x.png" size="1.5rem"
style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);" />
</div>
</div>
</div> -->
<van-toast v-model:show="show_toast" style="padding: 0">
<template #message>
<p style="padding: 0.5rem 1rem;">{{ toast_text }}</p>
</template>
</van-toast>
<!-- 底部导航组件 -->
<BottomNav />
</div>
</template>
<script>
import "@vant/touch-emulator";
// import { mapState } from 'vuex'
import coord from '@/common/map_data'
import my_router from '@/common/my_router'
import _ from 'lodash';
import $ from 'jquery';
import { useRect } from '@vant/use';
import { mapAPI } from '@/api/map.js'
import wx from 'weixin-js-sdk'
import pageInfo from '@/views/checkin/info.vue'
import audioBackground1 from '@/components/audioBackground1.vue'
import BottomNav from '@/components/BottomNav.vue'
import { mapState, mapActions } from 'pinia'
import { mainStore } from '@/store'
import { parseQueryString, getAdaptiveFontSize, getAdaptivePadding } from '@/utils/tools'
import AMapLoader from '@amap/amap-jsapi-loader'
import { mapAudioAPI } from '@/api/map.js'
// 地图缓存管理器
class MapCacheManager {
constructor() {
this.amapCache = null; // AMap实例缓存
this.mapDataCache = new Map(); // 地图数据缓存
this.loadingPromises = new Map(); // 正在加载的Promise缓存
this.cacheExpiry = 5 * 60 * 1000; // 缓存过期时间:5分钟
}
/**
* 获取缓存的AMap实例
*/
async getAMap() {
if (this.amapCache) {
return this.amapCache;
}
// 如果正在加载,返回现有的Promise
if (this.loadingPromises.has('amap')) {
return this.loadingPromises.get('amap');
}
const loadPromise = AMapLoader.load({
key: '17b8fc386104b89db88b60b049a6dbce',
version: '2.0',
plugins: ['AMap.ElasticMarker','AMap.ImageLayer','AMap.ToolBar','AMap.IndoorMap','AMap.Walking','AMap.Geolocation']
}).then(AMap => {
this.amapCache = AMap;
this.loadingPromises.delete('amap');
return AMap;
}).catch(error => {
this.loadingPromises.delete('amap');
throw error;
});
this.loadingPromises.set('amap', loadPromise);
return loadPromise;
}
/**
* 获取缓存的地图数据
*/
async getMapData(code) {
const cacheKey = `mapData_${code}`;
const cached = this.mapDataCache.get(cacheKey);
// 检查缓存是否有效
if (cached && (Date.now() - cached.timestamp < this.cacheExpiry)) {
return cached.data;
}
// 如果正在加载相同的数据,返回现有的Promise
if (this.loadingPromises.has(cacheKey)) {
return this.loadingPromises.get(cacheKey);
}
const loadPromise = mapAPI({ i: code }).then(response => {
const data = response.data;
this.mapDataCache.set(cacheKey, {
data,
timestamp: Date.now()
});
this.loadingPromises.delete(cacheKey);
return data;
}).catch(error => {
this.loadingPromises.delete(cacheKey);
throw error;
});
this.loadingPromises.set(cacheKey, loadPromise);
return loadPromise;
}
/**
* 预加载地图数据
*/
async preloadMapData(codes) {
const promises = codes.map(code => {
try {
return this.getMapData(code);
} catch (error) {
console.warn(`预加载地图数据失败 (code: ${code}):`, error);
return null;
}
});
return Promise.allSettled(promises);
}
/**
* 创建离线瓦片图层作为备用方案
*/
createOfflineTileLayer() {
// 使用本地瓦片图片作为备用
const offlineTileLayer = new AMap.TileLayer({
getTileUrl: function(x, y, z) {
// 检查本地是否有缓存的瓦片
const tileUrl = `/images/tiles/${z}/${x}/${y}.png`;
return tileUrl;
},
zIndex: 1,
opacity: 0.8
});
return offlineTileLayer;
}
/**
* 清理过期缓存
*/
cleanExpiredCache() {
const now = Date.now();
for (const [key, value] of this.mapDataCache.entries()) {
if (now - value.timestamp >= this.cacheExpiry) {
this.mapDataCache.delete(key);
}
}
}
}
// 全局地图缓存管理器实例
const mapCacheManager = new MapCacheManager();
const GPS = {
PI: 3.14159265358979324,
x_pi: 3.14159265358979324 * 3000.0 / 180.0,
delta: function (lat, lon) {
var a = 6378245.0; // a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
var ee = 0.00669342162296594323; // ee: 椭球的偏心率。
var dLat = this.transformLat(lon - 105.0, lat - 35.0);
var dLon = this.transformLon(lon - 105.0, lat - 35.0);
var radLat = lat / 180.0 * this.PI;
var magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
var sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
return {
'lat': dLat,
'lon': dLon
};
},
//WGS-84 to GCJ-02
gcj_encrypt: function (wgsLat, wgsLon) {
if (this.outOfChina(wgsLat, wgsLon))
return {
'lat': wgsLat,
'lon': wgsLon
};
var d = this.delta(wgsLat, wgsLon);
return {
'lat': wgsLat + d.lat,
'lon': wgsLon + d.lon
};
},
outOfChina: function (lat, lon) {
if (lon < 72.004 || lon > 137.8347)
return true;
if (lat < 0.8293 || lat > 55.8271)
return true;
return false;
},
transformLat: function (x, y) {
var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
return ret;
},
transformLon: function (x, y) {
var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
return ret;
}
};
// 关键安全配置
window._AMapSecurityConfig = {
securityJsCode: 'ac1a3a5858d74b7d6c50b6858100aa12', // 替换为你的密钥
}
export default {
name: 'CheckinMap',
components: { pageInfo, audioBackground1, BottomNav },
computed: {
...mapState(mainStore, ['audio_entity', 'audio_src', 'audio_status']),
/**
* 检测是否在小程序web-view环境中
* @returns {boolean} 是否在小程序环境
*/
isMiniProgramWebView() {
return navigator.userAgent.includes('miniProgram');
},
/**
* 动态计算地图高度
* @returns {string} 地图容器高度
*/
mapHeight() {
return this.isMiniProgramWebView ? 'calc(100vh - 80px)' : '100vh';
},
/**
* 获取地图缩放级别
* @returns {number} 地图缩放级别
*/
zoom() {
return this.data_zoom;
},
/**
* 动态计算适配的标记样式 - 选中状态(垂直)
* @returns {Object} 适配后的样式对象
*/
adaptiveMarkerStyle2() {
return {
"padding": getAdaptivePadding(".5rem .2rem .5rem .2rem"),
"border-color": "#DD7850",
"border-radius": ".25rem",
"background-color": "#FFF",
"font-size": getAdaptiveFontSize(0.8, true), // 仅iPad设备适配
"color": "#DD7850",
"writing-mode": "vertical-rl",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
};
},
/**
* 动态计算适配的标记样式 - 未选中状态(垂直)
* @returns {Object} 适配后的样式对象
*/
adaptiveMarkerStyle1() {
return {
"padding": getAdaptivePadding(".5rem .2rem .5rem .2rem"),
"border-color": "#fcfbfa",
"border-radius": ".25rem",
"background-color": "#DD7850",
"font-size": getAdaptiveFontSize(0.8, true), // 仅iPad设备适配
"color": "white",
"writing-mode": "vertical-rl",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
};
},
/**
* 动态计算适配的标记样式 - 选中状态(水平)
* @returns {Object} 适配后的样式对象
*/
adaptiveMarkerStyle2Horizontal() {
return {
"padding": getAdaptivePadding(".2rem .5rem .2rem .5rem"),
"border-color": "#DD7850",
"border-radius": ".25rem",
"background-color": "#FFF",
"font-size": getAdaptiveFontSize(0.8, true), // 仅iPad设备适配
"color": "#DD7850",
"writing-mode": "horizontal",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
};
},
/**
* 动态计算适配的标记样式 - 未选中状态(水平)
* @returns {Object} 适配后的样式对象
*/
adaptiveMarkerStyle1Horizontal() {
return {
"padding": getAdaptivePadding(".2rem .5rem .2rem .5rem"),
"border-color": "#fcfbfa",
"border-radius": ".25rem",
"background-color": "#DD7850",
"font-size": getAdaptiveFontSize(0.8, true), // 仅iPad设备适配
"color": "white",
"writing-mode": "horizontal",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
};
}
},
data() {
return {
map: '',
geolocation: '',
current_lng: '',
current_lat: '',
openid: '',
dialog_show: false,
dialog_text: '',
location_marker: '',
itemInfo: {},
navBarList: [],
navList: [],
navKey: '',
markerSum: [], // marker合集
mapTiles: [],
data_center: [], // 接口获取-地图中心点
data_zoom: '', // 接口获取-地图默认缩放
data_zooms: '', // 接口获取-地图默认缩放范围
data_rotation: 0, // 接口获取-地图旋转角度
data_paths: {}, // 接口获取-地图导航路径
data_path_list: [], // 接口获取-地图导航路径
info_height: 0,
anchors: [0, (0.65 * window.innerHeight), (1 * window.innerHeight)],
themeVars: {
floatingPanelHeaderHeight: 0,
floatingPanelBorderRadius: '1.25rem'
},
showClose: false,
// 地图加载状态管理
mapLoadingState: {
isLoading: true,
isError: false,
errorMessage: '',
retryCount: 0,
maxRetries: 3,
lastError: null,
queuePosition: 0,
estimatedWaitTime: 0
},
markerStyle2: { // 选中
//设置文本样式,Object 同 css 样式表
"padding": ".5rem .2rem .5rem .2rem",
// "margin-bottom": "1rem",
"border-color": "#DD7850",
"border-radius": ".25rem",
"background-color": "#FFF",
// "width": "1rem",
// "border-width": 0,
// "box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
// "text-align": "center",
"font-size": "0.8rem",
"color": "#DD7850",
"writing-mode": "vertical-rl",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
},
markerStyle1: { // 未选中
//设置文本样式,Object 同 css 样式表
"padding": ".5rem .2rem .5rem .2rem",
// "margin-bottom": "1rem",
"border-color": "#fcfbfa",
"border-radius": ".25rem",
"background-color": "#DD7850",
// "width": "1rem",
// "border-width": 0,
// "box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
// "text-align": "center",
"font-size": "0.8rem",
"color": "white",
"writing-mode": "vertical-rl",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
},
markerStyle2_horizontal: { // 选中
//设置文本样式,Object 同 css 样式表
"padding": ".2rem .5rem .2rem .5rem",
// "margin-bottom": "1rem",
"border-color": "#DD7850",
"border-radius": ".25rem",
"background-color": "#FFF",
// "width": "1rem",
// "border-width": 0,
// "box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
// "text-align": "center",
"font-size": "0.8rem",
"color": "#DD7850",
"writing-mode": "horizontal",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
},
markerStyle1_horizontal: { // 未选中
//设置文本样式,Object 同 css 样式表
"padding": ".2rem .5rem .2rem .5rem",
// "margin-bottom": "1rem",
"border-color": "#fcfbfa",
"border-radius": ".25rem",
"background-color": "#DD7850",
// "width": "1rem",
// "border-width": 0,
// "box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
// "text-align": "center",
"font-size": "0.8rem",
"color": "white",
"writing-mode": "horizontal",
"text-orientation": "mixed",
"display": "flex",
"justify-content": "center",
"align-items": "center",
},
current_safe_route: [],
route_safe_marker: [],
show_walk_route: true,
open_current_location: true,
show_toast: false,
toast_text: '',
data_logo: '',
data_layers: [],
point_range: [
[117.044223,26.835105], [117.044227,26.842448], [117.0552,26.842452], [117.055195,26.8351]
],
walking: '',
is_get_location: false,
}
},
async mounted() {
// 设置默认标题,避免显示undefined
document.title = '地图加载中...';
// 将当前页面添加到缓存列表
const store = mainStore();
if (!store.keepPages.includes('CheckinMap')) {
store.keepPages.push('CheckinMap');
}
// 预加载常用地图数据
const commonMapCodes = ['1', '2', '3']; // 根据实际情况调整
mapCacheManager.preloadMapData(commonMapCodes);
// 开始加载地图
this.mapLoadingState.isLoading = true;
this.mapLoadingState.isError = false;
try {
await this.initializeMapWithRetry();
} catch (error) {
console.error('地图初始化失败:', error);
this.handleMapLoadError(error);
}
},
// keep-alive 组件激活时调用
activated() {
// 组件被激活时,检查地图是否已经初始化
console.log('地图组件已激活');
// 确保当前页面在缓存列表中
const store = mainStore();
if (!store.keepPages.includes('CheckinMap')) {
store.keepPages.push('CheckinMap');
}
// 如果地图还未初始化或加载失败,重新尝试加载
if (!this.map || this.mapLoadingState.isError) {
console.log('地图未初始化或加载失败,重新加载');
this.mapLoadingState.isLoading = true;
this.mapLoadingState.isError = false;
this.initializeMapWithRetry().catch(error => {
console.error('重新激活时地图加载失败:', error);
this.handleMapLoadError(error);
});
} else {
// 地图已经初始化,重新设置地图大小以适应容器
this.$nextTick(() => {
this.map.getSize();
});
}
// 重置page-info组件状态,关闭浮动面板
this.info_height = 0;
this.itemInfo = {};
// 重置浮动面板样式
this.$nextTick(() => {
$('.van-floating-panel__content').css('borderRadius', '1.25rem');
$('.van-floating-panel').css('boxShadow', 'none');
// 还原标记点样式
this.resetMarkStyle();
});
},
// keep-alive 组件停用时调用
deactivated() {
// 组件被停用时,保存当前状态
console.log('地图组件已停用,状态已保存');
},
watch: {
// // 监听 $route 对象的 query 属性
// '$route.query': {
// handler(newQuery, oldQuery) {
// if (newQuery.marker_id) {
// }
// },
// immediate: true, // 设置为 true,确保在初始化时也执行一次 handler
// deep: true // 如果 query 是嵌套对象,可以设置 deep 监听深层变化
// }
},
methods: {
...mapActions(mainStore, ['changeAudio', 'changeAudioSrc', 'changeAudioStatus']),
/**
* 计算重试延迟时间(智能指数退避算法)
* @param {number} retryCount - 当前重试次数
* @returns {number} 延迟时间(毫秒)
*/
calculateRetryDelay(retryCount) {
// 基础延迟时间:1秒,每次重试翻倍,最大不超过30秒
const baseDelay = 1000;
const maxDelay = 30000;
// 指数退避:2^retryCount * baseDelay
let delay = Math.min(baseDelay * Math.pow(2, retryCount), maxDelay);
// 添加随机抖动,避免所有用户同时重试(抖动范围:±30%)
const jitterRange = 0.3;
const jitter = (Math.random() * 2 - 1) * jitterRange * delay;
delay = Math.max(delay + jitter, 500); // 最小延迟500ms
// 根据当前时间添加额外的分散策略
const timeBasedJitter = (Date.now() % 1000) * (retryCount + 1);
delay += timeBasedJitter;
return Math.floor(delay);
},
/**
* 智能重试策略 - 根据错误类型调整重试行为
* @param {Error} error - 错误对象
* @returns {Object} 重试配置
*/
getRetryStrategy(error) {
const errorMessage = error.message || '';
// 配额限制错误 - 使用更长的延迟
if (errorMessage.includes('quota') || errorMessage.includes('limit') || errorMessage.includes('rate')) {
return {
shouldRetry: true,
maxRetries: 5,
delayMultiplier: 3, // 延迟时间乘数
priority: 'low'
};
}
// 网络错误 - 快速重试
if (errorMessage.includes('network') || errorMessage.includes('timeout') || errorMessage.includes('fetch')) {
return {
shouldRetry: true,
maxRetries: 3,
delayMultiplier: 1,
priority: 'high'
};
}
// 服务器错误 - 中等延迟
if (errorMessage.includes('500') || errorMessage.includes('502') || errorMessage.includes('503')) {
return {
shouldRetry: true,
maxRetries: 4,
delayMultiplier: 2,
priority: 'medium'
};
}
// 默认策略
return {
shouldRetry: true,
maxRetries: 3,
delayMultiplier: 1.5,
priority: 'medium'
};
},
/**
* 重试加载地图
*/
async retryLoadMap() {
const retryStrategy = this.getRetryStrategy(this.mapLoadingState.lastError || new Error());
if (this.mapLoadingState.retryCount >= retryStrategy.maxRetries) {
this.mapLoadingState.errorMessage = '已达到最大重试次数,请稍后再试';
return;
}
this.mapLoadingState.isLoading = true;
this.mapLoadingState.isError = false;
this.mapLoadingState.retryCount++;
// 计算延迟时间(应用策略乘数)
const baseDelay = this.calculateRetryDelay(this.mapLoadingState.retryCount - 1);
const delay = baseDelay * retryStrategy.delayMultiplier;
try {
// 等待延迟时间
await new Promise(resolve => setTimeout(resolve, delay));
// 重新初始化地图
await this.initializeMapWithRetry();
} catch (error) {
console.error('重试加载地图失败:', error);
this.mapLoadingState.lastError = error;
this.handleMapLoadError(error);
}
},
/**
* 处理地图加载错误
* @param {Error} error - 错误对象
*/
handleMapLoadError(error) {
this.mapLoadingState.isLoading = false;
this.mapLoadingState.isError = true;
// 根据错误类型设置不同的错误信息
if (error.message && error.message.includes('quota')) {
this.mapLoadingState.errorMessage = '地图服务繁忙,请稍后重试';
// 模拟队列位置
this.mapLoadingState.queuePosition = Math.floor(Math.random() * 50) + 1;
this.mapLoadingState.estimatedWaitTime = this.mapLoadingState.queuePosition * 2000; // 每个位置2秒
} else if (error.message && error.message.includes('network')) {
this.mapLoadingState.errorMessage = '网络连接异常,请检查网络后重试';
} else {
this.mapLoadingState.errorMessage = '地图加载失败,请重试';
}
// 尝试启用离线模式
// this.tryOfflineMode();
},
/**
* 尝试启用离线模式
*/
tryOfflineMode() {
try {
// 检查是否有本地瓦片可用
const testImage = new Image();
testImage.onload = () => {
console.log('检测到本地瓦片,可启用离线模式');
this.mapLoadingState.errorMessage += '\n\n已启用离线模式,功能可能受限';
};
testImage.onerror = () => {
console.log('未检测到本地瓦片');
};
testImage.src = '/images/tiles/17/108000/55000.png'; // 测试一个瓦片
} catch (error) {
console.warn('离线模式检测失败:', error);
}
},
/**
* 带重试机制的地图初始化
*/
async initializeMapWithRetry() {
try {
// 使用缓存管理器获取AMap实例
const AMap = await mapCacheManager.getAMap();
// 获取地图数据(使用缓存)
const code = this.$route.query.id;
const data = await mapCacheManager.getMapData(code);
// 设置地图数据
this.navBarList = data.list;
this.mapTiles = data.level;
this.navKey = data.list.length ? data.list[0]['id'] : 0;
this.navList = data.list.length ? data.list.filter(item => item.id === this.navKey)[0]['list'] : [];
this.data_center = data.map.center.map(item => Number(item));
this.data_zoom = data.map.zoom;
this.data_rotation = data.map.rotation;
this.data_zooms = data.map.zooms.map(item => Number(item));
this.data_paths = data.map.path ? data.map.path : {};
this.data_logo = data.map.map_logo ? data.map.map_logo : '';
this.point_range = data.map.map_range ? data.map.map_range : [];
if (data.map.map_layers) {
if (data.map.map_layers === 'satellite') {
this.data_layers = [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()];
} else {
this.data_layers = [];
}
}
if (data.map.path) {
for (const key in data.map.path) {
const element = data.map.path[key];
this.data_path_list.push({
name: key,
path: element,
status: true
});
}
}
// 设置页面标题
document.title = data.map.map_title;
// 微信分享配置
const shareData = {
title: data.map.map_title,
desc: '',
link: location.origin + location.pathname + location.hash,
imgUrl: '',
success: function () {}
};
wx.updateAppMessageShareData(shareData);
wx.updateTimelineShareData(shareData);
wx.onMenuShareWeibo(shareData);
// 初始化地图
this.initMap();
this.setTitleLayer();
// 初始化步行导航
this.walking = new AMap.Walking({
map: this.map,
hideMarkers: false,
isOutline: true,
autoFitView: true,
});
// 地图加载成功
this.mapLoadingState.isLoading = false;
this.mapLoadingState.isError = false;
this.mapLoadingState.retryCount = 0;
// 清理过期缓存
mapCacheManager.cleanExpiredCache();
} catch (error) {
console.error('地图初始化失败:', error);
throw error; // 重新抛出错误,让调用方处理
}
},
/**
* 创建标记点的HTML内容,包含图标和文字
* @param {Object} entityInfo - 实体信息
* @param {String} textDirection - 文字方向 ('vertical' 或 'horizontal')
* @param {Boolean} isSelected - 是否选中状态
* @returns {String} HTML字符串
*/
createMarkerContent(entityInfo, textDirection, isSelected) {
const iconUrl = entityInfo.icon || '';
const name = entityInfo.name || '';
// 根据选中状态和文字方向选择样式
let textStyle, containerStyle;
if (textDirection === 'vertical') {
textStyle = isSelected ? this.adaptiveMarkerStyle2 : this.adaptiveMarkerStyle1;
containerStyle = 'flex-direction: column; align-items: center;';
} else {
textStyle = isSelected ? this.adaptiveMarkerStyle2Horizontal : this.adaptiveMarkerStyle1Horizontal;
containerStyle = 'flex-direction: row; align-items: center;';
}
// 将样式对象转换为CSS字符串
const textStyleStr = Object.entries(textStyle)
.map(([key, value]) => `${key}: ${value}`)
.join('; ');
// 创建HTML内容
const html = `
<div style="display: flex; ${containerStyle} cursor: pointer;">
${iconUrl ? `<img src="${iconUrl}" style="width: 20px; height: 20px; margin: ${textDirection === 'vertical' ? '0 0 4px 0' : '0 4px 0 0'};" />` : ''}
<div style="${textStyleStr}">${name}</div>
</div>
`;
return html;
},
initMap() {
// 初始化地图
this.map = new AMap.Map('container', {
viewMode: '2D', // 设置地图模式
turboMode: false,
showIndoorMap: false,
defaultCursor: 'pointer', // 地图默认鼠标样式
showBuildingBlock: false, // 是否展示地图 3D 楼块
zooms: this.data_zooms, // 地图显示的缩放级别范围, 默认为 [2, 20] ,取值范围 [2 ~ 30]
showLabel: true, // 是否展示地图文字和 POI 信息
zoom: this.data_zoom, // 设置地图显示的缩放级别
pitch: 0, // 俯仰角度,默认 0,最大值根据地图当前 zoom 级别不断增大,2D地图下无效 。
rotation: this.data_rotation, // 地图顺时针旋转角度,取值范围 [0-360] ,默认值:0
center: this.data_center, // 设置地图中心点坐标
forceVector: false,
// rotateEnable: true,
layers: this.data_layers,
features: ['bg', 'road', 'building', 'point'], // 设置地图上显示的元素种类
animateEnable: false, // 地图平移过程中是否使用动画
resizeEnable: true,
WebGLParams: { // 新增WebGL优化参数
preserveDrawingBuffer: true,
antialias: true,
stencil: true,
alpha: true
},
optimizeTileStrategy: true, // 开启瓦片优化
autoRendering: false // 关闭自动渲染
});
// 添加地图点击事件
this.map.on("click", this.showInfoClick);
// 加载景点图层
this.navKey && this.loadMaker(this.navKey);
//
this.map.setRotation(this.data_rotation, true);
},
loadMaker(id) {
var zoomStyleMapping = { 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0 };
const entity_info = this.navBarList.filter(item => item.id === id)[0]['list'];
this.markerSum = [];
_.each(entity_info, (x, i) => {
let marker_icon = '';
if (entity_info[i].window_type === 'warn' && entity_info[i].details.length === 1) { // 如果是预警类型并且内部预警项目只有一个取details第一个icon
marker_icon = entity_info[i].details[0]['icon'];
} else {
marker_icon = entity_info[i].icon;
}
let text_direction = entity_info[i]?.writing_mode === 'vertical' ? 'vertical' : 'horizontal';
// 创建自定义HTML内容,包含图标和文字
const markerContent = this.createMarkerContent(entity_info[i], text_direction, false);
let textMarker = new AMap.Marker({
zooms: this.data_zooms, // 点标记显示的层级范围,使用地图配置的缩放范围
content: markerContent, // 自定义HTML内容
anchor: "center", // 设置标记锚点位置
position: entity_info[i].position, // 点标记在地图上显示的位置
});
textMarker.setMap(this.map); //将文本标记设置到地图上
this.markerSum.push(textMarker);
if (clickListener1) {
textMarker.off('click', clickListener)
}
// 绑定景点的点击事件 - 文字出现才能触发
var clickListener1 = textMarker.on('click', async (e) => {
// 还原样式 - 将其他标记设为未选中状态
this.markerSum.forEach((item, index) => {
if (item !== textMarker) {
const itemInfo = entity_info[index] || entity_info.find(info => info.position[0] === item.getPosition().lng && info.position[1] === item.getPosition().lat);
if (itemInfo) {
const itemDirection = itemInfo?.writing_mode === 'vertical' ? 'vertical' : 'horizontal';
const newContent = this.createMarkerContent(itemInfo, itemDirection, false);
item.setContent(newContent);
}
}
});
// 设置当前标记为选中状态
const newContent = this.createMarkerContent(entity_info[i], text_direction, true);
textMarker.setContent(newContent);
// 修改文本内容
// textMarker.setText('样式已修改');
//
// 先获取音频信息
const { data, code } = await mapAudioAPI({ mid: this.$route.query.id, bid: entity_info[i].id });
// 创建新的对象并设置音频状态
const updatedInfo = JSON.parse(JSON.stringify(entity_info[i]));
if (data.length && updatedInfo.details && updatedInfo.details[0]) {
updatedInfo.details[0].show_audio = true;
}
// 使用 nextTick 确保视图更新
await this.$nextTick();
this.itemInfo = updatedInfo;
// 写入用户经纬度
const current_lng = this.$route.query?.current_lng || '';
const current_lat = this.$route.query?.current_lat || '';
const openid = this.$route.query?.openid || '';
if (openid) {
this.itemInfo.openid = openid;
}
if (current_lng && current_lat) {
this.itemInfo.current_lng = current_lng;
this.itemInfo.current_lat = current_lat;
} else {
this.itemInfo.current_lng = '';
this.itemInfo.current_lat = '';
// 提示用户获取定位
this.show_toast = true;
this.toast_text = '请先获取定位权限'
}
// 详情为空提示
if (!this.itemInfo.details.length) {
this.show_toast = true;
this.toast_text = '该景点暂无详情'
return;
}
// 打开浮动面板
this.info_height = (0.65 * window.innerHeight);
// 浮动面板样式
$('.van-floating-panel__content').css('borderRadius', '1.25rem');
$('.van-floating-panel').css('boxShadow', '0 0 15px black');
// 定位到当前位置中心
// this.map.setZoomAndCenter(this.zoom, this.itemInfo.position);
// 获取地图容器的高度
const mapHeight = this.map.getSize().height;
// 计算需要向上移动的像素值,比如向上移动地图高度的一半左右
const offsetY = -mapHeight / 3.5;
// 使用 panBy 方法进行视图偏移
// this.map.panBy(0, offsetY);
// 等待组件渲染完成后调用打卡状态检查
await this.$nextTick();
if (this.$refs.pageInfo && this.$refs.pageInfo.checkInitialCheckinStatus) {
await this.$refs.pageInfo.checkInitialCheckinStatus();
}
})
// if (entity_info[i]?.writing_mode === 'vertical') { // 标题文字垂直
// let textMarker = new AMap.Text({
// zooms: [18, 20], // 点标记显示的层级范围,超过范围不显示。
// text: entity_info[i].name, //标记显示的文本内容
// anchor: "center", //设置文本标记锚点位置
// // draggable: true, //是否可拖拽
// // cursor: "pointer", //指定鼠标悬停时的鼠标样式。
// // angle: 10, //点标记的旋转角度
// style: this.markerStyle1,
// position: entity_info[i].position, //点标记在地图上显示的位置
// });
// textMarker.setMap(this.map); //将文本标记设置到地图上
// this.markerSum.push(textMarker);
// if (clickListener1) {
// textMarker.off('click', clickListener)
// }
// // 绑定景点的点击事件 - 文字出现才能触发
// var clickListener1 = textMarker.on('click', (e) => {
// // 还原样式
// this.markerSum.forEach(item => {
// if (e.target.hS !== item.hS) {
// // 修改文本的样式
// item.setStyle(this.markerStyle2);
// }
// })
// // 修改文本的样式
// e.target.setStyle(this.markerStyle1);
// // 修改文本内容
// // textMarker.setText('样式已修改');
// //
// // console.warn(e);
// this.itemInfo = entity_info[i];
// // 详情为空提示
// if (!this.itemInfo.details.length) {
// this.show_toast = true;
// this.toast_text = '该景点暂无详情'
// return;
// }
// // 打开浮动面板
// this.info_height = (0.65 * window.innerHeight);
// // 浮动面板样式
// $('.van-floating-panel__content').css('borderRadius', '1.25rem');
// $('.van-floating-panel').css('boxShadow', '0 0 15px black');
// // 定位到当前位置中心
// this.map.setZoomAndCenter(this.zoom, this.itemInfo.position);
// // 获取地图容器的高度
// const mapHeight = this.map.getSize().height;
// // 计算需要向上移动的像素值,比如向上移动地图高度的一半左右
// const offsetY = -mapHeight / 3.5;
// // 使用 panBy 方法进行视图偏移
// this.map.panBy(0, offsetY);
// })
// }
// TODO: 获取详情定位信息用来导航
// 导航路径
let marker_id = this.$route.query.marker_id;
if (marker_id) {
this.$nextTick(() => {
let marker = this.navBarList[0]['list'].filter(item => item.id == marker_id)
// let path = marker[0].path;
// this.addSafeRoute({name: '参观路径', path});
// TAG: 新增步行导航
let position = marker[0].position;
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: (res) => {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
this.current_lng = GPS.gcj_encrypt(latitude, longitude).lon;
this.current_lat = GPS.gcj_encrypt(latitude, longitude).lat;
this.onWalkRoute({point: position});
},
});
// 获取当前 URL 的查询参数
let query = { ...this.$route.query };
// 删除 marker_id 参数
delete query.marker_id;
// 使用 Vue Router 更新 URL,并且不刷新页面
this.$router.replace({ query });
});
}
});
this.map.add(this.markerSum);
//
// setTimeout(() => {
// // 获取定位打标记
// this.setLocation();
// }, 1000);
},
isPointInRing() { // 是否在景区范围
let isPointInRing = AMap.GeometryUtil.isPointInRing([this.current_lng, this.current_lat], this.point_range);
return isPointInRing
},
setLocation() { // 开启定位服务
// 获取失败
// if (!this.current_lng || !this.current_lat) {
// this.dialog_show = true;
// this.dialog_text = '获取经纬度失败';
// }
this.getLocation();
},
getLocation() { // 获取经纬度
// PC端无法获取定位
// 微信获取地址
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: (res) => {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
this.current_lng = GPS.gcj_encrypt(latitude, longitude).lon;
this.current_lat = GPS.gcj_encrypt(latitude, longitude).lat;
// 判断是否在范围内
// if (!this.isPointInRing()) {
// this.dialog_show = true;
// this.dialog_text = '您不在景区范围内';
// } else {
// 使用纠正偏移后的地址,打一个定位标记
this.location_marker = new AMap.LabelMarker({
icon: {
image: 'https://cdn.ipadbiz.cn/bieyuan/map/icon/Group%2034@3x.png',
anchor: 'bottom-center',
size: [65, 65],
},
position: new AMap.LngLat(this.current_lng, this.current_lat), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
});
this.map.add(this.location_marker);
// 定位到当前位置中心
// this.map.setZoomAndCenter(this.zoom, [this.current_lng, this.current_lat]);
// 提示获取经纬度成功
this.show_toast = true;
this.toast_text = '获取经纬度成功';
//
this.is_get_location = true;
// }
},
complete: () => {
// 获取失败
if (!this.current_lng || !this.current_lat) {
this.dialog_show = true;
this.dialog_text = '获取经纬度失败';
}
},
});
},
setZoom(type) { // 设置放大缩小地图
const zoom = this.map.getZoom();
if (type === 'plus') {
this.map.setZoom(zoom + 1)
}
if (type === 'minus') {
this.map.setZoom(zoom - 1)
}
},
computedMapSource(x, y, z) { // 根据图层信息生成图层实际地址
for (const id in this.mapTiles) {
if (z == id) {
const scope = this.mapTiles[id];
return scope[`${x}-${y}`]
}
}
},
setTitleLayer() { // 生成瓦片图
// 获取瓦片图渲染范围
function getFirstProperty(obj) {
for (var prop in obj) {
return prop;
}
}
function getLastProperty(obj) {
var props = [];
for (var prop in obj) {
props.push(prop);
}
return props[props.length - 1];
}
let obj_scope = {};
for (const key in this.mapTiles) {
const element = this.mapTiles[key];
let first = getFirstProperty(element).split('-');
let last = getLastProperty(element).split('-');
obj_scope[key] = {
x: [first[0], last[0]],
y: [first[1], last[1]]
}
}
const _this = this;
var layer = new AMap.TileLayer.Flexible({
cacheSize: 50,
opacity: 1,
zIndex: 100,
createTile: function (x, y, z, success, fail) {
// 控制地图等级显示图片范围-过滤不显示的图层渲染
for (const id in obj_scope) {
if (z == id) {
const scope = obj_scope[id];
if (x < scope.x[0] || x > scope.x[1]) {
fail()
return;
}
if (y < scope.y[0] || y > scope.y[1]) {
fail()
return;
}
}
}
var img = document.createElement('img');
img.onload = function () {
success(img)
};
img.crossOrigin = "anonymous";// 必须添加,同时图片要有跨域头
img.onerror = function () {
fail()
};
// img.src = `images/tiles/${z}/${x}_${y}.png`;
img.src = _this.computedMapSource(x, y, z);
},
});
this.map.addLayer(layer);
// Canvas作为切片
var layer1 = new AMap.TileLayer.Flexible({
// tileSize: 128,
cacheSize: 300,
zIndex: 200,
createTile: function (x, y, z, success, fail) {
var c = document.createElement('canvas');
c.width = c.height = 256;
var cxt = c.getContext("2d");
cxt.font = "15px Verdana";
cxt.fillStyle = "#ff0000";
cxt.strokeStyle = "#FF0000";
cxt.strokeRect(0, 0, 256, 256);
cxt.fillText('(' + [x, y, z].join(',') + ')', 10, 30);
// 通知API切片创建完成
success(c);
}
});
// layer1.setMap(this.map);
// 只显示相应区域,移动会回到选定范围
// this.lockMapBounds()
},
// 限制地图范围
lockMapBounds() {
// var bounds = this.map.getBounds();
var myBounds = new AMap.Bounds( // 移动范围,对角线
[117.04384,26.833629],
[117.055975,26.843652]
);
this.map.setLimitBounds(myBounds);
let list =[ // 四个角,覆盖填充范围
[117.04421,26.833875],
[117.045012,26.842089],
[117.054749,26.84219],
[117.056013,26.83387]
]
// 隐藏边界以外的区域
let outer = [
new AMap.LngLat(-360, 90, true),
new AMap.LngLat(-360, -90, true),
new AMap.LngLat(360, -90, true),
new AMap.LngLat(360, 90, true),
] // 遮盖填充反向
let pathArray = [
outer,
list
]
var polygon = new AMap.Polygon({
pathL: pathArray,
strokeColor: "#fcfbf9",
strokeWeight: 2,
fillColor: "#fcfbf9",
fillOpacity: 1,
})
polygon.setPath(pathArray)
this.map.add(polygon)
},
showInfoClick(e) {
// console.log(e);
var zoom = this.map.getZoom(); //获取当前地图级别
// var text =
// "您在 [" +
// e.lnglat.getLng() +
// "," +
// e.lnglat.getLat() +
// "] 的位置单击了地图!当前层级" +
// zoom;
var text =
"[" +
e.lnglat.getLng() +
"," +
e.lnglat.getLat() +
"],"
console.log(text);
// 点击空白处,关闭弹框
if (this.info_height) {
// 关闭浮动面板
this.info_height = 0;
$('.van-floating-panel').css('boxShadow', 'none');
// 还原样式
this.resetMarkStyle();
}
},
scanQrcode() { // 扫码跳转详情页
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: (res) => {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
let id = parseQueryString(result).id;
let marker_id = parseQueryString(result).marker_id;
// 跳转详情页
this.$router.push({
path: '/checkin/info',
query: {
id,
marker_id
}
})
}
});
// 识别率太低
// this.$router.push({
// path: '/checkin/scan'
// })
},
onHeightChange ({ height }) { // 监听浮动面板高度变化
if (height > window.innerHeight * 0.6) {
// // 浮动面板样式
// $('.van-floating-panel__content').css('borderRadius', '0');
// this.showClose = true;
// 清空设置
// this.changeAudio('');
// this.changeAudioStatus('pause');
//
this.$router.push({
path: '/checkin/info',
query: {
id: this.$route.query.id,
marker_id: this.itemInfo.id,
current_lng: this.itemInfo.current_lng,
current_lat: this.itemInfo.current_lat,
openid: this.itemInfo.openid,
}
})
} else {
$('.van-floating-panel__content').css('borderRadius', '1.25rem');
$('.van-floating-panel').css('boxShadow', 'none');
this.showClose = false;
}
},
closeFloatPanel () {
this.info_height = (0.65 * window.innerHeight);
$('.van-floating-panel__content').css('borderRadius', '1.25rem');
this.showClose = false;
// 关闭音频
this.$refs.pageInfo.outerStopAudio();
},
resetMarkStyle () {
// 重置所有标记为未选中状态
this.markerSum.forEach((item, index) => {
// 获取对应的实体信息
const entityInfo = this.navList[index];
if (entityInfo) {
const textDirection = entityInfo?.writing_mode === 'vertical' ? 'vertical' : 'horizontal';
const newContent = this.createMarkerContent(entityInfo, textDirection, false);
item.setContent(newContent);
}
});
},
onCloseFloat () {
this.info_height = 0;
$('.van-floating-panel__content').css('borderRadius', '1.25rem');
$('.van-floating-panel').css('boxShadow', 'none');
this.resetMarkStyle();
},
addSafeRoute({name, path}) { // 新增路径
// 获取对象的第一个键和值
// let firstKey = Object.keys(this.data_paths)[0];
// let firstValue = this.data_paths[firstKey];
// 行动路线
// var path = [
// [120.587645, 31.314833],
// [120.587709, 31.314338],
// [120.588211, 31.314377],
// ];
// console.warn(firstValue);
// var path = firstValue;
// 生成折线地图路径
let current_safe_route = new AMap.Polyline({
path,
isOutline: true,
outlineColor: '#179FB1',
borderWeight: 1,
strokeColor: '#179FB1',
strokeOpacity: 1,
strokeWeight: 3,
// 折线样式还支持 'dashed'
strokeStyle: 'solid',
// strokeStyle是dashed时有效
strokeDasharray: [10, 5],
lineJoin: 'round',
lineCap: 'round',
zIndex: 50
})
this.map.add([current_safe_route]);
this.current_safe_route.push({
key: name,
path: current_safe_route
})
// 设置起始点标记
var marker1 = new AMap.Marker({
icon: new AMap.Icon({
image: 'https://cdn.ipadbiz.cn/bieyuan/map/icon/Ellipse%2013@3x.png',
size: new AMap.Size(15, 15),
// 图标所用图片大小
imageSize: new AMap.Size(15, 15),
// 图标取图偏移量
imageOffset: new AMap.Pixel(0, 0)
}),
position: new AMap.LngLat(path[0][0], path[0][1]), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
anchor: 'bottom-center',
offset: new AMap.Pixel(0, 0)
});
// marker1.setLabel({
// direction: 'right',
// offset: new AMap.Pixel(0, -10), //设置文本标注偏移量
// content: "<div class='info'>起点</div>", //设置文本标注内容
// });
var marker2 = new AMap.Marker({
icon: new AMap.Icon({
image: 'https://cdn.ipadbiz.cn/bieyuan/map/icon/Ellipse%2013@3x.png',
size: new AMap.Size(15, 15),
// 图标所用图片大小
imageSize: new AMap.Size(15, 15),
// 图标取图偏移量
imageOffset: new AMap.Pixel(0, 0)
}),
position: new AMap.LngLat(path[path.length - 1][0], path[path.length - 1][1]), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
anchor: 'bottom-center',
offset: new AMap.Pixel(0, 0)
});
// marker2.setLabel({
// direction: 'right',
// offset: new AMap.Pixel(0, -10), //设置文本标注偏移量
// content: "<div class='info'>终点</div>", //设置文本标注内容
// });
// 新增逃生路线标记
// this.route_safe_marker = [marker1, marker2]
// this.map.add(this.route_safe_marker);
// 新增逃生路线标记
let route_safe_marker = [marker1, marker2]
this.map.add(route_safe_marker);
this.route_safe_marker.push({
key: name,
path: route_safe_marker
});
// 关闭导航提示
this.show_walk_route = false;
},
removeSafeRoute({name}) { // 移除地图路线
this.current_safe_route.forEach(item => {
if (item.key === name) {
this.map.remove([item.path]); // 删除地图折线
}
});
// this.map.remove(this.route_safe_marker); // 删除起始点标记
this.route_safe_marker.forEach(item => {
if (item.key === name) {
this.map.remove(item.path); // 删除起始点标记
}
});
// 关闭导航提示
this.show_walk_route = true;
},
onRoute (path) {
console.warn(path);
// 模拟新增路线
this.addSafeRoute(path);
// 定位到当前位置中心
this.map.setZoomAndCenter(this.zoom, this.data_center);
},
async onWalkRoute (position) {
await this.$nextTick(); // 等待DOM更新
// 步行导航
// let walking = new AMap.Walking({
// map: this.map,
// panel: "panel"
// });
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: (res) => {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
this.current_lng = GPS.gcj_encrypt(latitude, longitude).lon;
this.current_lat = GPS.gcj_encrypt(latitude, longitude).lat;
// 确保参数格式正确
const startPoint = [this.current_lng, this.current_lat]; // 起点
const endPoint = position.point; // 终点
// 参数检查
if (!startPoint[0] || !startPoint[1]) {
this.show_toast = true;
this.toast_text = '无法获取当前位置,请确保已开启定位功能';
return;
}
if (!endPoint[0] || !endPoint[1]) {
this.show_toast = true;
this.toast_text = '目的地坐标不完整';
return;
}
// 转换为 LngLat 对象
const start = new AMap.LngLat(startPoint[0], startPoint[1]);
const end = new AMap.LngLat(endPoint[0], endPoint[1]);
// 规划步行路线
this.walking.search(start, end, (status, result) => {
if (status === 'complete') {
console.log('步行路线规划成功');
setTimeout(() =>{
// 定位到当前位置中心
this.getLocation();
this.show_walk_route = false;
},500)
} else {
console.error('步行路线规划失败:', status, result);
ElMessage.error('步行路线规划失败,请稍后重试');
}
});
},
});
},
handleLocation(status) { // 打开/关闭 当前定位
if (status) {
this.setLocation()
this.open_current_location = false;
} else {
this.removeLocation()
this.open_current_location = true;
}
},
removeLocation() { // 移除定位标记
this.current_lng = '';
this.current_lat = '';
this.map.remove(this.location_marker); // 删除当前定位标记
},
closeWalkingRoute() {
if (this.walking) {
this.walking.clear(); // 清除路线
this.show_walk_route = true; // 恢复状态
// 可选:移除面板内容
document.getElementById('walking-panel').innerHTML = '';
// 显示提示
this.show_toast = true;
this.toast_text = '已关闭步行导航';
}
},
}
}
</script>
<style lang="less">
#container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
// 遮挡地图logo
.amap-logo {
display: none!important;
visibility: hidden!important;
}
.amap-copyright {
display: none!important;
visibility: hidden!important;
}
/* 标记文字样式 */
.amap-marker-label {
padding: 0.25rem 0.5rem;
width: auto;
border: none;
border-radius: 2px;
background: rgba(86, 65, 23, 0.8);
color: white;
}
.amap-marker {
.amap-icon {
margin-top: 0.25rem;
}
}
.input-card {
display: flex;
flex-direction: column;
min-width: 0;
word-wrap: break-word;
background-color: #fff;
background-clip: border-box;
border-radius: .25rem;
width: 20rem;
border-width: 0;
border-radius: 0.4rem;
box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
position: fixed;
top: 4rem;
right: 1rem;
-ms-flex: 1 1 auto;
flex: 1 1 auto;
padding: 0.75rem 1.25rem;
}
.tool-bar-wrapper {
position: absolute;
left: 20px;
bottom: 8rem;
width: 20px;
}
.nav-bar-wrapper {
position: fixed;
bottom: 0;
left: 0;
height: 5.5rem;
width: 100%;
background-color: white;
text-align: center;
box-shadow: 0 -1px 0 rgba(80, 80, 80, 0.1);
z-index: 999;
// padding: 0.5rem 0;
padding-bottom: 0.5rem;
.nav-bar-content {
display: flex;
overflow-x: scroll;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
position: relative;
}
.item {
padding-top: 0.5rem;
color: #888;
width: 21.5%;
flex-shrink: 0;
padding-top: 1rem;
}
.checked {
color: #965f13;
}
}
.safe-route-wrapper {
position: absolute;
bottom: 2rem;
right: 1rem;
background-color: white;
}
.operate-bar-wrapper {
position: fixed;
left: 20px;
bottom: 6rem;
width: 20px;
height: auto;
z-index: 100;
.box-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.item {
position: relative;
text-align: center;
font-size: 0.85rem;
width: 2rem;
height: 2rem;
background-color: white;
margin-bottom: 1rem;
border-radius: 50%;
padding: 2.5px;
line-height: 2rem;
}
}
}
.popup-wrapper {
margin-top: 1rem;
.title {
font-size: 1.25rem;
margin-bottom: 0.85rem;
}
.content {
line-height: 1.75;
font-size: 0.95rem;
}
}
.hideScrollBar::-webkit-scrollbar {
display: none;
}
.hideScrollBar {
-ms-overflow-style: none;
overflow: -moz-scrollbars-none;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
color: #AB8F57;
}
.walk-nav-text {
position: fixed;
bottom: 6rem;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9;
background: rgba(86, 65, 23, 0.8);
color: white;
border-radius: 10px;
padding: 5px 12px;
font-size: 0.8rem;
}
.close-float-panel {
position: absolute;
top: 1rem;
left: 1rem;
}
.custom-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background-color: #f7f8fa;
}
.van-floating-panel__header-bar {
background: none;
}
/* 地图加载状态样式 */
.map-loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.9);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
backdrop-filter: blur(2px);
}
.loading-content {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
padding: 2rem;
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
max-width: 300px;
width: 90%;
}
.loading-text {
margin-top: 1rem;
color: #666;
font-size: 0.9rem;
}
.queue-info {
margin-top: 1rem;
padding: 0.75rem;
background: #f8f9fa;
border-radius: 8px;
border-left: 3px solid #DD7850;
width: 100%;
}
.queue-text, .wait-time {
margin: 0.25rem 0;
color: #DD7850;
font-size: 13px;
font-weight: 500;
}
.retry-info {
margin-top: 1rem;
padding: 0.5rem;
background: #fff3cd;
border-radius: 6px;
border: 1px solid #ffeaa7;
width: 100%;
}
.retry-text {
margin: 0;
color: #856404;
font-size: 12px;
}
/* 地图加载错误状态样式 */
.map-error-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.95);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.error-content {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
padding: 2rem;
max-width: 300px;
}
.error-title {
margin: 1rem 0 0.5rem 0;
font-size: 1.1rem;
font-weight: 600;
color: #333;
}
.error-message {
margin: 0.5rem 0 1.5rem 0;
color: #666;
font-size: 0.9rem;
line-height: 1.4;
}
</style>