经纬志
首页 / 实战手册 / 数据加载

geometry 为 null 的要素,让 fitBounds 抛 null is not an object

先看结论

接口里混进两条 geometry 为 null 的记录,整个地图初始化就中断了。

最后验证 2026-11-03 · 多技术栈 · 更新 2026-10-29 · 引用本文

现象

控制台报:

Uncaught TypeError: Cannot read properties of null (reading 'lat')
    at L.LatLngBounds.extend (leaflet.js:5)
    at L.Map.fitBounds (leaflet.js:5)

地图停在初始位置,所有图层都没加上去。 数据里 500 条记录中有 2 条的 geometry 是 null, 其余 498 条完全正常。

原因

GeoJSON 规范允许 "geometry": null,用于表示「有属性但位置未知」的要素。 这类要素在 L.geoJSON 中会被创建为一个没有几何的空图层组, 本身没有 _bounds。

fitBounds 内部会对每个子图层的 bounds 调用 extend, 遇到 null 就抛异常。异常发生在初始化流程中,后续代码全部不执行。

排查过程

  1. 遍历要素,统计 geometry === null 的数量。
  2. 单独对 null 要素调用 L.geoJSON(f).getBounds(),确认返回的是空 bounds。
  3. 把 fitBounds 移出初始化函数,或加 try/catch,看是否还有其他要素有问题。
  4. 检查数据来源:多为 LEFT JOIN 查询产生的空几何,或字段被置空的脏数据。
const nulls = fc.features.filter(f => f.geometry === null);
console.log(nulls.length);                   // 2
console.log(nulls[0].properties);            // { id: 517, name: '未定位点' }

解决方案

在进入渲染层之前过滤掉空几何,并保留属性用于列表展示; 确实需要展示时,用属性中的经纬度补一个点。

const features = fc.features.filter(f => f.geometry && f.geometry.coordinates);

// 有经纬度属性时补几何
const repaired = fc.features.filter(f => !f.geometry).map(f => {
  const { lng, lat } = f.properties;
  if (typeof lng !== 'number' || typeof lat !== 'number') return null;
  return { ...f, geometry: { type: 'Point', coordinates: [lng, lat] } };
}).filter(Boolean);

const layer = L.geoJSON({ type: 'FeatureCollection', features: [...features, ...repaired] });

// fitBounds 前先确认 bounds 有效
if (layer.getLayers().length && layer.getBounds().isValid()) {
  map.fitBounds(layer.getBounds(), { padding: [24, 24] });
}

验证

过滤后 features.length 为 498,layer.getBounds().isValid() 为 true,地图能缩放定位到数据范围,控制台无异常。

console.assert(layer.getLayers().length === 498, '空几何未过滤');
console.assert(layer.getBounds().isValid(), 'bounds 仍无效');
// turf 校验整个集合
console.assert(turf.featureEach.length >= 0 && features.every(f => f.geometry), '仍含 null');

适用版本

库版本行为
Leaflet1.9.xnull 几何生成空图层,fitBounds 抛异常
Mapbox GL JS2.15 / 3.xnull 几何的要素被跳过,不报错
turf.js7.xturf.bbox 等函数对 null 会返回 NaN
GeoJSON RFC 79462016 起geometry: null 是合法值
引用本文

经纬志(2026)。《geometry 为 null 的要素,让 fitBounds 抛 null is not an object》。https://www.jingweizhi.com/cookbook/geojson-null-geometry.html(访问日期 2026-11-03)。