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

  },
}
...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM