安装百度地图
npm install --save vue-baidu-map
全局引入
在main.js中全局引入
import BaiduMap from 'vue-baidu-map'
页面
<form class="search-con" action="/">
<van-search v-model="addressKeyword" placeholder="请输入搜索关键词" @search="onSearch" />
</form>
<baidu-map class="map" @ready="handler" :center="center" :zoom="zoom">
<!--定位-->
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
</baidu-map>
<script>
data () {
return {
addressKeyword:"",
center: { lng: 118.811545, lat: 37.871721 },
zoom: 16,
// 需要标记的点的数组
centerList: []
}
},
created() {
// 从接口获取需要标记的位置
this.getCompany()
},
methods: {
async getCompany() {
try {
let res = await this.$api.home.getCompanyLocationList()
let arr = []
res.data.forEach((item) => {
arr.push(item)
})
this.centerList = arr
} catch (error) {
this.$toast(error.msg)
}
},
// 搜索
onSearch(val) {
let _this = this
let arr = []
this.centerList.forEach((item) => {
// 如果搜索值不为空,进行地图中心点改变,否则不变
if (val.length !== 0) {
// 判断搜索的是否为检索范围内
if (item.name === val) {
arr.push(1)
_this.center.lng = item.lng
_this.center.lat = item.lat
} else {
arr.push(2)
}
} else {
arr.push(1)
this.center = { lng: 118.811545, lat: 37.871721 }
}
})
if (arr.indexOf(1) === -1) {
_this.$toast('请输入有效值')
}
},
// 地图初始化
handler ({ BMap, map }) {
// 将标记点 渲染
this.centerList.forEach((item) => {
this.getPoints({ BMap, map }, item)
})
map.enableScrollWheelZoom(true)
},
getPoints({ BMap, map }, position) {
var that = this
var point = new BMap.Point(position.lng, position.lat)
var marker = new BMap.Marker(point)
map.addOverlay(marker)
// 设置提示框的宽高等
var opts = {
width: 130,
height: 60,
enableMessage: true
}
// 设置提示框的内容
var infoWindow = new BMap.InfoWindow(position.name, opts)
marker.addEventListener('click', function() {
map.openInfoWindow(infoWindow, point)
})
},
// 关闭信息窗口 @close 自带的方法
infoWindowClose (marker) {
this.centerList[marker].showFlag = false
},
// 打开信息框
infoWindowOpen (marker) {
this.centerList[marker].showFlag = true
}
}
</script>