Control
Quick answer
L.Control is the base class behind zoom buttons, attribution text, layer switchers and any custom panel placed on the map. Extend it with options.position, onAdd and onRemove to build panels that follow the same mount and removal lifecycle as built-in controls.
L.Control.extend( { options, onAdd, onRemove } ) → Control 子类
Key points
- onAdd must return a DOM node; returning null leaves the control unusable.
- Wrap interactive containers with L.DomEvent.disableClickPropagation so clicks skip the map.
- setPosition removes and re-adds the control, firing onRemove and then onAdd.
Example
var HomeControl = L.Control.extend({
options: { position: 'topleft' },
onAdd: function (map) {
var box = L.DomUtil.create('div', 'home-control');
box.innerHTML = '<button type="button">回到初始视图</button>';
L.DomEvent.disableClickPropagation(box);
L.DomEvent.disableScrollPropagation(box);
box.querySelector('button').addEventListener('click', function () {
map.flyTo([39.907359, 116.391263], 12);
});
return box;
}
});
var home = new HomeControl({ position: 'topleft' }).addTo(map);
home.setPosition('topright');
Notes
- Skipping disableScrollPropagation lets wheel events over the control zoom the map underneath.
- Controls that bind map events in onAdd must unbind them in onRemove to avoid dangling handlers.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Control. https://www.jingweizhi.com/en/leaflet/api/control.html (accessed 2026-11-03).