@dsh-gis/dsh-opengis-skill 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +68 -28
  3. package/THIRD_PARTY_NOTICES.md +9 -0
  4. package/adaptations/brutile.md +8 -0
  5. package/adaptations/cesiumjs.md +8 -0
  6. package/adaptations/common.md +19 -0
  7. package/adaptations/deck-gl.md +8 -0
  8. package/adaptations/duckdb-spatial.md +8 -0
  9. package/adaptations/gdal-api.md +8 -0
  10. package/adaptations/gdal.md +8 -0
  11. package/adaptations/geolibre.md +8 -0
  12. package/adaptations/geometry-api-java.md +8 -0
  13. package/adaptations/geometry-api-net.md +8 -0
  14. package/adaptations/geonode.md +8 -0
  15. package/adaptations/geopandas.md +8 -0
  16. package/adaptations/geopipe-agent.md +8 -0
  17. package/adaptations/geoserver-cloud.md +8 -0
  18. package/adaptations/geoserver-rest-api.md +8 -0
  19. package/adaptations/geoserver.md +8 -0
  20. package/adaptations/geotools.md +8 -0
  21. package/adaptations/grass-gis.md +8 -0
  22. package/adaptations/jts.md +8 -0
  23. package/adaptations/kepler-gl.md +8 -0
  24. package/adaptations/leaflet.md +8 -0
  25. package/adaptations/mapbox-gl-js.md +8 -0
  26. package/adaptations/mapserver.md +8 -0
  27. package/adaptations/mapsui.md +8 -0
  28. package/adaptations/nettopologysuite.md +8 -0
  29. package/adaptations/opengis-all.md +9 -0
  30. package/adaptations/opengis-daf.md +9 -0
  31. package/adaptations/opengis-utils-for-java.md +8 -0
  32. package/adaptations/opengis-utils-for-net.md +8 -0
  33. package/adaptations/openlayers.md +8 -0
  34. package/adaptations/pdal.md +8 -0
  35. package/adaptations/postgis.md +8 -0
  36. package/adaptations/proj.md +8 -0
  37. package/adaptations/projnet4geoapi.md +8 -0
  38. package/adaptations/pyqgis.md +8 -0
  39. package/adaptations/qgis-process.md +8 -0
  40. package/adaptations/qgis-server.md +8 -0
  41. package/adaptations/shapely.md +8 -0
  42. package/adaptations/sharpmap.md +8 -0
  43. package/adaptations/spatialite.md +8 -0
  44. package/adaptations/whitebox-tools.md +8 -0
  45. package/assets/brutile/SKILL.md +283 -0
  46. package/assets/cesiumjs/SKILL.md +81 -35
  47. package/assets/deck-gl/SKILL.md +26 -34
  48. package/assets/duckdb-spatial/SKILL.md +363 -0
  49. package/assets/gdal/SKILL.md +55 -33
  50. package/assets/gdal/reference/raster-tools.md +14 -0
  51. package/assets/gdal/reference/vector-tools.md +5 -0
  52. package/assets/gdal-api/SKILL.md +12 -18
  53. package/assets/gdal-api/reference/raster-api.md +7 -0
  54. package/assets/gdal-api/reference/vector-api.md +9 -0
  55. package/assets/geolibre/SKILL.md +357 -0
  56. package/assets/geometry-api-java/SKILL.md +10 -16
  57. package/assets/geometry-api-net/SKILL.md +70 -32
  58. package/assets/geometry-api-net/reference/geometry-types.md +5 -0
  59. package/assets/geonode/SKILL.md +340 -0
  60. package/assets/geopandas/SKILL.md +21 -24
  61. package/assets/geopandas/reference/core-api.md +4 -0
  62. package/assets/geopipe-agent/SKILL.md +29 -31
  63. package/assets/geopipe-agent/reference/steps-reference.md +12 -0
  64. package/assets/geopipe-agent/reference/workflows.md +8 -0
  65. package/assets/geoserver/SKILL.md +10 -15
  66. package/assets/geoserver-cloud/SKILL.md +25 -33
  67. package/assets/geoserver-rest-api/SKILL.md +17 -19
  68. package/assets/geoserver-rest-api/reference/endpoints.md +16 -0
  69. package/assets/geotools/SKILL.md +12 -17
  70. package/assets/geotools/reference/raster-rendering.md +5 -0
  71. package/assets/geotools/reference/vector-io.md +7 -0
  72. package/assets/grass-gis/SKILL.md +26 -33
  73. package/assets/jts/SKILL.md +12 -16
  74. package/assets/jts/reference/geometry-operations.md +13 -0
  75. package/assets/kepler-gl/SKILL.md +306 -0
  76. package/assets/leaflet/SKILL.md +58 -40
  77. package/assets/mapbox-gl-js/SKILL.md +26 -33
  78. package/assets/mapserver/SKILL.md +21 -29
  79. package/assets/mapsui/SKILL.md +109 -63
  80. package/assets/nettopologysuite/SKILL.md +96 -31
  81. package/assets/opengis-all/SKILL.md +91 -289
  82. package/assets/opengis-all/reference/data-stages.md +269 -4
  83. package/assets/opengis-all/reference/workflow-cheatsheets.md +7 -0
  84. package/assets/opengis-daf/SKILL.md +10 -17
  85. package/assets/opengis-utils-for-java/SKILL.md +58 -49
  86. package/assets/opengis-utils-for-java/reference/common-tasks.md +16 -12
  87. package/assets/opengis-utils-for-net/SKILL.md +109 -48
  88. package/assets/opengis-utils-for-net/reference/code-patterns.md +15 -11
  89. package/assets/opengis-utils-for-net/reference/util-classes.md +35 -26
  90. package/assets/openlayers/SKILL.md +81 -28
  91. package/assets/pdal/SKILL.md +25 -27
  92. package/assets/postgis/SKILL.md +80 -35
  93. package/assets/proj/SKILL.md +32 -41
  94. package/assets/projnet4geoapi/SKILL.md +293 -0
  95. package/assets/pyqgis/SKILL.md +33 -30
  96. package/assets/pyqgis/reference/processing-rendering.md +6 -0
  97. package/assets/pyqgis/reference/vector-raster-layers.md +6 -0
  98. package/assets/qgis-process/SKILL.md +75 -33
  99. package/assets/qgis-process/reference/algorithm-cheatsheet.md +6 -0
  100. package/assets/qgis-server/SKILL.md +25 -31
  101. package/assets/shapely/SKILL.md +136 -84
  102. package/assets/shapely/reference/operations-reference.md +12 -0
  103. package/assets/sharpmap/SKILL.md +97 -60
  104. package/assets/spatialite/SKILL.md +358 -0
  105. package/assets/whitebox-tools/SKILL.md +262 -0
  106. package/lib/adaptations.d.ts +53 -0
  107. package/lib/adaptations.js +343 -0
  108. package/lib/catalog.d.ts +7 -1
  109. package/lib/catalog.js +9 -1
  110. package/lib/index.d.ts +10 -1
  111. package/lib/index.js +34 -3
  112. package/lib/skill-file.d.ts +12 -0
  113. package/lib/skill-file.js +133 -18
  114. package/locale/en.json +1 -1
  115. package/locale/zh.json +1 -1
  116. package/package.json +12 -2
  117. package/upstream.json +73 -57
