地圖在項目中用得很多,最近也用了幾次,好長時間不用都記不清了,閑暇時整理了vue里使用百度地圖的2種方法,方便自己查看,也分享給大家,希望可以幫助有需要的人。
普遍的方法是:
1.index.html 中引入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰"></script>
2.新建個組件maps
注意 :不要把組件命名為map,因為html中有map標簽,會報錯
報錯:Do not use built-in or reserved HTML elements as component id:map
3.然后就可以直接再組件了寫相關代碼了
mounted(){ var map = new BMap.Map('map') var point = new BMap.Point(108.840053, 34.129522) map.centerAndZoom(point, 14) //... }另一個方法:
1.新建一個map.js
export function MP(ak) { return new Promise(function (resolve, reject) { window.onload = function () { resolve(BMap) } var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://api.map.baidu.com/api?v=2.0&ak="+ak+"&callback=init"; script.onerror = reject; document.head.appendChild(script); })}2.在需要用到的地圖的vue頁面中引入
import {MP} from './map.js'3.在vue頁面中調用
data:{ return{ ak:'1287348913029483740293'//密鑰 }},mounted(){ this.$nextTick(function(){ var _this = this; MP(_this.ak).then(BMap => { //在此調用api }) }}新聞熱點
疑難解答