Skip to content

百度地图(BMap)和BMap Draw地图选取点线面的vue2实现

  • BMap官方文档为原生js,BMap Draw官方文档为react实现
  • 这是使用vue2实现功能记录

BMap初始化

初始化BMap,初始化完成后对BMap Draw初始化

js
BMPGL (ak) {
    return new Promise(function (resolve, reject) {
        window.init = function () {
            // eslint-disable-next-line
            resolve(BMapGL)
        }
        const script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init`
        script.onerror = reject
        document.head.appendChild(script)
    })
},
// 初始化地图
async initMap () {
    try {
    	// BMap Key
        let ak = '***'
        this.BMapGL = await this.BMPGL(ak)
        this.centerPoint = new this.BMapGL.Point(points)// 地图中心点
        this.map = new this.BMapGL.Map('container')// 挂载的div元素
        this.map.centerAndZoom(this.centerPoint, 11)
        this.map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        this.map.setTilt(60) // 设置地图的倾斜角度
        this.map.setMapStyleV2({ styleJson: styleJson }) // 修改地图样式
        // 初始化绘制方法, 解构出需要的类
        // DrawScene是绘制的基类,后续都是继承这个基类,必须拿到这个
        const { DrawScene, MarkerDraw, PolylineDraw } = await import('bmap-draw')
        //在使用其他绘制功能前,需要先实例一个 DrawScene 类。
        this.scene = new DrawScene(this.map)
        this.MarkerDraw = MarkerDraw
        this.PolylineDraw = PolylineDraw
    } catch (e) {
        console.error('地图初始化失败:', e)
    }
}

开始绘制

js
// 绘制线,实例PolylineDraw
handleAddLine (bool) {
    // 绘制需要使用如下代码创建实例,isOpen状态是是否启用绘制
    // 先初始化,isOpen默认写false
    this.instance = new this.PolylineDraw(this.scene, {
        isOpen: false,
        enableSnap: true, // 开启吸附绘制
        matchOverlay: {
            // 自定义吸附点样式
            type: 'Marker',
            icon: new this.BMapGL.Icon(
                'http://maponline0.bdimg.com/sty/map_icons2x/MapRes/shenghui_1.png',
                new this.BMapGL.Size(10, 10),
                { offset: new this.BMapGL.Size(5, 5) }
            )
        }
    })
    // 根据状态判断是需要开始绘制还是关闭,调用open/close方法即可
    if (bool) {
        this.instance.open()
    } else {
        this.instance.close()
    }
    // 监听画线完成事件,在这拿到绘制的经纬度
    // 画线完成监听
    this.instance.addEventListener('operate-ok', e => {
        console.log('operate-ok:经纬度:', e.target.overlay.points)
        // 关闭绘制
        this.instance.close()
    })
}

清除所有的绘制

js
this.scene.clearData()

绘制各种初始的类名

配置项浏览官方文档:https://lbsyun.baidu.com/bmap-draw/guide/drawclass/markerdraw

js
// 绘制点
MarkerDraw
// 绘制线
PolylineDraw
// 绘制多边形
PolygonDraw
// 绘制矩形
RectDraw
// 绘制圆形
CircleDraw
// 测距
DistanceMeasure

监听事件名称

监听完成事件,在这拿到绘制成功的数据

js
// 测距结束事件监听
measure-length-end
// 绘制完成监听
operate-ok
// 绘制取消监听
operate-cancel

测距功能实现

js
// 实例DistanceMeasure
this.instance = new this.DistanceMeasure(this.scene)
// 监听measure-length-end获取测距结束的数据
this.instance.addEventListener('measure-length-end', (e) => {
    console.log('measure-end', e)
})