经纬志
首页 / Leaflet / API 文档

LatLngBounds

先看结论

轴对齐的经纬度矩形:由西南角与东北角两个点定义,用于视野计算与范围判断。

最后验证 2026-11-03 · Leaflet 1.9.4 · 更新 2026-10-29 · 引用本文
L.latLngBounds(corner1, corner2) → LatLngBounds

也可以传一个 LatLng 数组,或什么都不传得到一个无效范围。 L.latLngBounds(latlngs) 会自动取所有点的外接矩形。

构造方式

写法结果
L.latLngBounds(sw, ne)西南角与东北角两个 LatLng
L.latLngBounds([sw, ne])两点数组,顺序不限,构造时会归一
L.latLngBounds(latlngs)多点数组,取全部点的外接矩形
L.latLngBounds()无效范围,isValid() 为 false

方法

方法返回说明
extend(obj)this并入一个点或另一个范围,原地扩大
pad(bufferRatio)LatLngBounds按比例向外扩张,返回新对象,不修改原范围
getCenter()LatLng矩形中心点
getSouthWest()LatLng西南角
getNorthEast()LatLng东北角
getNorthWest()LatLng西北角
getSouthEast()LatLng东南角
getWest() / getSouth() / getEast() / getNorth()number四个边的经度或纬度
contains(obj)boolean是否包含一个点或另一个范围
intersects(otherBounds)boolean是否与另一个范围相交
overlaps(otherBounds)boolean是否有面积重叠,只触边不算
isValid()boolean两个角点是否都已定义
toBBoxString()stringwest,south,east,north 形式的字符串
equals(otherBounds, maxMargin?)boolean近似相等,maxMargin 为允许的偏差

用数据算视野

var pts = [
  [39.907359, 116.391263],
  [39.934, 116.432],
  [39.881, 116.355]
];

var bounds = L.latLngBounds(pts);

map.fitBounds(bounds, {
  padding: [24, 24],
  maxZoom: 15
});

fitBounds 接受 LatLngBounds,也会自己把数组转成范围。 传 padding 可以留出边距,避免要素贴着边缘。

两点扩充为多要素范围

extend 原地修改并返回自身,适合在循环里累积。 如果不想影响调用方传进来的范围,先 L.latLngBounds(bounds.getSouthWest(), bounds.getNorthEast()) 复制一份。

var extent = L.latLngBounds();

geojson.features.forEach(function (feature) {
  L.geoJSON(feature).getLayers().forEach(function (layer) {
    if (layer.getBounds) {
      extent.extend(layer.getBounds());
    }
  });
});

console.log(extent.toBBoxString());

判断与扩张

调用结果
bounds.contains(latlng)点是否落在矩形内,边界上算包含
bounds.contains(other)另一个范围是否完全被包含
bounds.intersects(other)两个范围是否有任何接触
bounds.overlaps(other)只共享边或角时返回 false
bounds.pad(0.1)四边各向外扩 10% 的高度与宽度

跨越 180 度经线

LatLngBounds 假设西经小于东经,范围不跨越日期变更线。 数据落在两侧时,直接构造会得到一个横跨整个地球的巨大矩形。 这种数据应先在业务侧把经度归一到同一侧,或改用两个范围分别处理。

无效范围会让 fitBounds 报错。 数据为空时 L.latLngBounds() 仍是无效对象, map.fitBounds 会读不到角点。调用前先判断 bounds.isValid()。

引用本文

经纬志(2026)。《LatLngBounds》。https://www.jingweizhi.com/leaflet/api/latlng-bounds.html(访问日期 2026-11-03)。