1.新建loadBMap的js文件,
export default function loadBMap(ak) { return new Promise(function(resolve, reject) { if (typeof window.BMap !== 'undefined') { resolve(window.BMap) return true } window.onBMapCallback = function() { resolve(window.BMap) } let script = document.createElement('script') script.type = 'text/javascript' script.src = 'http://api.map.baidu.com/api?v=3.0&ak=' + ak + '&callback=onBMapCallback' script.onerror = reject document.head.appendChild(script) }) } 需要的页面导入这个方法 import loadBMap from '../../api/loadBMap.js'3.在mounted中使用(注意异步,等待加载完成使用)
async mounted() { console.log('参赛id',this.activityId) await loadBMap('你的地图ak') await this.getLoad() //调用方法 },4.在方法中使用
getLoad(){ var that = this; var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(res){ if(res) { console.log('获取地址') that.province = res.address.province that.myaddress = res.address.city }else { that.$message({ message:'请检查您的浏览器是否禁用了获取位置', type:'warning' }) console.log('默认地址') that.province = '省' that.myaddress = '市' } },{enableHighAccuracy: true}) //enableHighAccuracy:是否要求浏览器获取最佳效果,默认为false },Marco-灰 文章,地址 https://www.cnblogs.com/Marco-hui/p/12155995.html