Map.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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"
  8. >切换地图类型({{ mapType === 'BMAP_NORMAL_MAP' ? '地图' : '卫星' }})</button>
  9. </div>
  10. </div>
  11. <DeviceMonitorDrawer :model-value="drawerVisible" @update:model-value="(val) => (drawerVisible = val)" :id="deviceId" :deviceName="deviceName" :lastLineTime="lastLineTime"
  12. :ifLine="ifLine" :dept="dept" :deviceCode="deviceCode"
  13. ref="showDrawer" />
  14. </template>
  15. <script setup lang="ts">
  16. import { onBeforeUnmount, onMounted, ref } from 'vue'
  17. import { DICT_TYPE, getDictLabel } from '@/utils/dict'
  18. import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
  19. import DeviceMonitorDrawer from '@/views/pms/map/DeviceMonitorDrawer.vue'
  20. import * as DeptApi from '@/api/system/dept'
  21. interface Cluster {
  22. lng: number
  23. lat: number
  24. count: number
  25. devices?: IotDeviceVO[]
  26. }
  27. defineOptions({ name: 'DeviceMap' })
  28. const showDrawer = ref()
  29. const drawerVisible = ref<boolean>(false)
  30. const mapContainer = ref<HTMLElement | null>(null)
  31. const map = ref<any>(null)
  32. const mapType = ref<'BMAP_NORMAL_MAP' | 'BMAP_SATELLITE_MAP'>('BMAP_NORMAL_MAP')
  33. const selectedDevice = ref<IotDeviceVO | null>(null)
  34. const hoverDevice = ref<IotDeviceVO | null>(null)
  35. const clusters = ref<Cluster[]>([])
  36. const deviceId = ref()
  37. const deviceName = ref('')
  38. const lastLineTime = ref('')
  39. const ifLine = ref()
  40. const dept = ref('')
  41. const deviceCode = ref('')
  42. // 设备数据示例
  43. const devices = ref<IotDeviceVO[]>()
  44. // 初始化地图
  45. const initMap = () => {
  46. if (!mapContainer.value) return
  47. const script = document.createElement('script')
  48. script.src = `https://api.map.baidu.com/api?v=3.0&ak=c0crhdxQ5H7WcqbcazGr7mnHrLa4GmO0&type=webgl`
  49. script.async = true
  50. script.onload = () => {
  51. if ((window as any).BMap) {
  52. map.value = new (window as any).BMap.Map(mapContainer.value)
  53. const point = new (window as any).BMap.Point(104.114129, 37.550339)
  54. map.value.centerAndZoom(point, 6)
  55. map.value.enableScrollWheelZoom(true)
  56. map.value.setMapType((window as any)[mapType.value])
  57. map.value.addControl(new (window as any).BMap.NavigationControl())
  58. map.value.addControl(new (window as any).BMap.ScaleControl())
  59. initDeviceMarkers()
  60. map.value.addEventListener('zoomend', () => {
  61. initDeviceMarkers()
  62. })
  63. } else {
  64. console.error('百度地图API加载失败')
  65. }
  66. }
  67. script.onerror = () => {
  68. console.error('百度地图API加载失败')
  69. }
  70. document.head.appendChild(script)
  71. }
  72. const initDeviceMarkers = () => {
  73. if (!map.value) return
  74. map.value.clearOverlays()
  75. const zoomLevel = map.value.getZoom()
  76. debugger
  77. if (zoomLevel > 9) {
  78. // 高缩放级别下显示单个设备标记
  79. devices.value.forEach((device) => {
  80. const point = new (window as any).BMap.Point(device.lng, device.lat)
  81. const marker = createDeviceMarker(device, point)
  82. map.value.addOverlay(marker)
  83. })
  84. } else {
  85. // 低缩放级别下进行聚合
  86. clusters.value = clusterDevices(devices.value, map.value)
  87. clusters.value.forEach((cluster) => {
  88. if (cluster.count === 1) {
  89. // 只有一个设备时显示设备图标
  90. const device = cluster.devices?.[0]
  91. if (device) {
  92. const point = new (window as any).BMap.Point(device.lng, device.lat)
  93. const marker = createDeviceMarker(device, point)
  94. map.value.addOverlay(marker)
  95. }
  96. } else if (cluster.count > 1) {
  97. // 多个设备时显示聚合标签
  98. const point = new (window as any).BMap.Point(cluster.lng, cluster.lat)
  99. const label = createClusterLabel(cluster, point)
  100. map.value.addOverlay(label)
  101. }
  102. })
  103. }
  104. }
  105. const createDeviceMarker = (device: IotDeviceVO, point: any) => {
  106. // 根据设备是否在线选择不同的图标
  107. const iconUrl = device.ifInline === 3
  108. ? 'https://iot.deepoil.cc/images/dinggreen.svg'
  109. : 'https://iot.deepoil.cc/images/dingout.svg';
  110. const marker = new (window as any).BMap.Marker(point, {
  111. icon: new (window as any).BMap.Icon(
  112. iconUrl,
  113. new (window as any).BMap.Size(40, 40),
  114. {
  115. anchor: new (window as any).BMap.Size(25, 40)
  116. // imageOffset: new (window as any).BMap.Size(0, -5)
  117. }
  118. )
  119. });
  120. // 添加点击事件
  121. marker.addEventListener('click', () => {
  122. showDeviceInfoWindow(device, point);
  123. });
  124. return marker;
  125. };
  126. const createClusterLabel = (cluster: Cluster, point: any) => {
  127. const label = new (window as any).BMap.Label(cluster.count.toString(), {
  128. position: point,
  129. offset: new (window as any).BMap.Size(-10, -10)
  130. })
  131. // 创建一个 style 标签并添加到 head 中,定义呼吸动画
  132. const style = document.createElement('style')
  133. style.textContent = `
  134. @keyframes breathing {
  135. 0% {
  136. border-color: rgba(255, 255, 255, 0.3);
  137. }
  138. 50% {
  139. border-color: rgba(255, 255, 255, 0.8);
  140. }
  141. 100% {
  142. border-color: rgba(255, 255, 255, 0.3);
  143. }
  144. }
  145. `
  146. document.head.appendChild(style)
  147. // 初始样式
  148. label.setStyle({
  149. color: '#fff',
  150. backgroundColor: 'blue',
  151. borderRadius: '50%',
  152. width: '50px',
  153. height: '50px',
  154. textAlign: 'center',
  155. lineHeight: '40px',
  156. cursor: 'pointer',
  157. fontSize: '18px',
  158. fontWeight: 'bold',
  159. boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
  160. transition: 'all 0.3s ease',
  161. border: '6px solid rgba(255, 255, 255, 0.5)', // 添加带有不透明度的边框
  162. animation: 'breathing 1.5s infinite' // 添加呼吸动画
  163. })
  164. // 鼠标悬停样式
  165. const hoverStyle = {
  166. backgroundColor: '#2196df',
  167. transform: 'scale(1.1)'
  168. }
  169. // 鼠标移出样式
  170. const normalStyle = {
  171. backgroundColor: '#c38f65',
  172. transform: 'scale(1)'
  173. }
  174. // 添加点击事件
  175. label.addEventListener('click', () => {
  176. if (map.value) {
  177. const currentZoom = map.value.getZoom();
  178. const MAX_ZOOM = 19; // 手动设定最大缩放级别
  179. const newZoom = Math.min(currentZoom + 3, MAX_ZOOM);
  180. map.value.setZoom(newZoom);
  181. map.value.panTo(point);
  182. initDeviceMarkers(); // 重新计算并显示标记和聚合标签
  183. }
  184. })
  185. return label
  186. }
  187. const clusterDevices = (devices: IotDeviceVO[], map: any): Cluster[] => {
  188. const clusters: Cluster[] = []
  189. const gridSize = getGridSize(map.getZoom())
  190. const gridMap = new Map<string, Cluster>()
  191. devices.forEach((device) => {
  192. const gridKey = `${Math.floor(device.lng / gridSize)}_${Math.floor(device.lat / gridSize)}`
  193. if (!gridMap.has(gridKey)) {
  194. gridMap.set(gridKey, {
  195. lng: Math.floor(device.lng / gridSize) * gridSize + gridSize / 2,
  196. lat: Math.floor(device.lat / gridSize) * gridSize + gridSize / 2,
  197. count: 0,
  198. devices: []
  199. })
  200. }
  201. const cluster = gridMap.get(gridKey)!
  202. cluster.count++
  203. if (!cluster.devices) cluster.devices = []
  204. cluster.devices.push(device)
  205. })
  206. return Array.from(gridMap.values())
  207. }
  208. const getGridSize = (zoom: number): number => {
  209. if (zoom <= 5) return 2
  210. if (zoom <= 8) return 1
  211. if (zoom < 10) return 0.03
  212. return 0.1
  213. }
  214. const showDeviceInfoWindow = (device: IotDeviceVO, point: any) => {
  215. DeptApi.getDept(device.deptId).then(res=>{
  216. dept.value = res.name
  217. const content = `
  218. <div style="display: flex;flex-direction: column;justify-content: center;border: 1px solid #ccc;">
  219. <div style="margin-top: 1px;padding: 8px">
  220. <p><strong>设备编码:</strong> ${device.deviceCode}</p>
  221. <p><strong>设备名称:</strong> ${device.deviceName}</p>
  222. <p><strong>所在部门:</strong> ${res.name}</p>
  223. <p><strong>位置:</strong> ${device.location}</p>
  224. <p><strong>状态:</strong> ${getDictLabel(DICT_TYPE.PMS_DEVICE_STATUS, device.deviceStatus)}</p>
  225. <p><strong>是否在线:</strong> ${getDictLabel(DICT_TYPE.IOT_DEVICE_STATUS, device.ifInline)}</p>
  226. <p><strong>最后在线时间:</strong> ${device.lastInlineTime}</p>
  227. </div>
  228. <div style="margin-bottom: 5px;padding: 8px">
  229. <button id="device-detail-btn" style=" background-color: #2196f3;
  230. color: white;
  231. border: none;
  232. padding: 8px 16px;
  233. border-radius: 4px;
  234. cursor: pointer;">查看</button>
  235. </div>
  236. </div>
  237. `
  238. const infoWindow = new (window as any).BMap.InfoWindow(content, {
  239. width: 350,
  240. height: 270
  241. })
  242. map.value.openInfoWindow(infoWindow, point)
  243. // 事件绑定(需延迟确保DOM加载)
  244. setTimeout(function () {
  245. document.getElementById('device-detail-btn').addEventListener('click', function () {
  246. drawerVisible.value = true
  247. deviceId.value = device.id;
  248. deviceCode.value = device.deviceCode
  249. deviceName.value = device.deviceName
  250. ifLine.value = device.ifInline
  251. lastLineTime.value = device.lastInlineTime
  252. showDrawer.value.openDrawer()
  253. })
  254. }, 200)
  255. })
  256. }
  257. const zoomIn = () => {
  258. if (map.value) {
  259. map.value.zoomIn()
  260. }
  261. }
  262. const zoomOut = () => {
  263. if (map.value) {
  264. map.value.zoomOut()
  265. }
  266. }
  267. const toggleMapType = () => {
  268. if (!map.value) return
  269. mapType.value = mapType.value === 'BMAP_NORMAL_MAP' ? 'BMAP_SATELLITE_MAP' : 'BMAP_NORMAL_MAP'
  270. map.value.setMapType((window as any)[mapType.value])
  271. }
  272. const getData = async () => {
  273. await IotDeviceApi.getMapDevice().then((res) => {
  274. devices.value = res
  275. initMap()
  276. })
  277. }
  278. onMounted(async () => {
  279. await getData()
  280. })
  281. onBeforeUnmount(() => {
  282. if (map.value) {
  283. // 清除地图上的覆盖物
  284. map.value.clearOverlays();
  285. // 移除地图容器中的内容
  286. if (mapContainer.value) {
  287. mapContainer.value.innerHTML = '';
  288. }
  289. // 解除地图的事件绑定
  290. map.value.removeEventListener('zoomend', initDeviceMarkers);
  291. }
  292. })
  293. // return {
  294. // mapContainer,
  295. // selectedDevice,
  296. // hoverDevice,
  297. // // deviceStatusMap,
  298. // zoomIn,
  299. // zoomOut,
  300. // toggleMapType
  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. right: 20px; /* 修改为right定位 */
  318. z-index: 1000;
  319. display: flex;
  320. flex-direction: column; /* 垂直排列按钮 */
  321. gap: 10px;
  322. }
  323. .map-controls button {
  324. padding: 5px 10px;
  325. background: #fff;
  326. border: 1px solid #ccc;
  327. border-radius: 3px;
  328. cursor: pointer;
  329. }
  330. </style>