Vue異步加載高德地圖API

項目中用到了高德地圖的API以及UI組件庫,由於是直接把引入script寫在index.html中,項目打包後運行在服務器,用瀏覽器訪問加載第一次時會很是慢,主要緣由是加載高德地圖相關的js(近一分鐘),用戶體驗很是很差。javascript

因而在網上找了些資料,改爲異步加載的方式。如下是實現方案:html

1.首先定義一個asyncLoadJs.js(這裏用到了AMap和AMapUI):vue

// 異步加載高德地圖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.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:java

/* 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) {
        ...
    });

  },
}
...
相關文章
相關標籤/搜索