@@ -1,16 +1,10 @@
1
1
  ---
2
2
  name: sharpmap
3
3
  description: "Use when rendering 2D maps in legacy .NET Framework 4.7.2 WinForms or ASP.NET WebForms apps with SharpMap 1.2.0 — Map.GetMap() to PNG, ShapeFile/PostGIS providers, VectorLayer with CustomTheme, TileAsyncLayer via BruTile, ProjNet4GeoAPI transforms, or debugging blank output and GDI+ handle leaks. New projects should use Mapsui."
4
- tags:
5
- - dotnet
6
- - csharp
7
- - 2d
8
- - map
9
- - rendering
10
- - wms
11
- - shapefile
12
- - postgis
13
- - winforms
4
+ license: MIT
5
+ metadata:
6
+ category: gis
7
+ tags: "dotnet, csharp, 2d, map, rendering, wms, shapefile, postgis, winforms"
14
8
  ---
15
9
 
16
10
  > **项目地址:** <https://github.com/SharpMap/SharpMap>
@@ -19,7 +13,7 @@ tags:
19
13
  >
20
14
  > **NuGet:** `SharpMap`、`SharpMap.UI`、`SharpMap.Extensions`、`SharpMap.Web`、`SharpMap.Layers.BruTile`
21
15
  >
