首页 / Leaflet / API 文档
GridLayer
先看结论
按网格切分并加载内容的图层基类,TileLayer 与 WMS 都从它派生。
L.gridLayer(options) → GridLayer
参数
| 选项 | 默认值 | 说明 |
|---|---|---|
tileSize | 256 | 单块瓦片边长,像素;可传 L.point(w, h) |
minZoom | 0 | 图层可见的最小缩放级别 |
maxZoom | undefined | 图层可见的最大缩放级别,不设则跟随地图 |
minNativeZoom | undefined | 可请求的最低原生级别,更低时拉伸高层瓦片 |
maxNativeZoom | undefined | 可请求的最高原生级别,更高时放大低层瓦片 |
noWrap | false | 禁止经度方向循环复制 |
bounds | null | 只在指定范围内加载瓦片,超出部分不请求 |
pane | 'tilePane' | 所在 pane,层级 200 |
opacity | 1 | 整体不透明度 |
zIndex | 1 | 同 pane 内层级 |
keepBuffer | 2 | 视野外额外保留的瓦片圈数,影响拖动流畅度与内存 |
updateWhenIdle | false(移动端为 true) | 是否等移动结束再加载 |
updateWhenZooming | true | 缩放动画过程中是否刷新瓦片 |
updateInterval | 200 | 加载节流间隔,毫秒 |
className | '' | 容器附加 class |
attribution | '' | 版权文字,加入版权控件 |
成员
| 成员 | 返回值 | 说明 |
|---|---|---|
createTile(coords, done) | HTMLElement | 必须重写;完成后调用 done(err, tile) |
getTileSize() | Point | 读取瓦片尺寸 |
setOpacity(opacity) | this | 批量改瓦片透明度 |
setZIndex(zIndex) | this | 调整层级 |
redraw() | this | 清除现有瓦片并重新请求 |
isLoading() | Boolean | 是否仍有瓦片在加载 |
getContainer() | HTMLElement | 瓦片容器节点 |
bringToFront() / bringToBack() | this | 同级图层排序 |
事件
| 事件 | 触发时机 |
|---|---|
loading | 开始加载一批瓦片 |
tileloadstart | 单块瓦片请求发出,e.tile、e.coords |
tileload | 单块瓦片加载成功 |
tileerror | 单块瓦片失败,e.error 为错误对象 |
tileunload | 瓦片被移出保留范围 |
load | 当前视野内瓦片全部就绪 |
var LabelGrid = L.GridLayer.extend({
createTile: function (coords) {
var tile = L.DomUtil.create('canvas', 'leaflet-tile');
var size = this.getTileSize();
tile.width = size.x;
tile.height = size.y;
var ctx = tile.getContext('2d');
ctx.fillStyle = '#f4f6f8';
ctx.fillRect(0, 0, size.x, size.y);
ctx.strokeStyle = '#d5dae1';
ctx.strokeRect(0.5, 0.5, size.x - 1, size.y - 1);
ctx.fillStyle = '#58606e';
ctx.font = '12px sans-serif';
ctx.fillText(coords.z + '/' + coords.x + '/' + coords.y, 10, 20);
return tile;
}
});
var labels = new LabelGrid({ tileSize: 256, opacity: 0.9 }).addTo(map);
labels.on('tileerror', function (e) { console.warn(e.coords, e.error); });
异步加载瓦片时必须在完成后调 done。图片或异步绘制忘了在回调里
done(null, tile),图层的 load 事件不会触发,
isLoading() 会一直为 true。同步返回的 canvas 瓦片不调也能显示,
只是不参与加载状态统计。
maxNativeZoom 不设置时,地图放大到超过瓦片服务上限会请求不存在的
层级,表现是整屏空白。服务最高只到 18 级就把这个值设为 18,Leaflet 会拉伸 18 级瓦片,
牺牲清晰度换取连续显示。移动端 updateWhenIdle 默认为 true,
拖动时瓦片不更新,属于省流设计。
经纬志(2026)。《GridLayer》。https://www.jingweizhi.com/leaflet/api/grid-layer.html(访问日期 2026-11-03)。