首页 / Leaflet / API 文档
GeoJSON
先看结论
把 GeoJSON 几何批量转成 Leaflet 图层,继承 FeatureGroup 的全部能力。
L.geoJSON(geojson?, options?) → GeoJSON
选项
| 选项 | 默认 | 说明 |
|---|---|---|
pointToLayer | — | (feature, latlng) => Layer,点要素的工厂函数 |
style | — | (feature) => Path options,线面样式 |
onEachFeature | — | (feature, layer),绑定弹窗与事件 |
filter | — | (feature) => Boolean,返回 false 则跳过 |
coordsToLatLng | — | 自定义坐标转换函数 |
markersInheritOptions | false | Marker 是否继承图层级 markerOptions |
interactive | true | 是否参与鼠标交互;纯展示可设 false |
bubblingMouseEvents | true | 鼠标事件是否向地图冒泡 |
pane | 'overlayPane' | 渲染 pane |
attribution | — | 版权文字 |
方法
| 方法 | 说明 |
|---|---|
addData(data) | 追加数据,可多次调用 |
setStyle(style) | 对象或函数,重设所有矢量样式 |
resetStyle(layer?) | 恢复某图层到初始样式 |
toGeoJSON(precision?) | 导回 GeoJSON,可指定小数位 |
getBounds() | 整组范围,需存在有效要素 |
eachLayer(fn) | 遍历子图层 |
bindPopup(html) | 给整组绑定同一个弹窗 |
clearLayers() | 清空全部子图层 |
静态方法
| 方法 | 说明 |
|---|---|
L.GeoJSON.coordsToLatLng(coords) | [lng, lat] → LatLng,可选高度 |
L.GeoJSON.latLngToCoords(latlng, precision?) | 反向转换 |
L.GeoJSON.latLngsToCoords(latlngs, levels, closed?) | 批量转换,levels 控制嵌套深度 |
L.GeoJSON.asFeature(geojson) | 把裸几何包装成 Feature |
var layer = L.geoJSON(data, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, { radius: 6, fillOpacity: 0.9 });
},
style: function (feature) {
return { color: '#1f5fd0', weight: 2, fillOpacity: 0.2 };
},
onEachFeature: function (feature, lyr) {
lyr.bindPopup(feature.properties.name);
}
}).addTo(map);
layer.addData({
type: 'Feature',
properties: { name: '新增点' },
geometry: { type: 'Point', coordinates: [116.41, 39.91] }
});
toGeoJSON() 输出的坐标顺序是 [经度, 纬度]。
与输入一致,中途不需要翻转。需要控制精度时传参数,例如
toGeoJSON(6) 保留六位小数,能显著减小导出体积。
样式重算
setStyle 传函数时会为每个要素重新调用,适合做分级设色和选中高亮。
resetStyle 只对单个图层生效,常用于「点击高亮、再点恢复」:
layer.eachLayer(function (lyr) {
lyr.on('click', function () {
layer.eachLayer(function (other) { layer.resetStyle(other); });
lyr.setStyle({ color: '#c2410c', weight: 3 });
});
});
几何与坐标的边界情况
geometry: null的要素会被跳过,不会报错。- Polygon 的环首尾点重复是规范要求,Leaflet 接受重复点,但导出时不会自动补。
- 经纬度超出 ±180 / ±90 时不会自动裁剪,数据错误会在渲染阶段才暴露。
- 坐标系不是 WGS84 时,用
coordsToLatLng统一转换,别在样式回调里逐点处理。
经纬志(2026)。《GeoJSON》。https://www.jingweizhi.com/leaflet/api/geojson.html(访问日期 2026-11-03)。