首页 / MapLibre / API 文档
fitBounds
先看结论
把视角缩放到刚好容纳一个矩形范围,自动算出中心与缩放级别,动画期间地图还在动。
map.fitBounds([[west, south], [east, north]], { padding: 20, maxZoom: 12 })
参数
| 参数 | 默认 | 说明 |
|---|---|---|
bounds | — | [[west, south], [east, north]] 或 LngLatBounds |
padding | 0 | 四周留白,数字或 {top, bottom, left, right} |
offset | [0, 0] | 结果中心相对画布中心的像素偏移 |
maxZoom | 未设 | 范围很小时限制最大放大级别 |
bearing | 0 | 目标方位角,正北为 0 |
linear | false | true 时用 easeTo 匀速过渡,false 时用 flyTo |
eventData | — | 第三个参数,透传到 movestart 等事件 |
相关成员
| 成员 | 说明 |
|---|---|
cameraForBounds(bounds, options) | 只计算相机参数,不移动地图 |
fitScreenCoordinates(p0, p1, bearing, options) | 按两个屏幕点反算范围 |
easeTo(options) | linear: true 时实际调用的动画 |
flyTo(options) | linear: false 时实际调用的飞行动画 |
getBounds() | 读回当前视野范围,用于校验结果 |
示例
var bbox = [[73.5, 18.0], [135.1, 53.6]]; // 西南角、东北角
map.fitBounds(bbox, {
padding: { top: 40, bottom: 40, left: 60, right: 60 },
maxZoom: 6,
linear: true,
duration: 800
});
/* 单点是合法输入,但会缩放到最大级别,必须给 maxZoom 兜底 */
map.fitBounds([[116.39, 39.9], [116.39, 39.9]], {
padding: 80,
maxZoom: 14
});
/* 从图层数据算范围,再交给 fitBounds */
var bounds = new maplibregl.LngLatBounds();
map.querySourceFeatures('cities').forEach(function (f) {
if (f.geometry.type === 'Point') bounds.extend(f.geometry.coordinates);
});
if (!bounds.isEmpty()) map.fitBounds(bounds, { padding: 30 });
注意事项
padding 用来避开悬浮面板、图例与右上角控件。
数值给得不够时,标注会贴在范围边缘被裁掉一半;
给得过多则有效视口变小,缩放级别被压得过低。
两个角的顺序必须是西南在前、东北在后。写反时经度会被
adjustAntiMeridian 修正成跨 180 度的另一段,
表现为地图缩到整个太平洋。
动画期间读到的视角是中间态。需要拿到最终结果时监听
moveend,不要在 fitBounds 之后立刻读
getZoom()。
经纬志(2026)。《fitBounds》。https://www.jingweizhi.com/maplibre/api/fit-bounds.html(访问日期 2026-11-03)。