Map.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <template>
  2. <div class="map-container">
  3. <div id="baidu-map" ref="mapContainer"></div>
  4. <div class="map-controls">
  5. <button @click="zoomIn">放大</button>
  6. <button @click="zoomOut">缩小</button>
  7. <button @click="toggleMapType">切换地图类型({{ mapType === 'BMAP_NORMAL_MAP' ? '地图' : '卫星' }})</button>
  8. </div>
  9. <div v-if="selectedDevice" class="device-info-dialog" :style="{ left: dialogLeft + 'px', top: dialogTop + 'px' }">
  10. <div class="dialog-header">
  11. <h3>设备详情</h3>
  12. <button @click="closeDeviceInfo">×</button>
  13. </div>
  14. <div class="dialog-content">
  15. <p><strong>设备ID:</strong> {{ selectedDevice.id }}</p>
  16. <p><strong>设备名称:</strong> {{ selectedDevice.name }}</p>
  17. <p><strong>位置:</strong> {{ selectedDevice.location }}</p>
  18. <p><strong>状态:</strong> {{ deviceStatusMap[selectedDevice.status] }}</p>
  19. </div>
  20. </div>
  21. </div>
  22. </template>
  23. <script lang="ts">
  24. import { defineComponent, onMounted, onBeforeUnmount, ref } from 'vue';
  25. interface Device {
  26. id: string;
  27. name: string;
  28. location: string;
  29. status: number;
  30. lng: number;
  31. lat: number;
  32. }
  33. interface Cluster {
  34. lng: number;
  35. lat: number;
  36. count: number;
  37. devices?: Device[];
  38. }
  39. export default defineComponent({
  40. name: 'ChinaDeviceMap',
  41. setup() {
  42. const mapContainer = ref<HTMLElement | null>(null);
  43. const map = ref<any>(null);
  44. const mapType = ref<'BMAP_NORMAL_MAP' | 'BMAP_SATELLITE_MAP'>('BMAP_NORMAL_MAP');
  45. const selectedDevice = ref<Device | null>(null);
  46. const hoverDevice = ref<Device | null>(null);
  47. const clusters = ref<Cluster[]>([]);
  48. const dialogLeft = ref<number>(0);
  49. const dialogTop = ref<number>(0);
  50. // 设备数据示例
  51. const devices = ref<Device[]>([
  52. { id: 'D001', name: '设备1', location: '北京', status: 1, lng: 116.404, lat: 39.915 },
  53. { id: 'D002', name: '设备2', location: '上海', status: 2, lng: 121.474, lat: 31.230 },
  54. { id: 'D003', name: '设备3', location: '广州', status: 1, lng: 113.264, lat: 23.129 },
  55. { id: 'D004', name: '设备4', location: '深圳', status: 3, lng: 114.058, lat: 22.543 },
  56. { id: 'D005', name: '设备5', location: '成都', status: 1, lng: 104.065, lat: 30.659 },
  57. { id: 'D006', name: '设备6', location: '武汉', status: 2, lng: 114.305, lat: 30.593 },
  58. { id: 'D007', name: '设备7', location: '西安', status: 1, lng: 108.948, lat: 34.263 },
  59. { id: 'D008', name: '设备8', location: '杭州', status: 3, lng: 120.155, lat: 30.274 },
  60. { id: 'D009', name: '设备9', location: '南京', status: 1, lng: 118.797, lat: 32.060 },
  61. { id: 'D010', name: '设备10', location: '重庆', status: 2, lng: 106.505, lat: 29.533 },
  62. ]);
  63. const deviceStatusMap = {
  64. 1: '在线',
  65. 2: '离线',
  66. 3: '异常'
  67. };
  68. // 初始化地图
  69. const initMap = () => {
  70. if (!mapContainer.value) return;
  71. const script = document.createElement('script');
  72. script.src = `https://api.map.baidu.com/api?v=3.0&ak=c0crhdxQ5H7WcqbcazGr7mnHrLa4GmO0&type=webgl`;
  73. script.async = true;
  74. script.onload = () => {
  75. if ((window as any).BMap) {
  76. map.value = new (window as any).BMap.Map(mapContainer.value);
  77. const point = new (window as any).BMap.Point(104.114129, 37.550339);
  78. map.value.centerAndZoom(point, 5);
  79. map.value.enableScrollWheelZoom(true);
  80. map.value.setMapType((window as any)[mapType.value]);
  81. map.value.addControl(new (window as any).BMap.NavigationControl());
  82. map.value.addControl(new (window as any).BMap.ScaleControl());
  83. initDeviceMarkers();
  84. map.value.addEventListener('zoomend', initDeviceMarkers);
  85. // 添加地图点击事件监听器
  86. map.value.addEventListener('click', closeDeviceInfoIfOutside);
  87. } else {
  88. console.error('百度地图API加载失败');
  89. }
  90. };
  91. script.onerror = () => {
  92. console.error('百度地图API加载失败');
  93. };
  94. document.head.appendChild(script);
  95. };
  96. const initDeviceMarkers = () => {
  97. if (!map.value) return;
  98. map.value.clearOverlays();
  99. const zoomLevel = map.value.getZoom();
  100. if (zoomLevel > 10) {
  101. // 高缩放级别下显示单个设备标记
  102. devices.value.forEach(device => {
  103. const point = new (window as any).BMap.Point(device.lng, device.lat);
  104. const marker = createDeviceMarker(device, point);
  105. map.value.addOverlay(marker);
  106. });
  107. } else {
  108. // 低缩放级别下进行聚合
  109. clusters.value = clusterDevices(devices.value, map.value);
  110. clusters.value.forEach(cluster => {
  111. if (cluster.count === 1) {
  112. // 只有一个设备时显示设备图标
  113. const device = cluster.devices?.[0];
  114. if (device) {
  115. const point = new (window as any).BMap.Point(device.lng, device.lat);
  116. const marker = createDeviceMarker(device, point);
  117. map.value.addOverlay(marker);
  118. }
  119. } else if (cluster.count > 1) {
  120. // 多个设备时显示聚合标签
  121. const point = new (window as any).BMap.Point(cluster.lng, cluster.lat);
  122. const label = createClusterLabel(cluster, point);
  123. map.value.addOverlay(label);
  124. }
  125. });
  126. }
  127. };
  128. const createDeviceMarker = (device: Device, point: any) => {
  129. const marker = new (window as any).BMap.Marker(point, {
  130. icon: new (window as any).BMap.Icon('https://iot.deepoil.cc/images/ding300.svg', new (window as any).BMap.Size(28, 30),
  131. {
  132. anchor: new (window as any).BMap.Size(10, 25),
  133. // imageOffset: new (window as any).BMap.Size(0, -5)
  134. }
  135. )
  136. });
  137. // 添加点击事件
  138. marker.addEventListener('click', () => {
  139. showDeviceInfo(device, point);
  140. });
  141. // 添加鼠标悬停事件
  142. marker.addEventListener('mouseover', () => {
  143. hoverDevice.value = device;
  144. showDeviceInfo(device, point);
  145. });
  146. marker.addEventListener('mouseout', () => {
  147. hoverDevice.value = null;
  148. });
  149. return marker;
  150. };
  151. const createClusterLabel = (cluster: Cluster, point: any) => {
  152. const label = new (window as any).BMap.Label(cluster.count.toString(), {
  153. position: point,
  154. offset: new (window as any).BMap.Size(-10, -10)
  155. });
  156. // 初始样式
  157. label.setStyle({
  158. color: '#fff',
  159. backgroundColor: '#c38f65',
  160. borderRadius: '50%',
  161. width: '40px',
  162. height: '40px',
  163. textAlign: 'center',
  164. lineHeight: '40px',
  165. cursor: 'pointer',
  166. fontSize: '18px',
  167. fontWeight: 'bold',
  168. boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
  169. transition: 'all 0.3s ease',
  170. border: '3px solid rgba(255, 255, 255, 0.5)' // 添加带有不透明度的边框
  171. });
  172. // 鼠标悬停样式
  173. const hoverStyle = {
  174. backgroundColor: '#a5734b',
  175. transform: 'scale(1.1)'
  176. };
  177. // 鼠标移出样式
  178. const normalStyle = {
  179. backgroundColor: '#c38f65',
  180. transform: 'scale(1)'
  181. };
  182. // 添加鼠标悬停事件
  183. label.addEventListener('mouseover', () => {
  184. Object.assign(label.getStyle(), hoverStyle);
  185. label.setStyle(label.getStyle());
  186. });
  187. // 添加鼠标移出事件
  188. label.addEventListener('mouseout', () => {
  189. Object.assign(label.getStyle(), normalStyle);
  190. label.setStyle(label.getStyle());
  191. });
  192. // 添加点击事件
  193. label.addEventListener('click', () => {
  194. map.value?.setZoom(9.5);
  195. map.value?.panTo(point);
  196. });
  197. return label;
  198. };
  199. const clusterDevices = (devices: Device[], map: any): Cluster[] => {
  200. const clusters: Cluster[] = [];
  201. const gridSize = getGridSize(map.getZoom());
  202. const gridMap = new Map<string, Cluster>();
  203. devices.forEach(device => {
  204. const gridKey = `${Math.floor(device.lng / gridSize)}_${Math.floor(device.lat / gridSize)}`;
  205. if (!gridMap.has(gridKey)) {
  206. gridMap.set(gridKey, {
  207. lng: Math.floor(device.lng / gridSize) * gridSize + gridSize / 2,
  208. lat: Math.floor(device.lat / gridSize) * gridSize + gridSize / 2,
  209. count: 0,
  210. devices: []
  211. });
  212. }
  213. const cluster = gridMap.get(gridKey)!;
  214. cluster.count++;
  215. if (!cluster.devices) cluster.devices = [];
  216. cluster.devices.push(device);
  217. });
  218. return Array.from(gridMap.values());
  219. };
  220. const getGridSize = (zoom: number): number => {
  221. if (zoom <= 5) return 2;
  222. if (zoom <= 8) return 1;
  223. if (zoom <= 10) return 0.5;
  224. return 0.1;
  225. };
  226. const showDeviceInfo = (device: Device, point: any) => {
  227. selectedDevice.value = device;
  228. const pixel = map.value.pointToOverlayPixel(point);
  229. const dialogWidth = 300; // 对话框宽度
  230. const arrowWidth = 10; // 箭头宽度
  231. const arrowHeight = 10; // 箭头高度
  232. // 计算对话框的左偏移量,使箭头居中指向设备
  233. dialogLeft.value = pixel.x - dialogWidth / 2;
  234. // 计算对话框的上偏移量,使箭头指向设备
  235. dialogTop.value = pixel.y - arrowHeight;
  236. // 确保对话框不会超出地图边界
  237. if (dialogLeft.value < 0) {
  238. dialogLeft.value = 0;
  239. }
  240. if (dialogTop.value < 0) {
  241. dialogTop.value = 0;
  242. }
  243. };
  244. const closeDeviceInfo = () => {
  245. selectedDevice.value = null;
  246. };
  247. const closeDeviceInfoIfOutside = (e: any) => {
  248. const dialogElement = document.querySelector('.device-info-dialog');
  249. if (dialogElement && selectedDevice.value) {
  250. const rect = dialogElement.getBoundingClientRect();
  251. const x = e.pixel.x;
  252. const y = e.pixel.y;
  253. if (
  254. x < rect.left ||
  255. x > rect.right ||
  256. y < rect.top ||
  257. y > rect.bottom
  258. ) {
  259. closeDeviceInfo();
  260. }
  261. }
  262. };
  263. const zoomIn = () => {
  264. if (map.value) {
  265. map.value.zoomIn();
  266. }
  267. };
  268. const zoomOut = () => {
  269. if (map.value) {
  270. map.value.zoomOut();
  271. }
  272. };
  273. const toggleMapType = () => {
  274. if (!map.value) return;
  275. mapType.value = mapType.value === 'BMAP_NORMAL_MAP'
  276. ? 'BMAP_SATELLITE_MAP'
  277. : 'BMAP_NORMAL_MAP';
  278. map.value.setMapType((window as any)[mapType.value]);
  279. };
  280. onMounted(() => {
  281. initMap();
  282. });
  283. onBeforeUnmount(() => {
  284. if (map.value) {
  285. map.value.destroy();
  286. }
  287. });
  288. return {
  289. mapContainer,
  290. selectedDevice,
  291. hoverDevice,
  292. deviceStatusMap,
  293. zoomIn,
  294. zoomOut,
  295. toggleMapType,
  296. showDeviceInfo,
  297. closeDeviceInfo,
  298. dialogLeft,
  299. dialogTop
  300. };
  301. }
  302. });
  303. </script>
  304. <style scoped>
  305. .map-container {
  306. position: relative;
  307. width: 100%;
  308. height: 100vh;
  309. }
  310. #baidu-map {
  311. width: 100%;
  312. height: 100%;
  313. }
  314. .map-controls {
  315. position: absolute;
  316. top: 20px;
  317. left: 20px;
  318. z-index: 1000;
  319. display: flex;
  320. gap: 10px;
  321. }
  322. .map-controls button {
  323. padding: 5px 10px;
  324. background: #fff;
  325. border: 1px solid #ccc;
  326. border-radius: 3px;
  327. cursor: pointer;
  328. }
  329. .device-info-dialog {
  330. position: absolute;
  331. z-index: 1000;
  332. width: 300px;
  333. background: #fff;
  334. border-radius: 5px;
  335. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  336. padding: 15px;
  337. }
  338. .dialog-header {
  339. display: flex;
  340. justify-content: space-between;
  341. align-items: center;
  342. margin-bottom: 10px;
  343. }
  344. .dialog-header button {
  345. background: none;
  346. border: none;
  347. font-size: 18px;
  348. cursor: pointer;
  349. }
  350. .dialog-content p {
  351. margin: 5px 0;
  352. }
  353. /* 箭头样式 */
  354. .dialog-arrow {
  355. position: absolute;
  356. bottom: -10px; /* 调整箭头的垂直位置 */
  357. left: 50%; /* 使箭头水平居中 */
  358. transform: translateX(-50%); /* 使箭头水平居中 */
  359. width: 0;
  360. height: 0;
  361. border-left: 10px solid transparent;
  362. border-right: 10px solid transparent;
  363. border-top: 10px solid #fff; /* 箭头颜色与对话框背景色一致 */
  364. }
  365. </style>