1.脚手架使用时会提示undefined,可以在react组件外面定义一个变量
const BMapGL = window.BMapGL
const map = new BMapGL.Map('container')
2.城市反向解析,并调整视野,获取比例尺和缩放空间
// 获取当前定位城市
const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
// 初始化地图实例
const map = new BMapGL.Map('container')
// 作用:能够在其他方法中通过 this 来获取到地图对象
this.map = map
// 创建地址解析器实例
const myGeo = new BMapGL.Geocoder()
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint(
label,
async (point) => {
if (point) {
// 初始化地图
map.centerAndZoom(point, 11)
// 添加常用控件,比例尺和缩放
map.addControl(new BMapGL.NavigationControl())
map.addControl(new BMapGL.ScaleControl())
// 调用 renderOverlays 方法
// this.renderOverlays(value)
}
},
label
)
3.调整控件位置,大小
map.addControl(new BMapGL.NavigationControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP],anchor:BMAP_ANCHOR_TOP_RIGHT,type: BMAP_NAVIGATION_CONTROL_SMALL}))
// eslint-disable-next-line no-undef
map.addControl(new BMapGL.ScaleControl({anchor: BMAP_ANCHOR_TOP_RIGHT}))
4.创建文本覆盖物,label.setContent书写html,设置样式label.setStyle(labelStyle)
// 创建区、镇覆盖物
createCircle(point, name, count, id, zoom) {
// 创建覆盖物
const label = new BMapGL.Label('', {
position: point,
offset: new BMapGL.Size(-35, -35),
})
// 给 label 对象添加一个唯一标识
label.id = id
// 设置房源覆盖物内容
label.setContent(`
<div class="${styles.bubble}">
<p class="${styles.name}">${name}</p>
<p>${count}套</p>
</div>
`)
// 设置样式
label.setStyle(labelStyle)
// 添加单击事件
label.addEventListener('click', () => {
// 调用 renderOverlays 方法,获取该区域下的房源数据
this.renderOverlays(id)
// 放大地图,以当前点击的覆盖物为中心放大地图
this.map.centerAndZoom(point, zoom)
// 解决清除覆盖物时,百度地图API的JS文件自身报错的问题
setTimeout(() => {
// 清除当前覆盖物信息
this.map.clearOverlays()
}, 0)
})
// 添加覆盖物到地图中
this.map.addOverlay(label)
}