Vue專案接入百度地圖,此次學習用的是原生API,
一、引入百度地圖JS
在 index.html 內添加script標簽,引入百度地圖api地址:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=百度地圖秘鑰(ak)"></script>

二、API呼叫,地圖初始化
1、容器節點準備
完成百度地圖引入以后,就可以進行地圖api呼叫了,但,在地圖初始化api呼叫之前,還需要先準備一個DOM標簽(一般為div)作為容器,用于顯示地圖,
<el-col style="width: calc(100% - 320px);padding-left: 20px"> <div id="allmap" ref="allmap" :style="{ height: mapHandler.height + 'px' }"></div> </el-col>
注:地圖顯示和其他內容顯示不一樣,其他節點我們給DOM標簽或父標簽設定了寬(100%)高(100%),標簽會根據內容的寬高自行撐開節點顯示,但地圖不會,需要我們明確地設定寬高值(不能用比較寬泛的100%)
2、初始化地圖
容器節點準備好以后,就可以進行地圖的初始化了,(由于百度地圖基類BMap在專案啟動時,已被掛載到window物件上,故可以直接呼叫)
const BMap = window.BMap;// 用常量存放BMap基類,便于其他地方呼叫,不用每次都去window物件上獲取,也更易于理解
mounted() { this.initMap(); },
initMap() { this.mapInstance = new BMap.Map(this.$refs.allmap); // 初始化地圖,創建Map實體,用全域變數存放Map實體,便于子組件或其他方法呼叫Map實體 this.getCurrentPosition(); this.mapInstance.addControl(new BMap.NavigationControl()); // 添加地圖縮放比例組件 this.mapInstance.addControl(new BMap.ScaleControl()); // 添加比例尺組件 this.mapInstance.addControl(new BMap.OverviewMapControl()); // 添加全域查看組件(個人感覺沒啥用) this.mapInstance.addControl(new BMap.MapTypeControl()); // 添加地圖型別控制(地圖、衛星、三維) }, // 獲取本地位置資訊(經緯度坐標、城市名稱等),進行地圖初始化 getCurrentPosition() { let that = this; let geolocation = new BMap.Geolocation(); // 獲取本地位置經緯度坐標 geolocation.getCurrentPosition( function(r) { that.mapInstance.centerAndZoom( new BMap.Point(r.longitude, r.latitude), 13 ); // 地圖初始化,設定中心點坐標(本地)和地圖縮放比例,Point也可以設定為一個固定值,如天安門(): that.mapInstance.setCurrentCity(r.address.city); // 設定地圖顯示的城市(當前位置城市) 此項必須設定 that.mapInstance.enableScrollWheelZoom(true); // 開啟滑鼠滾輪縮放 that.loadingStatus = true; }, { enableHighAccuracy: true } ); },

3、地圖功能開發
在地圖初始化完成以后,就可以根據實際需要進行功能開發了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/243196.html
標籤:JavaScript
上一篇:JS撰寫的科學計算器
下一篇:JavaScript(二)