22
- > **最新版本:** 1.2.0(截至2026-10,NuGet;发布于 2021-03,仓库未归档但维护低频)
16
+ > **最新版本:** 1.2.0(截至 2026-11,[NuGet `SharpMap`](https://www.nuget.org/packages/SharpMap);发布于 2021-03,仓库未归档但维护低频)
23
17
  >
24
18
  > **许可证:** LGPL-2.1-or-later
25
19
 
@@ -41,6 +35,8 @@ SharpMap 提供:
41
35
 
42
36
  ## 安装
43
37
 
38
+ ### 方式一:dotnet CLI
39
+
44
40
  ```bash
45
41
  dotnet add package SharpMap # 核心(netstandard2.0)
46
42
  dotnet add package SharpMap.UI # WinForms MapBox 控件(.NET Framework 4.7.2)
@@ -50,6 +46,33 @@ dotnet add package SharpMap.Web # ASP.NET WMS 服务
50
46
  dotnet add package ProjNet4GeoAPI # 坐标变换(实现 GeoAPI 接口;ProjNet 2.x 与 SharpMap 1.2 类型不兼容)
51
47
  ```
52
48
 
49
+ ### 方式二:手写 csproj 的 PackageReference
50
+
51
+ ```xml
52
+ <Project Sdk="Microsoft.NET.Sdk">
53
+ <PropertyGroup>
54
+ <OutputType>WinExe</OutputType>
55
+ <TargetFramework>net472</TargetFramework> <!-- SharpMap.UI 只有 .NET Framework 4.7.2 -->
56
+ </PropertyGroup>
57
+ <ItemGroup>
58
+ <PackageReference Include="SharpMap" Version="1.2.0" />
59
+ <PackageReference Include="SharpMap.UI" Version="1.2.0" />
60
+ <PackageReference Include="SharpMap.Layers.BruTile" Version="1.2.0" />
61
+ </ItemGroup>
62
+ </Project>
63
+ ```
64
+
65
+ ### 验证
66
+
67
+ ```bash
68
+ dotnet --version # 确认 SDK 可用
69
+ dotnet restore # 能还原 SharpMap 1.2.0 即包解析成功
70
+ dotnet build # 编译通过仅代表能构建,渲染结果仍需出图检查
71
+ ```
72
+
73
+ > `dotnet restore` 通常伴随 NU1902/NU1903/NU1904 漏洞告警(SharpMap 1.2.0 发布于 2021-03,传递依赖较旧),这是已知状态,不要当成安装失败。
74
+
75
+
53
76
  ---
54
77
 
55
78
  ## 核心 API:核心对象
@@ -183,34 +206,12 @@ mapBox1.MouseDown += (s, e) => {
183
206
 
184
207
  ---
185
208
 
186
- ## 性能建议
187
-
188
- 1. 预建空间索引(Shapefile `.qix`、PostGIS GiST)
189
- 2. `TileAsyncLayer` 用于在线底图
190
- 3. 避免主线程加载大数据
191
- 4. `LabelLayer` 启用优先级与碰撞检测
192
- 5. 复用 `Brush/Pen/VectorStyle`
193
-
194
- ---
195
-
196
- ## 常见问题
197
-
198
- | 问题 | 解决 |
199
- |------|------|
200
- | 无图 | 检查 SRID、`ZoomToExtents` |
201
- | 文字模糊 | 设置高 DPI Aware、`MapBox.MapTransform` |
202
- | GDI+ 内存泄漏 | 释放 `Brush/Pen/Bitmap` |
203
- | Shapefile 中文乱码 | `new ShapeFile(path, true, false, Encoding.UTF8)` |
204
- | 找不到 `SharpMap.UI.WinForms` 包 | 该包名在 NuGet 上不存在,WinForms 控件在 `SharpMap.UI` 包中 |
205
- | `CoordinateTransformation` 赋值编译错误 | ProjNet 2.x 不再实现 GeoAPI 接口,改用 `ProjNet4GeoAPI` 1.4.1 |
206
- | 找不到 `TileAsyncLayer` | 瓦片图层不在核心包中,需安装 `SharpMap.Layers.BruTile` |
207
-
208
- ---
209
-
210
209
  ## 典型工作流
211
210
 
212
211
  ### 工作流 1:Shapefile 渲染 + 主题样式 + 输出图片
213
212
 
213
+ 输入 `data/countries.shp`(含 `NAME`、`POP_EST` 字段),输出 `output.png`。
214
+
214
215
  ```csharp
215
216
  using SharpMap;
216
217
  using SharpMap.Layers;
@@ -219,12 +220,9 @@ using SharpMap.Styles;
219
220
  using SharpMap.Rendering.Thematics;
220
221
  using System.Drawing;
221
222
 
222
- // 创建地图
223
- var map = new Map(new Size(1024, 768));
224
- map.SRID = 4326;
223
+ var map = new Map(new Size(1024, 768)) { SRID = 4326 };
225
224
 
226
- // 添加 Shapefile 图层
227
- var prov = new ShapeFile("countries.shp", true);
225
+ var prov = new ShapeFile("data/countries.shp", true);
228
226
  var layer = new VectorLayer("Countries", prov)
229
227
  {
230
228
  Style = new VectorStyle
@@ -235,10 +233,10 @@ var layer = new VectorLayer("Countries", prov)
235
233
  }
236
234
  };
237
235
 
238
- // 按人口设置主题样式
236
+ // 按人口分档着色(DataRowView 索引器返回 object,需显式转换)
239
237
  layer.Theme = new CustomTheme(row =>
240
238
  {
241
- var pop = (int)row["POP_EST"];
239
+ var pop = Convert.ToInt64(row["POP_EST"]);
242
240
  return new VectorStyle
243
241
  {
244
242
  Fill = new SolidBrush(pop > 100_000_000 ? Color.Red : Color.LightBlue)
@@ -246,43 +244,82 @@ layer.Theme = new CustomTheme(row =>
246
244
  });
247
245
  map.Layers.Add(layer);
248
246
 
249
- // 添加行政标注
250
- var labels = new LabelLayer("Labels")
247
+ map.Layers.Add(new LabelLayer("Labels")
251
248
  {
252
- DataSource = prov, LabelColumn = "NAME",
249
+ DataSource = prov,
250
+ LabelColumn = "NAME",
253
251
  Style = new LabelStyle { Font = new Font("Arial", 10) }
254
- };
255
- map.Layers.Add(labels);
252
+ });
256
253
 
257
- // 渲染
258
254
  map.ZoomToExtents();
259
- using var img = map.GetMap();
255
+ using var img = map.GetMap(); // System.Drawing.Image
260
256
  img.Save("output.png");
261
257
  ```
262
258
 
263
- ### 工作流 2:PostGIS 数据 + OSM 底图 + WMS 发布
259
+ ### 工作流 2:PostGIS 数据 + OSM 底图
260
+
261
+ 输入 PostGIS 表 `poi(geom, id)`,输出带在线底图的 `map_with_osm.png`。
264
262
 
265
263
  ```csharp
266
- // PostGIS 数据
267
- var pgConn = "Host=localhost;Database=gisdb;User Id=postgres;Password=pg";
264
+ using BruTile.Predefined;
265
+
266
+ // 1) OSM 底图:瓦片图层来自 SharpMap.Layers.BruTile 包
267
+ var tileSrc = KnownTileSources.Create(KnownTileSource.OpenStreetMap);
268
+ map.Layers.Add(new TileAsyncLayer(tileSrc, "OSM"));
269
+
270
+ // 2) 底图是 Web Mercator,地图 SRID 必须同步,否则矢量层整体偏移
271
+ map.SRID = 3857;
272
+
273
+ // 3) PostGIS 矢量层:连接串后依次为表名、几何列、主键列
274
+ var pgConn = "Host=localhost;Database=gisdb;User Id=postgres;Password=***";
268
275
  var poiProvider = new PostGIS(pgConn, "poi", "geom", "id");
269
276
  map.Layers.Add(new VectorLayer("POI", poiProvider)
270
277
  {
271
278
  Style = new VectorStyle { Fill = Brushes.OrangeRed }
272
279
  });
273
280
 
274
- // OSM 底图
275
- using BruTile.Predefined;
276
- var tileSrc = KnownTileSources.Create(KnownTileSource.OpenStreetMap);
277
- map.Layers.Add(new TileAsyncLayer(tileSrc, "OSM"));
278
- map.SRID = 3857;
281
+ map.ZoomToExtents();
282
+ using var img = map.GetMap();
283
+ img.Save("map_with_osm.png");
284
+ ```
285
+
286
+ ```bash
287
+ dotnet --version # 需 .NET Framework 4.7.2 工程或 net472 目标框架
288
+ dotnet add package SharpMap --version 1.2.0
289
+ dotnet add package SharpMap.UI --version 1.2.0
290
+ dotnet build # 通过后打开输出的 PNG 检查
279
291
  ```
280
292
 
281
- ## DeepSeek Harness 使用建议
293
+ **验证产物**:只有 `dotnet build` 成功不算完成——打开 `output.png`,能看到按人口分色的面、标注文字与底图瓦片才算渲染正确。
294
+
295
+ ## 最佳实践与性能建议
296
+
297
+ 1. 预建空间索引(Shapefile `.qix`、PostGIS GiST)
298
+ 2. `TileAsyncLayer` 用于在线底图
299
+ 3. 避免主线程加载大数据
300
+ 4. `LabelLayer` 启用优先级与碰撞检测
301
+ 5. 复用 `Brush/Pen/VectorStyle`
302
+
303
+ ---
304
+
305
+ ## 常见问题
306
+
307
+ | 问题 | 解决 |
308
+ |------|------|
309
+ | 无图 | 检查 SRID、`ZoomToExtents` |
310
+ | 文字模糊 | 设置高 DPI Aware、`MapBox.MapTransform` |
311
+ | GDI+ 内存泄漏 | 释放 `Brush/Pen/Bitmap` |
312
+ | Shapefile 中文乱码 | DBF 无编码声明时 SharpMap 默认按 UTF-8 解码:`var shp = new ShapeFile("roads.shp"); shp.Encoding = System.Text.Encoding.GetEncoding("GBK");`(构造函数没有 Encoding 重载) |
313
+ | 找不到 `SharpMap.UI.WinForms` 包 | 该包名在 NuGet 上不存在,WinForms 控件在 `SharpMap.UI` 包中 |
314
+ | `CoordinateTransformation` 赋值编译错误 | ProjNet 2.x 不再实现 GeoAPI 接口,改用 `ProjNet4GeoAPI` 1.4.1 |
315
+ | 找不到 `TileAsyncLayer` | 瓦片图层不在核心包中,需安装 `SharpMap.Layers.BruTile` |
316
+
317
+ ---
318
+
319
+ ## AI 使用建议
282
320
 
283
- - **加载与引用**:用 `skill("sharpmap")` 加载(用户也可输入 `/sharpmap`);示例写入会话工作区的 .NET 工程,技能目录只读。
284
321
  - **执行环境**:先 `dotnet --list-sdks`;核心包 `SharpMap` 是 netstandard2.0,可被 .NET 8+ 工程引用,但 WinForms 控件 `SharpMap.UI` 只有 .NET Framework 4.7.2,目标框架必须选 net472,不能套 net8.0。
285
- - **验证产物**:`dotnet build` 后 `map.GetMap()` 取 `System.Drawing.Image` 再 `Save("output.png")`,用 `read_image` 看实际着色与标注;编译通过不代表渲染正确。
322
+ - **验证产物**:`dotnet build` 后 `map.GetMap()` 取 `System.Drawing.Image` 再 `Save("output.png")`,打开 PNG 看实际着色与标注;编译通过不代表渲染正确。
286
323
  - **依赖风险**:SharpMap 1.2.0(2021-03)的传递依赖含 `NetTopologySuite.Core` 1.15.3、`System.Drawing.Common` 4.6.0、`System.Data.SqlClient` 4.7.0,`dotnet restore` 会报 NU1902/NU1903/NU1904 漏洞告警,需向用户说明而不是静默忽略。
287
324
  - **坐标与 SRID**:`map.SRID` 与图层 SRID 必须一致;ProjNet 2.x 不再实现 GeoAPI 接口,坐标变换用 `ProjNet4GeoAPI` 1.4.1。
288
325
  - **资源释放**:GDI+ 的 `Brush`/`Pen`/`Bitmap` 必须 `using` 或 `Dispose`,否则长时间运行内存持续上涨。
@@ -0,0 +1,358 @@
1
+ ---
2
+ name: spatialite
3
+ description: "Use when adding spatial SQL to a single-file SQLite database with SpatiaLite — mod_spatialite loading, InitSpatialMetaData, AddGeometryColumn, CreateSpatialIndex/MbrWithin, ST_Transform and GEOS predicates, spatialite_tool or ogr2ogr import of Shapefile, and GPKG fallback; also for 'no such module: mod_spatialite', 'no such function: InitSpatialMetaData', and 'the SPATIALITE_SECURITY environment variable' errors. libspatialite 5.1.0."
4
+ license: MIT
5
+ metadata:
6
+ category: gis
7
+ tags: "spatialite, sqlite, sql, gis, spatial, geospatial, python, vector, gpkg, command-line"
8
+ ---
9
+
10
+ > **项目地址:** <https://www.gaia-gis.it/fossil/libspatialite/index>
11
+ >
12
+ > **官方文档:** <https://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html>
13
+ >
14
+ > **最新版本:** libspatialite 5.1.0(2023-08-04,[源码目录](https://www.gaia-gis.it/gaia-sins/libspatialite-sources/));spatialite-tools 5.1.0a(2023-08-13,[源码目录](https://www.gaia-gis.it/gaia-sins/spatialite-tools-sources/)),截至 2026-11 仍为最新
15
+ >
16
+ > **安装包:** Debian/Ubuntu `libsqlite3-mod-spatialite` 5.1.0-3、`spatialite-bin` 5.1.0a-2;conda-forge `libspatialite` 5.1.0
17
+ >
18
+ > **许可证:** MPL-1.1 / GPL-2.0+ / LGPL-2.1+ 三许可(libspatialite);spatialite-tools 为 GPL-3.0+
19
+
20
+ ## 概述
21
+
22
+ SpatiaLite 是 SQLite 的空间扩展库。它把完整的空间 SQL 能力加进 SQLite:几何类型、空间索引、坐标转换与 OGC 关系谓词,而数据库仍然是**单个普通文件**,不需要任何服务端进程。官方把它定位为"SQLite 上的 PostGIS 替代品",适合嵌入式、桌面应用与只读发布场景。
23
+
24
+ 核心组件:
25
+
26
+ - **libspatialite**:扩展库本体,以 `mod_spatialite` 模块形式加载进 SQLite,提供 SQL 函数
27
+ - **spatialite-tools**:命令行工具集(`spatialite` shell、`spatialite_tool` 导入导出等)
28
+ - **元数据表**:`geometry_columns` 与 `spatial_ref_sys`,由 `InitSpatialMetaData` 创建
29
+ - **RTree 空间索引**:`CreateSpatialIndex` 建立并与主表触发器保持同步
30
+ - **GPKG 兼容**:同一套函数能读写 OGC GeoPackage
31
+
32
+ **与 GeoPackage 的关系:** GeoPackage 是 SQLite 表格结构的标准封装;SpatiaLite 是功能更全的扩展实现。要跨工具交换数据时优先 GPKG,要完整空间 SQL 能力时用 SpatiaLite。
33
+
34
+ ## 环境准备
35
+
36
+ ### 方式一:系统包(Debian / Ubuntu)
37
+
38
+ ```bash
39
+ # 扩展模块(Python 与 sqlite3 CLI 都用它)
40
+ sudo apt install libsqlite3-mod-spatialite
41
+
42
+ # 命令行工具(spatialite shell、spatialite_tool 等)
43
+ sudo apt install spatialite-bin
44
+
45
+ # 开发头文件(自己编译或链接 libspatialite 时需要)
46
+ sudo apt install libspatialite-dev
47
+ ```
48
+
49
+ Debian trixie 上的版本为 5.1.0,与上游一致;更老的发行版(如 bookworm 的 5.0.1)会落后一个小版本。
50
+
51
+ ### 方式二:conda / mamba
52
+
53
+ ```bash
54
+ conda install -c conda-forge libspatialite
55
+ ```
56
+
57
+ conda-forge 的 `libspatialite` 为 5.1.0,Windows / macOS / Linux 均有构建,是跨平台最省事的方式。
58
+
59
+ ### 方式三:Windows 预编译包
60
+
61
+ 官方站点提供 Windows 二进制(`mod_spatialite-x.y.z-win-x86_64.zip` 一类命名),解压后把目录加入 `PATH`,或把 `mod_spatialite.dll` 放到与 sqlite3.exe 同级的目录。用 conda 装则无需手工放置 DLL。
62
+
63
+ ### 方式四:源码编译
64
+
65
+ ```bash
66
+ curl -LO https://www.gaia-gis.it/gaia-sins/libspatialite-sources/libspatialite-5.1.0.tar.gz
67
+ tar xzf libspatialite-5.1.0.tar.gz
68
+ cd libspatialite-5.1.0
69
+ ./configure --disable-rttopo # 按需启用 GEOS/PROJ/RTTOPO 等依赖
70
+ make -j"$(nproc)"
71
+ sudo make install
72
+ sudo ldconfig
73
+ ```
74
+
75
+ 依赖链较长(SQLite、GEOS、PROJ、FreeXL、libxml2 等),没有特殊需求时优先用包管理器。
76
+
77
+ ### 验证
78
+
79
+ ```bash
80
+ # 1) 库文件是否存在
81
+ ls /usr/lib/x86_64-linux-gnu/mod_spatialite.so # Linux
82
+ # Windows 下为 mod_spatialite.dll,macOS 下为 mod_spatialite.dylib
83
+
84
+ # 2) CLI 能否加载扩展并报出版本
85
+ spatialite :memory: "SELECT spatialite_version();"
86
+
87
+ # 3) Python 侧能否加载
88
+ python -c "import sqlite3; c=sqlite3.connect(':memory:'); c.enable_load_extension(True); c.load_extension('mod_spatialite'); print(c.execute('SELECT spatialite_version()').fetchone())"
89
+ ```
90
+
91
+ 三条任一失败,先解决加载问题再写 SQL。
92
+
93
+ ## 核心 API
94
+
95
+ ### 加载扩展
96
+
97
+ ```bash
98
+ # CLI:进入 shell 后加载
99
+ spatialite mydb.sqlite
100
+ spatialite> .load mod_spatialite
101
+
102
+ # CLI:一次性执行(把扩展加载与 SQL 放在同一次调用里)
103
+ spatialite mydb.sqlite -cmd ".load mod_spatialite" "SELECT spatialite_version();"
104
+ ```
105
+
106
+ ```python
107
+ import sqlite3
108
+
109
+ con = sqlite3.connect("mydb.sqlite")
110
+ con.enable_load_extension(True) # Python 3.10+ 需要显式开启
111
+ con.load_extension("mod_spatialite") # 找不到时传绝对路径
112
+ con.enable_load_extension(False)
113
+
114
+ print(con.execute("SELECT spatialite_version()").fetchone())
115
+ ```
116
+
117
+ ### 初始化空间元数据
118
+
119
+ 每个数据库**只需执行一次**:
120
+
121
+ ```sql
122
+ -- 创建 geometry_columns 与 spatial_ref_sys(1 = 成功)
123
+ SELECT InitSpatialMetaData(1);
124
+
125
+ -- 只要 WGS84 相关 SRID,体积更小
126
+ SELECT InitSpatialMetaData(1, 'WGS84');
127
+
128
+ -- 完全不插入 EPSG 定义(自己管理 SRID)
129
+ SELECT InitSpatialMetaData(1, 'NONE');
130
+ ```
131
+
132
+ 返回 1 表示创建成功;对已初始化的库重复调用会返回 0,不会破坏数据。
133
+
134
+ ### 建表并声明几何列
135
+
136
+ 先建普通表,再用 `AddGeometryColumn` 注册几何列(不要手写 geometry 列):
137
+
138
+ ```sql
139
+ CREATE TABLE poi (
140
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
141
+ name TEXT
142
+ );
143
+
144
+ SELECT AddGeometryColumn('poi', 'geom', 4326, 'POINT', 'XY');
145
+
146
+ INSERT INTO poi (name, geom)
147
+ VALUES ('tiananmen', MakePoint(116.397, 39.908, 4326)),
148
+ ('waitan', MakePoint(121.490, 31.241, 4326));
149
+ ```
150
+
151
+ `AddGeometryColumn` 会同时建触发器,保证写入的几何类型与 SRID 与声明一致。
152
+
153
+ ### 空间索引
154
+
155
+ ```sql
156
+ -- 建 RTree 索引(自动创建同步触发器)
157
+ SELECT CreateSpatialIndex('poi', 'geom');
158
+
159
+ -- 校验索引一致性;参数省略时检查全部
160
+ SELECT CheckSpatialIndex('poi', 'geom');
161
+
162
+ -- 更新图层统计信息(要素数与总范围)
163
+ SELECT UpdateLayerStatistics('poi', 'geom');
164
+
165
+ -- 需要停用时
166
+ -- SELECT DisableSpatialIndex('poi', 'geom');
167
+ ```
168
+
169
+ ### 常用空间函数
170
+
171
+ | 类别 | 函数 | 说明 |
172
+ |------|------|------|
173
+ | 构造 | MakePoint(x, y [, srid]) | 构造点 |
174
+ | 构造 | GeomFromText(wkt [, srid]) / ST_GeomFromText | WKT 转几何 |
175
+ | 输出 | AsText(geom) / ST_AsText | 几何转 WKT |
176
+ | 输出 | AsBinary(geom) / AsGeoJSON(geom) | WKB / GeoJSON |
177
+ | 谓词 | ST_Intersects / ST_Contains / ST_Within / ST_Touches / ST_Crosses / ST_Disjoint | OGC 关系 |
178
+ | 谓词 | MbrWithin / MbrIntersects / MbrDisjoint | 仅比较包围盒,最快 |
179
+ | 度量 | ST_Area / ST_Length / ST_Distance / ST_Perimeter | 平面度量(单位随 SRID) |
180
+ | 运算 | ST_Buffer / ST_Intersection / ST_Union / ST_Difference / ST_ConvexHull | GEOS 运算 |
181
+ | 转换 | ST_Transform(geom, srid) | 坐标转换(需 PROJ) |
182
+ | 修复 | ST_MakeValid / GeosMakeValid / ST_IsValid | 无效几何处理 |
183
+
184
+ ```sql
185
+ -- 5 公里内的点(先用 MBR 粗筛走索引,再精算距离)
186
+ SELECT a.name, b.name, ST_Distance(a.geom, b.geom) AS deg
187
+ FROM poi a, poi b
188
+ WHERE a.id < b.id
189
+ AND MbrWithin(b.geom, ST_Buffer(a.geom, 0.05))
190
+ AND ST_Distance(a.geom, b.geom) < 0.05;
191
+
192
+ -- 投影到米制后再算距离,避免"度"当"米"
193
+ SELECT ST_Distance(ST_Transform(a.geom, 3857), ST_Transform(b.geom, 3857)) AS meters
194
+ FROM poi a, poi b
195
+ WHERE a.id = 1 AND b.id = 2;
196
+ ```
197
+
198
+ ### 元数据与图层信息
199
+
200
+ ```sql
201
+ -- 库里有哪些几何列
202
+ SELECT f_table_name, f_geometry_column, geometry_type, srid, spatial_index_enabled
203
+ FROM geometry_columns;
204
+
205
+ -- 某图层的包围盒
206
+ SELECT ST_AsText(ST_Envelope(ST_Collect(geom))) FROM poi;
207
+ ```
208
+
209
+ ## 典型工作流:Shapefile → SpatiaLite → 空间查询 → 导出
210
+
211
+ 输入 `data/roads.shp` 与 `data/cities.shp`,目标是找出每条道路 2 公里内的城市并导出结果表。
212
+
213
+ **步骤 1:导入(两种方式任选)**
214
+
215
+ ```bash
216
+ # 方式 A:spatialite_tool(参数随版本略有差异,先跑 --help 确认)
217
+ spatialite_tool --help
218
+
219
+ # 方式 B:ogr2ogr(GDAL,最稳定,强烈推荐)
220
+ ogr2ogr -f SQLite -dsco SPATIALITE=YES out.gis.sqlite data/roads.shp -nln roads
221
+ ogr2ogr -f SQLite -dsco SPATIALITE=YES -append out.gis.sqlite data/cities.shp -nln cities
222
+ ```
223
+
224
+ `-dsco SPATIALITE=YES` 让 GDAL 按 SpatiaLite 格式写库(而不是纯 SQLite 表);导入后 GDAL 会建好元数据与索引。
225
+
226
+ **步骤 2:初始化并核对**
227
+
228
+ ```python
229
+ import sqlite3
230
+
231
+ con = sqlite3.connect("out.gis.sqlite")
232
+ con.enable_load_extension(True)
233
+ con.load_extension("mod_spatialite")
234
+ con.enable_load_extension(False)
235
+
236
+ # 若库是新建的空库,先执行一次
237
+ # con.execute("SELECT InitSpatialMetaData(1)")
238
+
239
+ for row in con.execute("""
240
+ SELECT f_table_name, f_geometry_column, geometry_type, srid, spatial_index_enabled
241
+ FROM geometry_columns
242
+ """):
243
+ print(row)
244
+ ```
245
+
246
+ **步骤 3:空间查询**
247
+
248
+ ```python
249
+ rows = con.execute("""
250
+ SELECT r.name AS road, c.name AS city,
251
+ ST_Distance(ST_Transform(r.geom, 3857),
252
+ ST_Transform(c.geom, 3857)) AS meters
253
+ FROM roads r
254
+ JOIN cities c
255
+ ON MbrWithin(c.geom, ST_Buffer(r.geom, 0.02))
256
+ AND ST_Distance(r.geom, c.geom) < 0.02
257
+ ORDER BY meters
258
+ """).fetchall()
259
+ print(len(rows), "pairs")
260
+ ```
261
+
262
+ **步骤 4:导出结果**
263
+
264
+ ```python
265
+ con.execute("""
266
+ CREATE TABLE road_city AS
267
+ SELECT r.name AS road, c.name AS city,
268
+ ST_Distance(ST_Transform(r.geom, 3857),
269
+ ST_Transform(c.geom, 3857)) AS meters
270
+ FROM roads r
271
+ JOIN cities c
272
+ ON MbrWithin(c.geom, ST_Buffer(r.geom, 0.02))
273
+ AND ST_Distance(r.geom, c.geom) < 0.02
274
+ """)
275
+ con.commit()
276
+ print(con.execute("SELECT count(*) FROM road_city").fetchone())
277
+ ```
278
+
279
+ ```bash
280
+ # 用 GDAL 把结果导成 GeoPackage / GeoJSON
281
+ ogr2ogr -f GPKG out/road_city.gpkg out.gis.sqlite road_city
282
+ ```
283
+
284
+ **步骤 5:验收**
285
+
286
+ ```bash
287
+ ogrinfo -so out/road_city.gpkg road_city | head -20
288
+ ```
289
+
290
+ 确认要素数、几何类型与 SRID 与预期一致。
291
+
292
+ ## 与 Python 生态配合
293
+
294
+ ```python
295
+ import sqlite3
296
+ import geopandas as gpd
297
+
298
+ con = sqlite3.connect("out.gis.sqlite")
299
+ con.enable_load_extension(True)
300
+ con.load_extension("mod_spatialite")
301
+ con.enable_load_extension(False)
302
+
303
+ # 读成 GeoDataFrame(GeoPandas 走 pyogrio/GDAL,会自动识别 SpatiaLite)
304
+ gdf = gpd.read_file("out.gis.sqlite", layer="cities")
305
+
306
+ # 用 SQL 结果再构造 GeoDataFrame
307
+ rows = con.execute("SELECT name, AsText(geom) FROM cities").fetchall()
308
+ print(rows[:3])
309
+ ```
310
+
311
+ 注意:GeoPandas 读 SpatiaLite 依赖 GDAL 的 SQLite 驱动;写回时用 `gdf.to_file("out.gis.sqlite", layer="new_layer", driver="SQLite")` 即可。
312
+
313
+ ## 最佳实践
314
+
315
+ 1. **几何列一定用 AddGeometryColumn 建**:手写 geometry 列会绕过元数据与触发器,后续空间函数找不到列。
316
+ 2. **InitSpatialMetaData 只跑一次**:新库初始化后不要重复执行;用 `'WGS84'` 模式可以显著缩小 spatial_ref_sys。
317
+ 3. **先 MBR 粗筛再精算**:`MbrWithin` / `MbrIntersects` 能吃到 RTree 索引,直接对全部行跑 ST_Distance 会很慢。
318
+ 4. **SRID 必须一致**:不同 SRID 的几何不能直接比较,先 `ST_Transform` 统一。
319
+ 5. **单位意识**:4326 下 ST_Distance 返回"度"、ST_Area 返回"平方度";要米就投到米制投影(如 3857)。
320
+ 6. **空间索引用 CheckSpatialIndex 体检**:批量导入或大量 UPDATE 之后跑一次,确认索引与主表同步。
321
+ 7. **交换数据优先 GPKG**:SpatiaLite 专有函数多,跨工具可移植性不如 GeoPackage。
322
+ 8. **写事务要提交**:Python 里 `con.commit()`,否则 `CreateSpatialIndex` 的触发器与数据都不落盘。
323
+
324
+ ## 常见问题
325
+
326
+ | 问题 | 原因 | 解决方案 |
327
+ |------|------|---------|
328
+ | no such function: InitSpatialMetaData | 扩展未加载,或加载的是空壳库 | 先 `.load mod_spatialite`(CLI)或 `load_extension("mod_spatialite")`(Python),用 `spatialite_version()` 验证 |
329
+ | no such module: mod_spatialite | 动态库不在搜索路径 | 指定绝对路径加载;Linux 装 `libsqlite3-mod-spatialite`,Windows 把 DLL 放同目录或加 PATH |
330
+ | Python 报 "not authorized" / 无法 enable_load_extension | 解释器禁用了扩展加载 | 用系统 Python 或开启 `--enable-loadable-sqlite-extensions` 的构建;PyPI 的 `pysqlite3-binary` 可用于替换 |
331
+ | CLI 里 `.load` 报加载失败 | 动态库路径不对,或 shell 与库的位数/构建不匹配 | 先用 `python -c` 那条验证库本身可加载,再在 CLI 里给绝对路径;仍失败时改用 Python 或 GDAL 路径 |
332
+ | CreateSpatialIndex 返回 -1 | 表里存在名为 rowid 的物理列,遮蔽了真实 ROWID | 重命名该列后再建索引 |
333
+ | ST_Intersects 报 "geometry has invalid SRID" | 混入了 SRID 为 -1 或 0 的几何 | 用 `GeomFromText(wkt, 4326)` 或 `ST_Transform` 赋上正确 SRID |
334
+ | 空间查询依旧很慢 | 只用了 ST_Distance,没有 MBR 前置条件 | 先加 `MbrWithin` 或 `MbrIntersects` 条件让 RTree 生效,再精确判断 |
335
+ | apt 装的版本比官网旧 | 发行版冻结版本 | 需要 5.1.0 特性时用 conda-forge,或从源码编译 |
336
+ | 用 GDAL 打开 SQLite 库看不到图层 | 库不是 SpatiaLite 格式 | 导入时加 `-dsco SPATIALITE=YES`;已存在的库可用 GDAL 的 `SQLite` 驱动按层读取 |
337
+
338
+ ## AI 使用建议
339
+
340
+ - **先确认库能被加载**:任何排查都从 `python -c "import sqlite3; c=sqlite3.connect(':memory:'); c.enable_load_extension(True); c.load_extension('mod_spatialite')"` 开始;库加载不了时,SQL 报错没有诊断价值。
341
+ - **版本差异**:SpatiaLite 5.x 的函数集与 4.x 不同(如 `GeosMakeValid`、`InitSpatialMetaData` 的重载)。动手前查 `spatialite_version()`,并按官方函数参考核对函数名与参数。
342
+ - **优先用 ogr2ogr 导入**:命令行工具的参数在不同构建间不一致,GDAL 的 `-dsco SPATIALITE=YES` 路径最稳定;确需 `spatialite_tool` 时先跑 `--help` 核对参数。
343
+ - **验证产物**:导入或建索引后回读 `geometry_columns`(几何列、SRID、spatial_index_enabled)与 `CheckSpatialIndex(`…`)`,确认索引真的生效,再宣称"查询已优化"。
344
+ - **写操作确认**:`DROP TABLE`、`DisableSpatialIndex`、批量 `DELETE` 不可回滚到旧状态(SQLite 事务只保护单次会话);执行前备份 .sqlite 文件。
345
+
346
+ ## 相关技能
347
+
348
+ - **postgis** — 服务端空间数据库,能力更完整:[../postgis/SKILL.md](../postgis/SKILL.md)
349
+ - **gdal** — ogr2ogr 导入导出,事实上的稳定路径:[../gdal/SKILL.md](../gdal/SKILL.md)
350
+ - **geopandas** — Python 侧读写 SpatiaLite/GPKG:[../geopandas/SKILL.md](../geopandas/SKILL.md)
351
+ - **duckdb-spatial** — 另一种嵌入式空间分析方案:[../duckdb-spatial/SKILL.md](../duckdb-spatial/SKILL.md)
352
+ - **proj** — ST_Transform 依赖的坐标转换库:[../proj/SKILL.md](../proj/SKILL.md)
353
+
354
+ ## 参考资源
355
+ - 官方主页(fossil 仓库):<https://www.gaia-gis.it/fossil/libspatialite/index>
356
+ - SQL 函数参考:<https://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html>
357
+ - spatialite-tools:<https://www.gaia-gis.it/fossil/spatialite-tools/index>
358
+ - GeoPackage 标准:<https://www.geopackage.org/>