Vue异步加载高德地图API
项目中用到了高德地图的API以及UI组件库,因为是直接把引入script写在index.html中,项目打包后运行在服务器,用浏览器访问加载第一次时会非常慢,主要原因是加载高德地图相关的js(近一分钟),用户体验非常不好。
于是在网上找了些资料,改成异步加载的方式。以下是实现方案:
1.首先定义一个asyncLoadJs.js(这里用到了AMap和AMapUI):
// 异步加载高德地图API export function loadMP() { const mp = new Promise(function (resolve, reject) { let hasLoaded1 = document.getElementById("amap"); if(hasLoaded1) { // 只加载一次 return } window.init = function () { resolve(AMap) }; let script = document.createElement("script"); script.type = "text/javascript";
script.async = true; script.src = "//webapi.amap.com/maps?v=1.4.6&key=[申请的key]&plugin=AMap.Driving,AMap.Geocoder,AMap.ToolBar&callback=init"; script.id = "amap"; script.onerror = reject; document.head.appendChild(script); }); const mpUI = new Promise(function (resolve,reject) { let hasLoaded2 = document.getElementById("amapUI"); if(hasLoaded2) { // 只加载一次 return } let script2 = document.createElement("script"); script2.type = "text/javascript"; script2.src = "//webapi.amap.com/ui/1.0/main.js"; script2.id = 'amapUI'; script2.onerror = reject; script2.onload = function(su){ resolve(AMapUI) }; document.head.appendChild(script2); }); return Promise.all([mp,mpUI]) .then(function (result) { return result }).catch(e=>{ console.log(e);}) }
2.然后在组件中引入并调用API:
/* posLocation.vue组件 */ import {loadMP} from '../../assets/js/asyncLoadJs' ... created() { // 加载高德地图API loadMP().then(AMap => { initAMapUI(); //这里调用initAMapUI初始化 }); }, methods: { // 地址模糊搜索 placeAutoInput() { AMap.plugin('AMap.Autocomplete', () => { // 实例化Autocomplete let autoOptions = { city: '全国' }; let autoComplete = new AMap.Autocomplete(autoOptions); let keywords = this.value autoComplete.search(keywords, (status, result) => { if (status === 'no_data') { this.isError = true this.lng = '' this.lat = '' this.$emit('updateMs', this.name, {name: '', lng: '', lat: ''}) } else { // 搜索成功时,result即是对应的匹配数据 if (result.info === 'OK') { this.flag = true this.isError = false this.result = result.tips; this.$nextTick(function () { let resultList = document.getElementsByClassName('result-list')[0] resultList.style.width = this.w }) } } }) }) }, // 地图选址 pickAddress(lon, lat) { AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) { ... }); }, } ...