Util
Quick answer
L.Util collects the shared helpers Leaflet uses throughout: option merging, prototype extension, ID stamping, URL templating, number wrapping, formatting and frame throttling. Custom layers and controls lean on it constantly. The functions here cover inheritance, option handling, URL building and animation scheduling.
L.Util. method (...) → 视函数而定
Key points
- stamp assigns a unique id cached in _leaflet_id and returns the same value on later calls.
- setOptions merges user options into the instance without destroying inherited defaults.
- template throws on missing keys rather than leaving unresolved placeholders.
Example
/* 继承并合并默认选项,自定义图层常用写法 */
var HeatLayer = L.Layer.extend({
options: { radius: 20, blur: 15, max: 1 },
initialize: function (points, options) {
L.Util.setOptions(this, options);
this._points = points || [];
}
});
/* 拼请求串:不要手写 & 和 ? */
L.Util.getParamString({ layers: 'a:b', format: 'image/png' }, '/wms?');
/* → /wms?layers=a%3Ab&format=image%2Fpng */
L.Util.template('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { z: 12, x: 3372, y: 1552 });
/* 经度归一到 -180~180 */
L.Util.wrapNum(190, [-180, 180]); /* → -170 */
L.Util.formatNum(116.391263, 4); /* → 116.3913,默认保留 6 位 */
var icon = L.divIcon({ className: '', html: '<i></i>', iconSize: [10, 10] });
console.log(L.Util.stamp(icon)); /* 唯一 id,重复调用不变 */
Notes
- formatNum rounds to six decimals by default; pass false to preserve full coordinate precision.
- requestAnimFrame should be paired with cancelAnimFrame whenever an animation stops.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Util. https://www.jingweizhi.com/en/leaflet/api/util.html (accessed 2026-11-03).