Skip to content

GeoJSON 支持

本文档涵盖 Leaflet 全面的 GeoJSON 支持系统,该系统支持解析、显示和转换 GeoJSON 格式 的地理数据。系统提供输入功能(将 GeoJSON 数据加载到地图上)和输出功能(将 Leaflet 图层转换回 GeoJSON 格式)。

关于矢量图层渲染和样式的信息,请参阅 矢量图层。关于标记特定功能,请参阅 标记与图标

架构概览

Leaflet 的 GeoJSON 支持围绕一个扩展 FeatureGroup 的中心 GeoJSON 类构建,以及用于坐标转换和几何转换的静态工具函数。系统还为核心图层类型扩展了 toGeoJSON() 方法以实现往返转换。

SVG
100%

架构:GeoJSON 支持系统

GeoJSON 类

GeoJSON 类作为在 Leaflet 中处理 GeoJSON 数据的主要接口。它扩展 FeatureGroup 以提供图层管理能力,同时添加 GeoJSON 特定功能。

构造函数和选项

GeoJSON 类接受可选的 GeoJSON 数据和配置选项:

选项类型默认值描述
pointToLayerFunction创建 Marker将 GeoJSON 点转换为 Leaflet 图层
styleFunction{}矢量图层的样式函数
onEachFeatureFunction无操作为每个要素执行的回调
filterFunctiontrue要素过滤函数
coordsToLatLngFunctioncoordsToLatLng坐标转换函数
markersInheritOptionsBooleanfalse标记是否继承组选项
SVG
100%

GeoJSON 类初始化和选项

核心方法

addData(geojson)

addData() 方法处理 GeoJSON 数据并将其转换为适当的 Leaflet 图层:

SVG
100%

addData 方法处理流程

resetStyle(layer) 和 setStyle(style)

样式管理方法允许动态样式更新:

  • resetStyle() - 将图层样式重置为原始 GeoJSON 样式
  • setStyle() - 将新样式函数应用于所有图层

静态工具函数

几何转换

geometryToLayer(geojson, options)

将 GeoJSON 几何图形转换为适当的 Leaflet 图层类型:

GeoJSON 类型Leaflet 图层备注
PointMarker如果提供则使用 pointToLayer 选项
MultiPointFeatureGroup包含多个标记
LineStringPolyline单条线
MultiLineStringPolyline多维坐标
PolygonPolygon单个多边形,可选带孔洞
MultiPolygonPolygon多维坐标
GeometryCollectionFeatureGroup递归几何处理
FeatureCollectionFeatureGroup递归要素处理
SVG
100%

geometryToLayer 转换逻辑

坐标转换

coordsToLatLng(coords) 和 coordsToLatLngs(coords, levelsDeep, coordsToLatLng)

处理 GeoJSON 格式([lng, lat, alt])和 Leaflet 格式(LatLng(lat, lng, alt))之间的坐标系统转换:

SVG
100%

坐标系统转换

图层 toGeoJSON 扩展

Leaflet 为核心图层类型扩展了 toGeoJSON() 方法,以支持将图层转换回 GeoJSON 格式。

基于点的图层

基于点的图层(MarkerCircleCircleMarker)共享一个通用的 PointToGeoJSON mixin:

SVG
100%

点图层 GeoJSON 转换

矢量图层

Polyline toGeoJSON

折线根据坐标结构转换为 LineStringMultiLineString

SVG
100%

Polyline GeoJSON 转换

Polygon toGeoJSON

多边形处理简单多边形和带孔洞的多多边形:

SVG
100%

Polygon GeoJSON 转换

LayerGroup 集合

LayerGroup 处理集合并生成 FeatureCollectionGeometryCollectionMultiPoint 输出:

SVG
100%

LayerGroup GeoJSON 转换

要素规范化

asFeature()getFeature() 函数确保一致的 GeoJSON Feature 格式:

输入类型输出
Feature原样返回
FeatureCollection原样返回
Geometry 对象包装在具有空 properties 的 Feature 中

使用模式

基本 GeoJSON 加载

new GeoJSON(geojsonData, {
    style: function (feature) {
        return {color: feature.properties.color};
    },
    onEachFeature: function (feature, layer) {
        layer.bindPopup(feature.properties.description);
    }
}).addTo(map);

自定义点渲染

new GeoJSON(geojsonData, {
    pointToLayer: function (feature, latlng) {
        return new CircleMarker(latlng, {radius: feature.properties.size});
    }
});

往返转换

// 图层转 GeoJSON
const geojson = layerGroup.toGeoJSON();

// GeoJSON 转回图层
const layers = new GeoJSON(geojson);