# leaflet-gridfill **Repository Path**: stylekong/leaflet-gridfill ## Basic Information - **Project Name**: leaflet-gridfill - **Description**: leaflet 网格填充多边形 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-09 - **Last Updated**: 2026-06-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README (# leaflet-gridfill) 一个用于在 GeoJSON 矩形/多边形图层上生成规则网格线的轻量插件。网格线只保留在要素内部的线段,使用屏幕像素间隔控制网格密度。 **主要特点** - 按屏幕像素间隔(`gridSize`)生成横/竖网格线 - 仅在输入要素内部保留线段(基于 `@turf/turf` 的几何相交判断) - 可设置线条颜色、透明度、宽度,可与 `L.geoJSON` 的 `style` 选项配合使用 **仓库结构** - 源文件: [src/leaflet-gridfill.js](src/leaflet-gridfill.js) **安装** 如果你直接从源码使用,确保在构建或打包时包含 `src/leaflet-gridfill.js`,并安装依赖: ```bash npm install leaflet @turf/turf ``` **快速开始(ES 模块)** ```js import L from 'leaflet' import 'leaflet-gridfill' // 如果你将插件打包为模块,或直接导入文件 // 假设已有 map 和 geojson 数据 const layer = L.gridfill(geojson, { gridSize: 20, // 像素间隔 gridColor: '#ff0000', gridOpacity: 0.6, gridWeight: 1, style: feature => ({ color: '#3388ff', weight: 2, fillOpacity: 0.1 }) }) layer.addTo(map) ``` 或者在浏览器中直接通过 script 引入(需先加载 `leaflet` 与 `@turf/turf`): ```html ``` 然后按上面的方式调用 `L.gridfill`。 **API** - `L.gridfill(json, option)` - 参数 - `json`:GeoJSON `FeatureCollection`,应包含矩形或多边形要素 - `option`:可选,Leaflet 图层选项,同时支持以下自定义配置(也可放在 `option` 中): - `gridSize` (number) — 网格像素间隔,默认 `10` - `gridColor` (string) — 网格线颜色,默认 `#3388ff` - `gridOpacity` (number) — 网格线透明度,默认 `0.5` - `gridWeight` (number) — 网格线宽度,默认 `1` - `style` (function|object) — 可用于设置要素样式(会与网格样式合并) - 返回值:`L.layerGroup`,包含原始的 GeoJSON 图层与生成的网格线图层 **实现要点** - 插件在地图的 `zoomend` 和 `moveend` 事件触发时重新计算可视范围内的网格 - 通过将可视范围转为屏幕像素点,以像素为单位按 `gridSize` 生成横/竖轴线,然后将屏幕点转换回地理坐标进行 turf 运算 - 使用 `turf.lineIntersect` 与 `turf.booleanPointInPolygon` 筛选在要素内部的线段片段 **示例:使用自定义 style 函数** ```js const layer = L.gridfill(geojson, { gridSize: 15, style: feature => ({ color: feature.properties.color || '#3388ff', weight: 2, fillOpacity: 0.05 }) }) ``` **注意事项** - 插件依赖 `@turf/turf` 执行几何运算,请确保在环境中可用 - `gridSize` 单位为屏幕像素,放大/缩小时网格密度会根据像素间隔发生变化