一、安裝及引入
1、在vue中安裝依賴
$ npm install vue-baidu-map --save
在vue腳手架main.js中引入
import BaiduMap from 'vue-baidu-map' Vue.use(BaiduMap, { ak: 'Yo8oGhNGslHc4B8Qs8EWI4BvU3Qt4Zla' });
2、cdn
<script src="https://unpkg.com/vue-baidu-map"></script>
3、申請ak及具體過程請參照官網
(1)官網:http://lbsyun.baidu.com/index.php?title=jspopularGL
(2)vue開發文檔:https://dafrok.github.io/vue-baidu-map/#/
二、個別案例介紹
1、在地圖上不同地點標出不同顏色的點
<!--center和zoom屬性必須要有,否則地圖不渲染。--> <!--@ready:地圖 API 加載完畢后執行的代碼,不要在 vue 自身的生命周期中調用 BMap 類--> <!--ak:百度地圖密鑰,沒有會報錯--> <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler" :scroll-wheel-zoom="true"> <!-- 這里使用<template>循環只是為了減少代碼結構,使用<div>循環效果一樣的,看個人習慣--> <template v-for="(item,index) in points"> <bm-marker :key="index" :position="item.site" :dragging="false" :icon="{url: item.url, size: {width: 30, height: 40}}" @click="infoWindowOpen(item)"></bm-marker> </template> <bm-info-window @close="infoWindowClose2" @open="infoWindowOpen2" :position="site" :show="show"> {{content}} </bm-info-window> </baidu-map>
handler ({BMap, map}) { console.log(BMap, map) // 地圖中心點 this.center.lng = 116.315064 this.center.lat = 40.043554 this.zoom = 15 this.addPoints() }, addPoints () { // 隨便給的幾個點 this.points = [ { site:{ lng: '116.315064', lat: ' 40.043554' }, value: '嘉華大廈', id: 3, url: '' }, { site:{ lng: '116.306754', lat: '40.047459' }, value: '八維研修學院', id: 2, url: '' }, { site:{ lng: '116.32508', lat: '40.030197' }, value: '北京體育大學', id: 1, url: '' }, { site:{ lng: '116.302227', lat: '40.033954' }, value: '興天海園', id: 4, url: '' } ] // 根據id區別圖標,相對路徑要使用require() for(let item of this.points){ let path = '' switch (item.id) { case 1: path = require('../../assets/redIcon.gif') break; case 2: path = require('../../assets/yellowIcon.png') break; case 3: path = require('../../assets/blueIcon.png') break; case 4: path = require('../../assets/blackIcon.png') break; } item.url = path } }
2、根據經緯度返回該點的信息及城市碼citycode(逆地理編碼服務)
$.ajax({ url:'http://api.map.baidu.com/reverse_geocoding/v3/?ak=你的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194', dataType: 'jsonp', callback: 'BMap._rd._cbk43398', success: function(res) { console.log(res); }, error:function(res) { console.log(res); } });
接口功能介紹
逆地理編碼
http://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194 //GET請求
注意:當前為V3.0版本接口文檔,V2.0及以前版本自2019.6.18起新用戶無法使用。老用戶仍可繼續使用V2.0及以前版本請求實現逆地理編碼服務,為保障用戶體驗,建議您盡快遷移到V3.0版本。
如在使用V3.0 時“鑒權失敗“ 可在”控制台“->“查看應用”->“設置” 確認是否已獲得“逆地理編碼服務”權限。
如有其他問題,可通過“反饋與幫助”反饋給我們。