詳解vue-amap引入高德JS API的原理
vue-amap是對高德地圖JS API進(jìn)行封裝的、適用于vue項目的地圖組件庫。在筆者開發(fā)的很多項目中都有用到,相比直接使用高德地圖JS API 來說,vue-amap更加好用,符合vue開發(fā)者的編程習(xí)慣。本文通過vue-amap源碼分析了vue-amap引入高德JS API的原理。
vue-amap使用
在使用vue-amap時,main.js文件往往有這樣一段代碼:
import VueAMap from 'vue-amap' Vue.use(VueAMap) VueAMap.initAMapApiLoader({ key: '82732XXXXXa5eXXXXb3face28c25',//你的高德key plugin: [ 'AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor' ], // 默認(rèn)高德 sdk 版本為 1.4.4 v: '1.4.14' })
這段代碼的關(guān)鍵就是initAMapApiLoader方法。
vue-amap入口文件
看vue-amap源碼,index.js 文件有如下代碼(部分代碼):
// 初始化接口 import {initAMapApiLoader} from './services/injected-amap-api-instance'; export { AMapManager, initAMapApiLoader, createCustomComponent };
可見initAMapApiLoader方法是被vue-amap直接向使用者暴露的,我們研究其具體實現(xiàn)。
initAMapApiLoader方法
接著我們到對應(yīng)目錄查看initAMapApiLoader的定義:
let lazyAMapApiLoaderInstance = null; import AMapAPILoader from './lazy-amap-api-loader'; import Vue from 'vue'; export const initAMapApiLoader = (config) => { if (Vue.prototype.$isServer) return; // if (lazyAMapApiLoaderInstance) throw new Error('You has already initial your lazyAMapApiLoaderInstance, just import it'); if (lazyAMapApiLoaderInstance) return; if (!lazyAMapApiLoaderInstance) lazyAMapApiLoaderInstance = new AMapAPILoader(config); lazyAMapApiLoaderInstance.load(); };
initAMapApiLoader中使用到了lazy-amap-api-loader中定義的AMapAPILoader類,new了一個實例,并且調(diào)用了load()方法。
AMapAPILoader類
下面我們就看一下AMapAPILoader類的定義:
看長長的代碼先折疊,了解大概
下面就看load()方法:
load() { // 如果window上掛載了AMap,那么直接調(diào)用loadUIAMap() if (this._window.AMap && this._window.AMap.Map) { return this.loadUIAMap(); } if (this._scriptLoadingPromise) return this._scriptLoadingPromise; // 新建一個script標(biāo)簽 const script = this._document.createElement('script'); script.type = 'text/javascript'; // 異步執(zhí)行 script.async = true; script.defer = true; script.src = this._getScriptSrc(); const UIPromise = this._config.uiVersion ? this.loadUIAMap() : null; this._scriptLoadingPromise = new Promise((resolve, reject) => { this._window['amapInitComponent'] = () => { while (this._queueEvents.length) { this._queueEvents.pop().apply(); } if (UIPromise) { UIPromise.then(() => { // initAMapUI 這里調(diào)用initAMapUI初始化 window.initAMapUI(); setTimeout(resolve); }); } else { return resolve(); } }; script.onerror = error => reject(error); }); // script標(biāo)簽插入到head中 this._document.head.appendChild(script); return this._scriptLoadingPromise; }
可以看到這段代碼做了兩件事情:(1)增加引入高德的script標(biāo)簽 ,script標(biāo)簽的src是通過 _getScriptSrc生成的 (2)引入AMapUI 組件庫 ,通過調(diào)用loadUIAMap實現(xiàn)
下面分別來看這兩個方法:
_getScriptSrc方法
_getScriptSrc() { // amap plugin prefix reg // 插件前綴 const amap_prefix_reg = /^AMap./; const config = this._config; const paramKeys = ['v', 'key', 'plugin', 'callback']; // check 'AMap.' prefix if (config.plugin && config.plugin.length > 0) { // push default types config.plugin.push('Autocomplete', 'PlaceSearch', 'PolyEditor', 'CircleEditor'); const plugins = []; // fixed plugin name compatibility. // 拼接插件 config.plugin.forEach(item => { const prefixName = (amap_prefix_reg.test(item)) ? item : 'AMap.' + item; const pureName = prefixName.replace(amap_prefix_reg, ''); plugins.push(prefixName, pureName); }); config.plugin = plugins; } const params = Object.keys(config) .filter(k => ~paramKeys.indexOf(k)) .filter(k => config[k] != null) .filter(k => { return !Array.isArray(config[k]) || (Array.isArray(config[k]) && config[k].length > 0); }) .map(k => { let v = config[k]; if (Array.isArray(v)) return { key: k, value: v.join(',')}; return {key: k, value: v}; }) .map(entry => `${entry.key}=${entry.value}`) .join('&'); return `${this._config.protocol}://${this._config.hostAndPath}?${params}`; }
這段代碼的作用就是最終要生成如下的字符串:
"https://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Scale&plugin=AMap.ToolBar&plugin=AMap.PolyEditor&plugin=AMap.Autocomplete,AMap.PlaceSearch&plugin=AMap.Geocoder"
從而可以在index.html中加入這樣的script, 這樣就把高度地圖的js-api引入了
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Scale&plugin=AMap.ToolBar&plugin=AMap.PolyEditor&plugin=AMap.Autocomplete,AMap.PlaceSearch&plugin=AMap.Geocoder"></script>
loadUIAMap方法
再來看loadUIAMap
loadUIAMap() { if (!this._config.uiVersion || window.AMapUI) return Promise.resolve(); return new Promise((resolve, reject) => { const UIScript = document.createElement('script'); const [versionMain, versionSub, versionDetail] = this._config.uiVersion.split('.'); if (versionMain === undefined || versionSub === undefined) { console.error('amap ui version is not correct, please check! version: ', this._config.uiVersion); return; } let src = `${this._config.protocol}://webapi.amap.com/ui/${versionMain}.${versionSub}/main-async.js`; if (versionDetail) src += `?v=${versionMain}.${versionSub}.${versionDetail}`; UIScript.src = src; UIScript.type = 'text/javascript'; UIScript.async = true; this._document.head.appendChild(UIScript); UIScript.onload = () => { setTimeout(resolve, 0); }; UIScript.onerror = () => reject(); }); }
這段代碼的作用是要在index.html文件中插入加載 AMapUI 的script標(biāo)簽,如下所示:
<script async src="http://webapi.amap.com/ui/1.1/main-async.js"></script>
總結(jié)
一句話總結(jié)vue-amap引入高德地圖API的原理:vue-map之所以能夠使用高德地圖的JS API 以及 AMapUI 是因為通過生成引入JS API 和 AMapUI的script標(biāo)簽,并將標(biāo)簽插入到項目的html文件。
到此這篇關(guān)于詳解vue-amap引入高德JS API的原理的文章就介紹到這了,更多相關(guān)vue-amap引入高德JS API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue項目引入translate.js國際化自動翻譯組件的方法
這篇文章主要給大家介紹了關(guān)于Vue項目引入translate.js國際化自動翻譯組件的相關(guān)資料,除了基本的文本翻譯功能之外,jstranslate還提供了一些高級功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01Vue中Table組件行內(nèi)右鍵菜單實現(xiàn)方法(基于 vue + AntDesign)
這篇文章主要介紹了Vue中Table組件行內(nèi)右鍵菜單實現(xiàn)方法,該項目是基于 vue + AntDesign的,具體實例代碼給大家介紹的非常詳細(xì) ,需要的朋友可以參考下2019-11-11vue動態(tài)菜單、動態(tài)路由加載以及刷新踩坑實戰(zhàn)
這篇文章主要給大家介紹了關(guān)于vue動態(tài)菜單、動態(tài)路由加載以及刷新踩坑的相關(guān)資料,踩的這些坑其實是挺常見的,大家可以看看,避免遇到的時候再踩到同樣的坑,需要的朋友可以參考下2021-10-10vue-cli創(chuàng)建項目ERROR?in?Conflict:?Multiple?assets?emit?dif
最近vue/cli創(chuàng)建項目后出現(xiàn)了錯誤,下面這篇文章主要給大家介紹了關(guān)于vue-cli創(chuàng)建項目ERROR?in?Conflict:?Multiple?assets?emit?different?content?to?the?same?filename?index.html問題的解決辦法,需要的朋友可以參考下2023-02-02vue-element換膚所有主題色和基礎(chǔ)色均可實現(xiàn)自主配置
這篇文章主要介紹了vue-element換膚所有主題色和基礎(chǔ)色均可實現(xiàn)自主配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04vue-awesome-swiper 基于vue實現(xiàn)h5滑動翻頁效果【推薦】
說到h5的翻頁,很定第一時間想到的是swiper。但是我當(dāng)時想到的卻是,vue里邊怎么用swiper。這篇文章主要介紹了vue-awesome-swiper - 基于vue實現(xiàn)h5滑動翻頁效果 ,需要的朋友可以參考下2018-11-11vue3 watch和watchEffect的使用以及有哪些區(qū)別
這篇文章主要介紹了vue3 watch和watchEffect的使用以及有哪些區(qū)別,幫助大家更好的理解和學(xué)習(xí)vue框架,感興趣的朋友可以了解下2021-01-01深入理解使用Vue實現(xiàn)Context-Menu的思考與總結(jié)
這篇文章主要介紹了使用Vue實現(xiàn)Context-Menu的思考與總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03