瀏覽代碼

feat: 增加加载地图的脚本,在需要的时候调用,会同时返回地图中心点

yanglzh 1 年之前
父節點
當前提交
35d1a4300f
共有 4 個文件被更改,包括 49 次插入96 次删除
  1. 0 7
      src/App.vue
  2. 37 78
      src/utils/map.ts
  3. 0 1
      src/views/iot/device/instance/component/edit.vue
  4. 12 10
      src/views/iot/device/instance/component/map.vue

+ 0 - 7
src/App.vue

@@ -29,13 +29,6 @@ export default defineComponent({
 			localStorage.setItem('sysinfo', JSON.stringify(res));
 			sessionStorage.setItem('btnNoAuth', res.sysButtonSwitch ? '' : '1');
 			sessionStorage.setItem('colNoAuth', res.sysColumnSwitch ? '' : '1');
-			// 增加map配置
-			const script = document.createElement('script');
-			script.type = 'text/javascript';
-			script.src = `//api.map.baidu.com/api?v=1.0&type=webgl&ak=${res.mapAccessKey}&callback=onBMapCallback`
-			document.head.appendChild(script);
-			// 加上callback才会加载成功
-			window.onBMapCallback = () => {}
 		});
 	},
 	setup() {

+ 37 - 78
src/utils/map.ts

@@ -1,81 +1,40 @@
-
-let BMapGL = (window as any).BMapGL;
-
-export function setMarker(markers: any[], map: any) {
-  const points: any = []
-  markers.forEach((item) => {
-    const { lat, lnt: lng } = item;
-    const point = new BMapGL.Point(lng, lat);
-    point.data = item
-    points.push(point)
-
-    const marker = new BMapGL.Marker(point);
-
-    map.addOverlay(marker);
-
-    marker.addEventListener("click", function () {
-      const infoWindow = new BMapGL.InfoWindow(
-        `
-      <div class="map-hover-box">
-        <div class="map-hover-title">换热站名称:${item.name}</div>
-        <div class="map-hover-row-item">
-          <div class="map-hover-label">换热站编号:</div>
-          <div class="map-hover-value">${item.code}</div>
-        </div>
-        <div class="map-hover-row-item">
-          <div class="map-hover-label">位置:</div>
-          <div class="map-hover-value">${item.position}</div>
-        </div>
-      </div>
-    `,
-        {
-          width: 200, // 信息窗口宽度
-          height: 100, // 信息窗口高度
-          title: item.stationName,
-        }
-      );
-      map.openInfoWindow(infoWindow, point); //开启信息窗口
-    });
-  });
-  return points
-}
-
-export function setLine(lines: any[], map: any) {
-  lines.forEach((item) => {
-    const polyline = new BMapGL.Polyline(item.loopViaPointInfo.map((item: any) => {
-      return new BMapGL.Point(item.lnt, item.lat)
-    }), { strokeColor: "blue", strokeWeight: 10, strokeOpacity: 0.5 });   //创建折线
-
-    map.addOverlay(polyline);
-
-    polyline.addEventListener("click", function (e: any) {
-      const infoWindow = new BMapGL.InfoWindow(
-        `
-      <div class="map-hover-box">
-        <div class="map-hover-title">环路名称:${item.name}</div>
-        <div class="map-hover-row-item">
-          <div class="map-hover-label">环路编号:</div>
-          <div class="map-hover-value">${item.code}</div>
-        </div>
-        <div class="map-hover-row-item">
-          <div class="map-hover-label">所属换热站:</div>
-          <div class="map-hover-value">${item.stationInfo.name}</div>
-        </div>
-        <div class="map-hover-row-item">
-          <div class="map-hover-btn" onclick="window.mapToDetail('${item.code}')">去详情页</div>
-        </div>
-      </div>
-    `,
-        {
-          width: 200, // 信息窗口宽度
-          height: 100, // 信息窗口高度
-          title: item.name,
+import apiSystem from '/@/api/system';
+import { ElMessageBox } from 'element-plus';
+
+let centerPoint: any
+
+// 增加map配置
+export function initMap(): any {
+  return new Promise((resolve, reject) => {
+    if (window.BMapGL) {
+      console.log('已经初始化了...');
+      return resolve({ BMapGL: window.BMapGL, centerPoint })
+    }
+
+    Promise.all([apiSystem.getInfoByKey({ ConfigKey: 'sys.map.access.key' }), apiSystem.getInfoByKey({ ConfigKey: 'sys.map.lngAndLat' })]).then(([res1, res2]) => {
+      const ak = res1.data.configValue
+      const centerStr = res2.data.configValue
+
+      // 百度地图异步加载回调处理
+      window.onBMapCallback = () => {
+        console.log('百度地图脚本初始化成功...');
+        if (centerStr) {
+          const [lng, lat] = centerStr.split(',')
+          centerPoint = new window.BMapGL.Point(lng.trim(), lat.trim())
+        } else {
+          centerPoint = '北京'
         }
-      );
-      // map.closeInfoWindow()
-      setTimeout(() => {
-        map.openInfoWindow(infoWindow, e.latLng); //开启信息窗口
-      }, 100)
-    });
+        resolve({ BMapGL: window.BMapGL, centerPoint })
+      }
+
+      const script = document.createElement('script');
+      script.type = 'text/javascript';
+      // 加上callback才会加载成功
+      script.src = `//api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=onBMapCallback`
+      document.head.appendChild(script);
+    }).catch(() => {
+      reject(new Error('地图加载失败,请刷新重试或联系开发者'))
+      ElMessageBox.alert('地图加载失败,请刷新重试或联系开发者', '提示', { type: 'error' })
+    })
   });
 }

+ 0 - 1
src/views/iot/device/instance/component/edit.vue

@@ -93,7 +93,6 @@ import tagVue from './tag.vue';
 import Map from './map.vue';
 import UploadVue from '/@/components/upload/index.vue';
 import certApi from '/@/api/certificateManagement';
-import { json } from 'stream/consumers';
 
 interface RuleFormState {
   id: number;

+ 12 - 10
src/views/iot/device/instance/component/map.vue

@@ -39,7 +39,9 @@
 <script lang="ts" setup>
 import { defineEmits, defineExpose, nextTick, ref } from 'vue';
 import { Search } from '@element-plus/icons-vue';
+import { initMap } from '/@/utils/map';
 
+initMap()
 
 const mapContainer = ref<HTMLElement | null>(null);
 const address = ref('');
@@ -50,13 +52,19 @@ const oldAddress = ref('');
 const searchKeyword = ref(''); // 搜索输入框的值
 
 const isShowDialog = ref(false);
-const marker = ref<BMapGL.Marker | null>(null);
-let map: BMapGL.Map | null = null;
+const marker = ref<any>(null);
+let BMapGL: any = null;
+let map: any = null;
 
 const openDialog = (row: any) => {
   oldAddress.value = '';
   isShowDialog.value = true;
-  nextTick(() => {
+  nextTick(async () => {
+
+    const { BMapGL: theBMapGL, centerPoint } = await initMap()
+
+    BMapGL = theBMapGL
+    
     map = new BMapGL.Map(mapContainer.value!);
 
     // 如果添加了经纬度则进入地图后还原上次地址
@@ -65,13 +73,7 @@ const openDialog = (row: any) => {
       lat.value = row.lat;
       searchByCoordinate();
     } else {
-      const mapLngAndLat = JSON.parse(localStorage.sysinfo || '{"mapLngAndLat": null}').mapLngAndLat
-      if (mapLngAndLat) {
-        const [lng, lat] = mapLngAndLat.split(',')
-        map.centerAndZoom(new BMapGL.Point(lng.trim(), lat.trim()), 10)
-      } else {
-        map.centerAndZoom('北京', 10);
-      }
+      map.centerAndZoom(centerPoint, 10);
     }
     map.enableScrollWheelZoom(true);