最近項目中有使用到高德地圖,搜了下發現餓了麼的 vue-amap 比較知名。不過實際安裝使用中發現仍是有不少問題的,並不友好。不但要學習 amap 的文檔,也還要學習原生高德API文檔,還不如直接使用原生來的方便。vue
而這篇教程的目的就是,怎麼在vue中使用高德地圖APIjquery
DEMO:vue-gaode.rxshc.com
GitHub: github.com/zuley/vue-g…git
載入的方式相似於 jquery 的腳本加載,我這裏也是使用了別人封裝好的一個加載方法,各位直接使用或者本身改github
async created () { // 已載入高德地圖API,則直接初始化地圖 if (window.AMap && window.AMapUI) { this.initMap() // 未載入高德地圖API,則先載入API再初始化 } else { await remoteLoad(`http://webapi.amap.com/maps?v=1.3&key=${MapKey}`) await remoteLoad('http://webapi.amap.com/ui/1.0/main.js') this.initMap() } }複製代碼
在 methods 中建立一個 initMap 的方法供載入地圖API以後調用。這裏就能夠使用任意高德APIweb
initMap () { // 加載PositionPicker,loadUI的路徑參數爲模塊名中 'ui/' 以後的部分 let AMapUI = this.AMapUI = window.AMapUI let AMap = this.AMap = window.AMap AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => { let mapConfig = { zoom: 16, cityName: MapCityName } if (this.lat && this.lng) { mapConfig.center = [this.lng, this.lat] } let map = new AMap.Map('js-container', mapConfig) // 加載地圖搜索插件 AMap.service('AMap.PlaceSearch', () => { this.placeSearch = new AMap.PlaceSearch({ pageSize: 5, pageIndex: 1, citylimit: true, city: MapCityName, map: map, panel: 'js-result' }) }) // 啓用工具條 AMap.plugin(['AMap.ToolBar'], function () { map.addControl(new AMap.ToolBar({ position: 'RB' })) }) // 建立地圖拖拽 let positionPicker = new PositionPicker({ mode: 'dragMap', // 設定爲拖拽地圖模式,可選'dragMap'、'dragMarker',默認爲'dragMap' map: map // 依賴地圖對象 }) // 拖拽完成發送自定義 drag 事件 positionPicker.on('success', positionResult => { // 過濾掉初始化地圖後的第一次默認拖放 if (!this.dragStatus) { this.dragStatus = true } else { this.$emit('drag', positionResult) } }) // 啓動拖放 positionPicker.start() }) }複製代碼
<mapDrag @drag="dragMap" lat="22.574405" lng="114.095388"></mapDrag>複製代碼