经纬志
首页 / Leaflet / API 文档

GeoJSON 选项

先看结论

GeoJSON 图层的六个回调与开关,决定数据怎么变成图层、长什么样、要不要加载。

最后验证 2026-11-03 · Leaflet 1.9.4 · 更新 2026-10-28 · 引用本文
L.geoJSON(geojson, options) → GeoJSON

参数

选项默认值说明
pointToLayer—(feature, latlng) => Layer,决定 Point 转成什么图层;不写则用默认 marker
style—(feature) => Path options,只作用于线与面
onEachFeature—(feature, layer) =>,每个要素创建后调用,用于绑气泡与事件
filter—(feature) => Boolean,返回 false 的要素不加入图层
coordsToLatLng—(coords) => LatLng,自定义坐标解析顺序
markersInheritOptionsfalse为 true 时 style 里的 icon 等选项会传给 marker
bubblingMouseEventstrue继承给要素的事件冒泡开关
其他 Path 选项—color、weight、fillOpacity 等直接下发给线与面

成员

成员返回值说明
addData(geojson)this追加数据,同样会走 filter 与 style 回调
setStyle(style)this把返回的样式应用到所有线与面
resetStyle(layer?)this恢复初始样式,按要素重新走一遍 style 回调
getFeature(layer)Object由图层反查原始 GeoJSON 要素
toGeoJSON(precision?)Object导出为 FeatureCollection,precision 默认 6
eachLayer(fn, context?)this遍历生成的所有子图层
getLayers()Layer[]子图层数组
L.geoJSON(data, {
  filter: function (feature) {
    return feature.properties.type !== 'hidden';
  },

  style: function (feature) {
    var level = feature.properties.level;
    return {
      color: level > 2 ? '#c2410c' : '#1f5fd0',
      weight: 1 + level * 0.6,
      fillOpacity: 0.1 + level * 0.05
    };
  },

  pointToLayer: function (feature, latlng) {
    return L.circleMarker(latlng, {
      radius: 5,
      color: '#fff',
      weight: 1,
      fillColor: '#17694a',
      fillOpacity: 0.9
    });
  },

  onEachFeature: function (feature, layer) {
    if (!feature.properties.name) return;
    layer.bindTooltip(feature.properties.name, { direction: 'top' });
  }
}).addTo(map);

style 不会影响点。Point 要素的样式要在 pointToLayer 里设, 想让 style 里的 icon 生效必须显式打开 markersInheritOptions: true,而且只认 icon 与 interactive 这类 Marker 选项。

onEachFeature 只在新要素创建时执行,addData 追加的数据 同样会触发。过滤掉的要素连图层都不会生成,因此不要指望在 onEachFeature 里把被 filter 排除的要素再放回来。数据量大时 用 filter 在进入渲染前就裁掉无关要素,比先加载再隐藏省得多。

引用本文

经纬志(2026)。《GeoJSON 选项》。https://www.jingweizhi.com/leaflet/api/geojson-options.html(访问日期 2026-11-03)。