<template>
<div>
<baidu-map
@ready="initMap"
:zoom="12"
center="北京市丰台区"
style="height: 100vh;width: 100%"
:scroll-wheel-zoom="true">
</baidu-map>
</div>
</template>
<script>
export default {
methods: {
initMap({BMap, map}) {
this.map = map
let city = "北京市"
let region = "丰台区"
this.drawPolygon(region)
this.addRegionLabel(city,region)
},
// 绘制行政区划轮廓
drawPolygon(regionName) {
let that = this
let bdary = new BMap.Boundary();
bdary.get(regionName, function (rs) {
//轮廓的总数 —— 有的区由多个封闭区域组成
let count = rs.boundaries.length;
if (!count) {
console.log('未能获取到当前输入的行政区域');
return;
}
for (let i = 0; i < count; i++) {
//创建多边形覆盖物
let ply = new BMap.Polygon(rs.boundaries[i],
{
strokeWeight: 2,
strokeColor: "red",
fillOpacity: 0.5,
strokeStyle: "dashed",
}
);
// 给覆盖物添加点击事件
ply.addEventListener('click', function () {
alert("我是:" + regionName)
// 改变自己的透明度
// this.setFillOpacity(0.6)
});
//添加覆盖物
that.map.addOverlay(ply);
}
})
},
// 获取行政区划的坐标
getReigonLocation(city, region) {
return this.$http.get("/baiduMapAPI/place/v2/search", {
params: {
query: region,
region: city,
output: 'json',
city_limit: true,
ak: this.GLOBAL.baiduMapAK
}
}).then(res => {
let location = res.data.results[0].location
return Promise.resolve(location);
})
},
// 添加行政区划文本标注
async addRegionLabel(city, region) {
let point = await this.getReigonLocation(city, region)
// 创建文本标注对象
let label = new BMap.Label(region,
{
position: new BMap.Point(point.lng, point.lat),
offset: new BMap.Size(0, 0) //设置文本偏移量
}
);
label.setStyle({
color: "red",
fontSize: "16px",
fontFamily: "微软雅黑",
background: "none",
border: "none",
fontWeight: 'bold'
});
// 在地图上添加文本标注对象
this.map.addOverlay(label);
},
},
data() {
return {
map: null
}
}
}
</script>
<style scoped>
/* 隐藏百度图片Logo */
/deep/ .BMap_cpyCtrl {
display: none;
}
/* 隐藏文字信息 */
/deep/ .anchorBL {
display: none;
}
</style>