前言
在我们使用百度地图的经常会使用到各种控件,比如百度地图内置的比例尺,定位,缩放。但是有时鉴于我们的需求,会用到其他的控件,但又不存在与其内置组件中,故需要我们设置自定义控件。
1.主要思路
定义一个Control类,使其继承于BMapGL.Control
class MyControl extends BMapGL.Control{
constructor(anchor,offset,name,func) {
super()
this.defaultAnchor = anchor
this.defaultOffset = offset
this.name = name
this.func = func
}
// 方法名字必须定义为initialize,没看源码。这个应该是百度地图中关于控件设置的特定方法名称
initialize(map){
let div = document.createElement('div');
//添加文字说明
div.appendChild(document.createTextNode(this.name));
// 设置样式
div.style.cursor = "pointer";
div.style.padding = "7px 10px";
div.style.boxShadow = "0 2px 6px 0 rgba(27, 142, 236, 0.5)";
div.style.borderRadius = "5px";
div.style.backgroundColor = "white";
div.style.position = "relative"
// 绑定事件,点击一次放大两级
div.onclick = this.func
// 添加DOM元素到地图中
map.getContainer().appendChild(div);
// 将DOM元素返回
return div;
}
}
之后直接在创建对象使用
let anchor = BMAP_ANCHOR_TOP_RIGHT;
let offset = new BMapGL.Size(20, 20)
let clearControl = new MyControl(anchor,offset,"重置地图",clearMap)
map.addControl(clearControl);
这里的clearMap是我们自己操作地图的方法,这个方法讲绑定到自定义控件上
参考:
https://lbsyun.baidu.com/jsdemo.htm#cAddCustomControl
不足之后请大家评论补充