一、前提准备,申请密钥
二、引入百度地图的方法
1. 线上SDK引入
1、index.html:
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=你申请的AK"></script>
2、build => webpack.base.conf.js
externals: {
// 键:表示导入包语法from后面跟着的名称
// 值:表示script引入js文件时,在全局环境中的变量名称
'BMap': 'BMap'
},
3、使用
template:
<div id="map" style="height:600px; width: 100%;"></div>
script:
mounted() {
this.ready()
},
methods: {
ready: function () {
let map = new BMap.Map('map')
// 自动定位
var geolocation = new BMap.Geolocation()
geolocation.getCurrentPosition((res) => {
if (res.point) {
// 设置地图中心点
let point = new BMap.Point(res.point.lng, res.point.lat)
map.centerAndZoom(point, 18)
map.enableScrollWheelZoom(true)
map.enableDoubleClickZoom(true)
// 设置标志
let markers = new BMap.Marker(res.point)
map.addOverlay(markers)
map.panTo(res.point)
map.centerAndZoom(res.point, 18)
}
}, {enableHighAccuracy: true}) // 开启高精度定位
},
}
2. 插件vue-baidu-map
下载:
npm i --save vue-baidu-map
a、全局引入
main.js:
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: '你申请的AK'
})
b、局部引入
script:
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import { BmGeolocation, BmLocalSearch, BmMarker } from 'vue-baidu-map'
// 根据自己需求按需引入
data: function () {
return {
selfKey: '你申请AK', // 百度地图key
map: '',
center: {}, // 初始化地图中心点
zoom: 20, // 缩放等级
point: { }, // 已选坐标
keyword: '商店', // 搜索关键字
}
methods:{
mapReady({ BMap, map }) {
const that = this
// 获取自动定位方法
let geolocation = new BMap.Geolocation()
geolocation.getCurrentPosition(function(res) {
if (res.point) {
let point = new BMap.Point(res.point.lng, res.point.lat)
that.point = {
lat: res.latitude,
lng: res.longitude
}
that.center = {
lat: res.latitude,
lng: res.longitude
}
console.log('自动定位后', that.center, that.point)
}, { enableHighAccuracy: true })
},
}
components: {
BaiduMap, // 地图
BmGeolocation, // 手动定位控件
BmLocalSearch, // 检索控件
BmMarker // marker控件
},
template:
<!--百度地图-->
<baidu-map id="allMap" :center="center" :zoom="zoom" :ak="selfKey" @ready="mapReady" :scroll-wheel-zoom="true" @click="getClickInfos">
<bm-marker :position="point" animation="BMAP_ANIMATION_DROP"></bm-marker>
<bm-local-search :keyword="keyword" :autoViewport="true" :location="point"
:nearby="{center: point, radius: 100000}" :pageCapacity="5" :zomm="zoom">
</bm-local-search>
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"
@locationSuccess="locationSuccess" @locationError="locationError"></bm-geolocation>
</baidu-map>
具体属性信息,可以看文档:https://dafrok.github.io/vue-baidu-map/#/zh/context-menu/menu
但是需要翻墙哦~