注:我们在写项目的时候,常常会遇到地图相关的功能,一般会使用百度地图,高德地图等SDK,但是里面的相关api,使用起来相对麻烦,这个使用可以借助Vue Baidu Map组件,实现相关功能。
Vue Baidu Map官网
1.使用npm安装插件
npm install vue-baidu-map --save
2.在项目中引入该插件
在main.js中全局引入
import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
// ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
ak: 'YOUR_APP_KEY'
})
3.在相关页面中使用
在地图中添加点标记
<baidu-map class="map" :center="{lng: 116.404, lat: 39.915}" :zoom="15">
<bm-marker :position="{lng: 116.404, lat: 39.915}" >
<bm-label content="我爱北京天安门" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{width: -35, height: 30}"/>
</bm-marker>
</baidu-map>
4.添加 1000 个随机点
<template>
<baidu-map class="map" :center="{lng: 105.000, lat: 38.000}" :zoom="4">
<bm-point-collection :points="points" shape="BMAP_POINT_SHAPE_STAR" color="red" size="BMAP_POINT_SIZE_SMALL" @click="clickHandler"></bm-point-collection>
</baidu-map>
</template>
<script>
export default {
data () {
return {
points: []
}
},
methods: {
clickHandler (e) {
alert(`单击点的坐标为:${e.point.lng}, ${e.point.lat}`);
},
addPoints () {
const points = [];
for (var i = 0; i < 1000; i++) {
const position = {lng: Math.random() * 40 + 85, lat: Math.random() * 30 + 21}
points.push(position)
}
this.points = points
}
}
}
</script>
5.点击 Marker 弹出 信息窗
<template>
<baidu-map class="map" :center="{lng: 116.404, lat: 39.915}" :zoom="15">
<bm-marker :position="markerPoint" :dragging="true" @click="infoWindowOpen">
<bm-info-window :show="show" @close="infoWindowClose" @open="infoWindowOpen">我爱北京天安门</bm-info-window>
</bm-marker>
</baidu-map>
</template>
<script>
export default {
data () {
return {
show: false
}
},
methods: {
infoWindowClose () {
this.show = false
},
infoWindowOpen () {
this.show = true
}
}
}
</script>