首页 / Leaflet / API 文档
GeoJSON 选项
先看结论
GeoJSON 图层的六个回调与开关,决定数据怎么变成图层、长什么样、要不要加载。
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,自定义坐标解析顺序 |
markersInheritOptions | false | 为 true 时 style 里的 icon 等选项会传给 marker |
bubblingMouseEvents | true | 继承给要素的事件冒泡开关 |
| 其他 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)。