map.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import apiSystem from '/@/api/system';
  2. import { ElMessageBox } from 'element-plus';
  3. let centerPoint: any
  4. // 增加map配置
  5. export function initMap(): any {
  6. return new Promise((resolve, reject) => {
  7. if (window.BMapGL) {
  8. console.log('已经初始化了...');
  9. return resolve({ BMapGL: window.BMapGL, centerPoint })
  10. }
  11. Promise.all([apiSystem.getInfoByKey('sys.map.access.key'), apiSystem.getInfoByKey('sys.map.lngAndLat')]).then(([res1, res2]) => {
  12. const ak = res1.data.configValue
  13. const centerStr = res2.data.configValue
  14. // 百度地图异步加载回调处理
  15. window.onBMapCallback = () => {
  16. console.log('百度地图脚本初始化成功...');
  17. if (centerStr) {
  18. const [lng, lat] = centerStr.split(',')
  19. centerPoint = new window.BMapGL.Point(lng.trim(), lat.trim())
  20. } else {
  21. centerPoint = '北京'
  22. }
  23. resolve({ BMapGL: window.BMapGL, centerPoint })
  24. }
  25. const script = document.createElement('script');
  26. script.type = 'text/javascript';
  27. // 加上callback才会加载成功
  28. script.src = `//api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=onBMapCallback`
  29. document.head.appendChild(script);
  30. }).catch(() => {
  31. reject(new Error('地图加载失败,请刷新重试或联系开发者'))
  32. ElMessageBox.alert('地图加载失败,请刷新重试或联系开发者', '提示', { type: 'error' })
  33. })
  34. });
  35. }