首页 / MapLibre / 使用示例
自定义控件
左上角三个按钮:复位、放大、缩小。控件只是返回一个 DOM 元素, 加上约定的类名就能沿用内置样式。
源码与运行效果
说明
控件对象只需实现两个方法:onAdd(map) 返回要插入的元素,
onRemove() 清理引用。类名写
maplibregl-ctrl maplibregl-ctrl-group,
圆角、阴影、按钮分隔线都会自动生效。
function ViewControl() { this._container = null; }
ViewControl.prototype.onAdd = function (map) {
var div = document.createElement('div');
div.className = 'maplibregl-ctrl maplibregl-ctrl-group';
var btn = document.createElement('button');
btn.type = 'button';
btn.textContent = '+';
btn.addEventListener('click', function () { map.zoomIn(); });
div.appendChild(btn);
this._container = div;
return div;
};
ViewControl.prototype.onRemove = function () {
if (this._container) this._container.remove();
this._container = null;
};
| 要点 | 说明 |
|---|---|
button.type = 'button' | 避免在表单里触发表单提交 |
| 元素放进容器 | 控件位置由 addControl 的位置参数决定 |
onRemove | 移除控件时释放 DOM 与事件 |
| 不拦截地图手势 | 控件在画布之外,无需阻止冒泡 |
复位按钮用 easeTo 而不是 jumpTo,
视角变化有过渡,用户能看清从哪里回到哪里。
控件内不要放需要频繁更新的内容。每次视角变化都改写控件 DOM, 会让控件在拖拽时抖动;需要显示坐标时,把信息放到地图外的信息栏。