GeoJSON 支持
本文档涵盖 Leaflet 全面的 GeoJSON 支持系统,该系统支持解析、显示和转换 GeoJSON 格式 的地理数据。系统提供输入功能(将 GeoJSON 数据加载到地图上)和输出功能(将 Leaflet 图层转换回 GeoJSON 格式)。
关于矢量图层渲染和样式的信息,请参阅 矢量图层。关于标记特定功能,请参阅 标记与图标。
架构概览
Leaflet 的 GeoJSON 支持围绕一个扩展 FeatureGroup 的中心 GeoJSON 类构建,以及用于坐标转换和几何转换的静态工具函数。系统还为核心图层类型扩展了 toGeoJSON() 方法以实现往返转换。
架构:GeoJSON 支持系统
GeoJSON 类
GeoJSON 类作为在 Leaflet 中处理 GeoJSON 数据的主要接口。它扩展 FeatureGroup 以提供图层管理能力,同时添加 GeoJSON 特定功能。
构造函数和选项
GeoJSON 类接受可选的 GeoJSON 数据和配置选项:
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
pointToLayer | Function | 创建 Marker | 将 GeoJSON 点转换为 Leaflet 图层 |
style | Function | {} | 矢量图层的样式函数 |
onEachFeature | Function | 无操作 | 为每个要素执行的回调 |
filter | Function | true | 要素过滤函数 |
coordsToLatLng | Function | coordsToLatLng | 坐标转换函数 |
markersInheritOptions | Boolean | false | 标记是否继承组选项 |
GeoJSON 类初始化和选项
核心方法
addData(geojson)
addData() 方法处理 GeoJSON 数据并将其转换为适当的 Leaflet 图层:
addData 方法处理流程
resetStyle(layer) 和 setStyle(style)
样式管理方法允许动态样式更新:
resetStyle()- 将图层样式重置为原始 GeoJSON 样式setStyle()- 将新样式函数应用于所有图层
静态工具函数
几何转换
geometryToLayer(geojson, options)
将 GeoJSON 几何图形转换为适当的 Leaflet 图层类型:
| GeoJSON 类型 | Leaflet 图层 | 备注 |
|---|---|---|
Point | Marker | 如果提供则使用 pointToLayer 选项 |
MultiPoint | FeatureGroup | 包含多个标记 |
LineString | Polyline | 单条线 |
MultiLineString | Polyline | 多维坐标 |
Polygon | Polygon | 单个多边形,可选带孔洞 |
MultiPolygon | Polygon | 多维坐标 |
GeometryCollection | FeatureGroup | 递归几何处理 |
FeatureCollection | FeatureGroup | 递归要素处理 |
geometryToLayer 转换逻辑
坐标转换
coordsToLatLng(coords) 和 coordsToLatLngs(coords, levelsDeep, coordsToLatLng)
处理 GeoJSON 格式([lng, lat, alt])和 Leaflet 格式(LatLng(lat, lng, alt))之间的坐标系统转换:
坐标系统转换
图层 toGeoJSON 扩展
Leaflet 为核心图层类型扩展了 toGeoJSON() 方法,以支持将图层转换回 GeoJSON 格式。
基于点的图层
基于点的图层(Marker、Circle、CircleMarker)共享一个通用的 PointToGeoJSON mixin:
点图层 GeoJSON 转换
矢量图层
Polyline toGeoJSON
折线根据坐标结构转换为 LineString 或 MultiLineString:
Polyline GeoJSON 转换
Polygon toGeoJSON
多边形处理简单多边形和带孔洞的多多边形:
Polygon GeoJSON 转换
LayerGroup 集合
LayerGroup 处理集合并生成 FeatureCollection、GeometryCollection 或 MultiPoint 输出:
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);