crossbind
GitHub
← 所有库

SpatiaLite

SQLite 的空间 SQL 扩展。

安装

在浏览器中运行;Node.js 和边缘运行环境也使用同一个包。构建目标:wasm32,单线程和多线程。

shell
npm install @crossbind/port-spatialite-wasm@beta
crossbind.config.js
import spatialiteWasm from '@crossbind/port-spatialite-wasm/crossbind.config.js';
 
export default {
dependencies: [spatialiteWasm],
paths: { config: import.meta.url },
};
main.js
import { initNative, spatialite_version } from '@crossbind/port-spatialite/spatialite.h';
 
await initNative();

crossbind 本身随你的打包工具插件一起提供;打包工具插件介绍了 Vite、Webpack、Rspack、Rsbuild、Rollup、esbuild、Bun 和 Next.js 的用法。

在浏览器中运行 SpatiaLite:空间 SQL、路径规划和 GeoPackage,无需服务器

SpatiaLite 为 SQLite 加入了 PostGIS 风格的空间 SQL:在一个数据库文件中实现空间索引、连接、重投影和路径规划。这些应用运行由 crossbind 与 GEOS、PROJ 和 SQLite 一起编译的 SpatiaLite 5.1.0:一个能把每个查询的返回结果绘制出来的 SQL 演练场,一个能绕开你所封闭街道的最短路径功能,以及一个 GDAL 和 QGIS 都能打开的 GeoPackage。ST_Transform 读取的 PROJ 数据库占下载内容中的 10.2 MB。这个构建没有包含 RTTOPO,因为它会让 SpatiaLite 只能以 GPL 许可证使用,所以这里的 ST_MakeValid 就是 GeosMakeValid。 首次运行时会下载一次 23.8 MB 的 WebAssembly;本页的所有应用都共用它,而且不会上传任何内容。

应用 01

空间 SQL,结果直接绘制成地图

在这个标签页中的 SpatiaLite 数据库里运行 PostGIS 风格的 SQL,数据是围绕土耳其十二座城市生成的 2,000 个兴趣点。选择一个查询或自己编写:通过 R*Tree 索引进行空间连接,用 KNN2 查找最近邻,用 ST_Union 合并缓冲区,生成 Voronoi 单元,以及转换到 UTM。查询返回的每个几何对象都会绘制在它的行上方。

查询
表:pois (id, kind, city, geom)、hexagons (id, geom) 和 cities (id, name, geom),全部使用 EPSG:4326,pois 和 hexagons 上建有空间索引。
运行 SpatiaLite(可任选 MPL-1.1、GPL-2.0+ 或 LGPL-2.1+ 许可证),以及采用 LGPL 许可证的 GEOS 和 GNU libiconv: 源代码 · 许可证 · 构建配方
运行一个查询,查看它的行并绘制它的几何对象。
查看代码
src/native/spatial_playground.h
// src/native/spatial_playground.h (excerpt)
SpatialPlayground() : connection(":memory:") {
// spatial::Connection opened SQLite, then called spatialite_alloc_connection
// and spatialite_init_ex; the sample SQL runs InitSpatialMetaData(1),
// creates cities, pois and hexagons and calls CreateSpatialIndex
spatial::exec(connection.get(), sample::PLAYGROUND);
}
 
std::string run(const std::string& sql, int limit) {
// ...
while (rest < end) { // every statement in turn
sqlite3_prepare_v2(db, rest, static_cast<int>(end - rest), &raw, &rest);
// ...
if (sqlite3_column_count(raw) > 0) rows = writer.rows(raw, limit);
}
// ...
}
 
// src/support/spatial_sql.h: a geometry cell goes back as GeoJSON
geometry(prepare(db, "SELECT AsGeoJSON(?1, 6), GeometryType(?1), SRID(?1)"))
main.js
const m = await initNative();
const playground = await new m.SpatialPlayground();
const result = JSON.parse(await playground.run(`
SELECT h.id, count(*) AS pois, h.geom
FROM hexagons AS h JOIN pois AS p ON p.ROWID IN (
SELECT ROWID FROM SpatialIndex
WHERE f_table_name = 'pois' AND search_frame = h.geom)
AND ST_Contains(h.geom, p.geom)
GROUP BY h.id ORDER BY pois DESC, h.id`, 2000));
// result.total: 53 hexagons with points
// result.rows[0]: [164, 497, { geometry: { type: 'Polygon', ... }, type: 'POLYGON', srid: 4326 }]
应用 02

用 SQL 计算最短路径,绕开你封闭的街道

CreateRouting 把一张街道表变成路网,对它执行 SELECT 就能返回最短路径。这个网格有 400 个路口和 718 条双向街道,每条街道需要 1 到 2 分钟;街道颜色越深,通行越慢。点击两个路口即可在它们之间规划路线,点击一条街道即可封闭它:SpatiaLite 会重建路网并再次运行查询,这一切都在这个标签页的 SQLite 中完成。

第一条路线从左下角通往右上角。
实线是按通行时间计算的最快路线;虚线是经过街道最少的路线。已封闭的街道显示为细虚线。
运行 SpatiaLite(可任选 MPL-1.1、GPL-2.0+ 或 LGPL-2.1+ 许可证),以及采用 LGPL 许可证的 GEOS 和 GNU libiconv: 源代码 · 许可证 · 构建配方
先规划路线来绘制街道网格,然后点击路口和街道。
查看代码
src/native/route_planner.h
// src/native/route_planner.h (excerpt)
// the open streets go into roads, a table with a LINESTRING column; then
build("SELECT CreateRouting('roads_data', 'roads_net', 'roads', 'node_from', 'node_to', "
"'geom', 'cost', NULL, 1, 1, NULL, NULL, 1)");
 
std::string route(int from, int to, bool fewest) {
// the VirtualRouting table takes only NodeFrom and NodeTo in WHERE
const auto query = spatial::prepare(db, fewest ? "SELECT ... FROM hops_net WHERE NodeFrom = ?1 AND NodeTo = ?2"
: "SELECT RouteRow, Role, LinkRowid, NodeFrom, NodeTo, Cost FROM roads_net WHERE NodeFrom = ?1 AND NodeTo = ?2");
sqlite3_bind_int(query.get(), 1, from);
sqlite3_bind_int(query.get(), 2, to);
return spatial::ResultWriter(db).rows(query.get(), 1000);
}
main.js
const m = await initNative();
const planner = await new m.RoutePlanner();
const route = JSON.parse(await planner.route(1, 400, false));
// route.rows[0]: [0, 'Route', null, 1, 400, 47.5], 47.5 minutes in all
// route.rows.length - 1: 38 streets, one row each: [n, 'Link', street, from, to, minutes]
 
await planner.closeStreets('[381, 401, 39]'); // CreateRouting runs again without them
JSON.parse(await planner.route(1, 400, false)).rows[0][5]; // 47.75
应用 03

在此标签页中写出 QGIS 和 GDAL 都能打开的 GeoPackage

GeoPackage 是 OGC 制定的单文件矢量数据格式,GDAL 和 QGIS 可以直接打开。这个应用用 SpatiaLite 的 gpkg 函数写出一个 GeoPackage,内容包括生成的点、每个六边形中的点数,以及你在地图上放置的标记,然后再次打开这个文件进行检查。它写出的文件能通过 GDAL 的 validate_gpkg.py 检查。在你下载之前,任何内容都不会离开这个标签页。

图层
pins:点击地图放置一些标记
运行 SpatiaLite(可任选 MPL-1.1、GPL-2.0+ 或 LGPL-2.1+ 许可证),以及采用 LGPL 许可证的 GEOS 和 GNU libiconv: 源代码 · 许可证 · 构建配方
构建文件以查看地图,然后在地图上放置标记并重新构建。
查看代码
src/native/geopackage_builder.h
// src/native/geopackage_builder.h (excerpt)
spatial::Connection connection(path); // a new file in /memfs
spatial::exec(db, "SELECT gpkgCreateBaseTables()");
// ...two fixes GDAL's validate_gpkg.py asks for, then one layer:
spatial::exec(db, "CREATE TABLE pins (fid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)");
// ...registered in gpkg_contents first, then
spatial::exec(db, "SELECT gpkgAddGeometryColumn('pins', 'geom', 'POINT', 0, 0, 4326)");
spatial::exec(db, "SELECT gpkgAddGeometryTriggers('pins', 'geom')");
spatial::exec(db, "SELECT gpkgAddSpatialIndex('pins', 'geom')");
// the pins arrive as JSON: [{ name, lon, lat }, ...]
"INSERT INTO pins (name, geom) SELECT json_extract(value, '$.name'), "
"gpkgMakePoint(json_extract(value, '$.lon'), json_extract(value, '$.lat'), 4326) FROM json_each(?1)"
main.js
const m = await initNative();
const path = `${await m.getRandomPath('/memfs')}/field.gpkg`;
const pins = [{ name: 'Meeting point', lon: 29, lat: 41 }, { name: 'Camp', lon: 32.5, lat: 39.5 }];
const report = JSON.parse(await m.GeoPackageBuilder.build(path, true, true, JSON.stringify(pins)));
// report.check: 1, CheckGeoPackageMetaData()
// report.layers: hexbins 53 polygons, pins 2 points, pois 2,000 points, all epsg:4326
const bytes = await m.getFileBytes(path); // the .gpkg QGIS and GDAL open

示例

每个示例都由一个小小的 C++ 头文件和调用它的 JavaScript 组成,并附有构建本站时它输出的内容。仅 JavaScript 标签页直接使用 SpatiaLite 自己的头文件完成同样的事,不需要 C++ 文件。最后一个是为 WASI 构建的完整 C++ 程序。

存储点并测量它们之间的距离

每个 SpatiaLite 程序开头都会用到的调用:spatialite_alloc_connection 和 spatialite_init_ex 在 SQLite 连接上注册空间 SQL 函数,InitSpatialMetaData 创建元数据表,AddGeometryColumn 添加一个几何列。GeomFromText 读取 WKT,ST_Distance(a, b, 1) 则在 WGS 84 椭球体上进行测量。

src/native/spatial_database.h
#pragma once
 
// spatialite.h uses SQLite's types without including sqlite3.h, so sqlite3.h comes first.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <stdexcept>
#include <string>
 
// An in-memory SQLite database with SpatiaLite's spatial SQL functions registered on it.
class SpatialDatabase {
public:
SpatialDatabase() {
if (sqlite3_open(":memory:", &handle) != SQLITE_OK) throw std::runtime_error("cannot open the database");
cache = spatialite_alloc_connection();
spatialite_init_ex(handle, cache, 0);
}
 
~SpatialDatabase() {
sqlite3_close(handle);
spatialite_cleanup_ex(cache);
}
 
static std::string version() { return spatialite_version(); }
 
void exec(const std::string& sql) {
char* message = nullptr;
if (sqlite3_exec(handle, sql.c_str(), nullptr, nullptr, &message) == SQLITE_OK) return;
const std::string reason = message ? message : sqlite3_errmsg(handle);
sqlite3_free(message);
throw std::runtime_error(reason);
}
 
// The first column of the first row as text, or "" when the query returns no row.
std::string scalar(const std::string& sql) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(handle, sql.c_str(), -1, &statement, nullptr) != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(handle));
const int step = sqlite3_step(statement);
const unsigned char* text = step == SQLITE_ROW ? sqlite3_column_text(statement, 0) : nullptr;
const std::string value = text ? reinterpret_cast<const char*>(text) : "";
const std::string error = step == SQLITE_ROW || step == SQLITE_DONE ? "" : sqlite3_errmsg(handle);
sqlite3_finalize(statement);
if (!error.empty()) throw std::runtime_error(error);
return value;
}
 
private:
sqlite3* handle = nullptr;
void* cache = nullptr;
};
main.js
import { initNative, SpatialDatabase } from './native/spatial_database.h';
 
await initNative();
const db = await new SpatialDatabase();
await db.exec(`
SELECT InitSpatialMetaData(1, 'WGS84');
CREATE TABLE cities (name TEXT NOT NULL);
SELECT AddGeometryColumn('cities', 'geom', 4326, 'POINT', 'XY');
INSERT INTO cities (name, geom) VALUES
('Istanbul', GeomFromText('POINT(28.9784 41.0082)', 4326)),
('Ankara', GeomFromText('POINT(32.8597 39.9334)', 4326)),
('Izmir', GeomFromText('POINT(27.1428 38.4237)', 4326));
`);
console.log(await SpatialDatabase.version(), await db.scalar('SELECT count(*) FROM cities'));
console.log(await db.scalar(`
SELECT group_concat(name || ' ' || km || ' km', ', ' ORDER BY km)
FROM (SELECT name, CAST(Round(ST_Distance(geom, MakePoint(28.9784, 41.0082, 4326), 1) / 1000) AS INTEGER) AS km FROM cities)
`));
输出首次运行需下载 23.8 MB
5.1.0 3
Istanbul 0 km, Izmir 327 km, Ankara 350 km

用空间索引找出地图视图中的地点和最近的地点

CreateSpatialIndex 为几何列的边界框维护一棵 R*Tree,查询通过虚拟表访问它:SpatialIndex 返回位于某个框(例如地图视图)内的行,KNN2 则返回离某个点最近的行及其以米为单位的距离。

src/native/place_index.h
#pragma once
 
// spatialite.h uses SQLite's types without including sqlite3.h, so sqlite3.h comes first.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <memory>
#include <stdexcept>
#include <string>
 
// Places in a SpatiaLite table with a spatial index: CreateSpatialIndex keeps an R*Tree of every
// geometry's bounding box, and queries reach it through the SpatialIndex and KNN2 virtual tables.
class PlaceIndex {
public:
PlaceIndex() {
if (sqlite3_open(":memory:", &db) != SQLITE_OK) throw std::runtime_error("cannot open the database");
cache = spatialite_alloc_connection();
spatialite_init_ex(db, cache, 0);
run("SELECT InitSpatialMetaData(1, 'WGS84')");
run("CREATE TABLE places (id INTEGER PRIMARY KEY, name TEXT NOT NULL)");
run("SELECT AddGeometryColumn('places', 'geom', 4326, 'POINT', 'XY')");
run("SELECT CreateSpatialIndex('places', 'geom')");
}
 
~PlaceIndex() {
sqlite3_close(db);
spatialite_cleanup_ex(cache);
}
 
int add(const std::string& name, double lon, double lat) {
Statement insert = prepare("INSERT INTO places (name, geom) VALUES (?1, MakePoint(?2, ?3, 4326))");
sqlite3_bind_text(insert.get(), 1, name.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_double(insert.get(), 2, lon);
sqlite3_bind_double(insert.get(), 3, lat);
if (sqlite3_step(insert.get()) != SQLITE_DONE) throw std::runtime_error(sqlite3_errmsg(db));
return static_cast<int>(sqlite3_last_insert_rowid(db));
}
 
// The places inside a longitude/latitude box, by name: the rows the R*Tree finds in the box.
std::string inView(double west, double south, double east, double north) {
Statement query = prepare(
"SELECT name FROM places WHERE ROWID IN (SELECT ROWID FROM SpatialIndex "
"WHERE f_table_name = 'places' AND search_frame = BuildMbr(?1, ?2, ?3, ?4, 4326)) ORDER BY name");
sqlite3_bind_double(query.get(), 1, west);
sqlite3_bind_double(query.get(), 2, south);
sqlite3_bind_double(query.get(), 3, east);
sqlite3_bind_double(query.get(), 4, north);
return lines(query.get());
}
 
// The `count` places nearest to a point, with their distance on the WGS 84 ellipsoid. KNN2 ranks
// the places inside a square of plus or minus `radius` degrees around the point, so the radius
// has to reach the farthest of them.
std::string nearest(double lon, double lat, int count, double radius) {
Statement query = prepare(
"SELECT p.name || ' ' || CAST(Round(k.distance_m / 1000) AS INTEGER) || ' km' FROM KNN2 AS k "
"JOIN places AS p ON p.id = k.fid WHERE k.f_table_name = 'places' "
"AND k.ref_geometry = MakePoint(?1, ?2, 4326) AND k.radius = ?3 AND k.max_items = ?4 ORDER BY k.pos");
sqlite3_bind_double(query.get(), 1, lon);
sqlite3_bind_double(query.get(), 2, lat);
sqlite3_bind_double(query.get(), 3, radius);
sqlite3_bind_int(query.get(), 4, count);
return lines(query.get());
}
 
private:
using Statement = std::unique_ptr<sqlite3_stmt, int (*)(sqlite3_stmt*)>;
 
Statement prepare(const char* sql) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nullptr) != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(db));
return Statement(statement, sqlite3_finalize);
}
 
void run(const char* sql) {
char* message = nullptr;
if (sqlite3_exec(db, sql, nullptr, nullptr, &message) == SQLITE_OK) return;
const std::string reason = message ? message : sqlite3_errmsg(db);
sqlite3_free(message);
throw std::runtime_error(reason);
}
 
// The first column of every row, joined with commas.
std::string lines(sqlite3_stmt* statement) {
std::string joined;
int result;
while ((result = sqlite3_step(statement)) == SQLITE_ROW) {
joined += (joined.empty() ? "" : ", ") + std::string(reinterpret_cast<const char*>(sqlite3_column_text(statement, 0)));
}
if (result != SQLITE_DONE) throw std::runtime_error(sqlite3_errmsg(db));
return joined;
}
 
sqlite3* db = nullptr;
void* cache = nullptr;
};
main.js
import { initNative, PlaceIndex } from './native/place_index.h';
 
await initNative();
const places = await new PlaceIndex();
const cities = [
['Istanbul', 28.9784, 41.0082],
['Ankara', 32.8597, 39.9334],
['Izmir', 27.1428, 38.4237],
['Bursa', 29.061, 40.1885],
['Antalya', 30.7133, 36.8969],
['Trabzon', 39.7168, 41.0027],
['Konya', 32.4846, 37.8746],
['Edirne', 26.5557, 41.6771],
];
for (const [name, lon, lat] of cities) await places.add(name, lon, lat);
console.log(await places.inView(26, 38, 31, 42));
const eskisehir = [30.5206, 39.7767];
console.log(await places.nearest(...eskisehir, 3, 5));
输出首次运行需下载 23.8 MB
Bursa, Edirne, Istanbul, Izmir
Bursa 133 km, Istanbul 189 km, Ankara 201 km

以米为单位测量面积和距离

SpatiaLite 以坐标的单位进行测量,所以经纬度多边形的 ST_Area 结果以平方度为单位。用 ST_Transform 转换到投影 CRS(这里是 UTM 35N 带,EPSG:32635)后,就能得到平方米和米,但形状离该带越远,结果被拉伸得越厉害;ST_Distance(a, b, 1) 则完全不经过投影,直接在椭球体上测量。

src/native/measure.h
#pragma once
 
// spatialite.h uses SQLite's types without including sqlite3.h, so sqlite3.h comes first.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <memory>
#include <stdexcept>
#include <string>
 
// Measurements of shapes written as WKT in longitude and latitude (EPSG:4326). SpatiaLite measures
// in the units of the coordinates, so the planar methods first transform the shape to the CRS they
// are given: a projected one such as UTM measures in metres.
class Measure {
public:
Measure() {
if (sqlite3_open(":memory:", &db) != SQLITE_OK) throw std::runtime_error("cannot open the database");
cache = spatialite_alloc_connection();
spatialite_init_ex(db, cache, 0);
char* message = nullptr;
if (sqlite3_exec(db, "SELECT InitSpatialMetaData(1, 'WGS84')", nullptr, nullptr, &message) == SQLITE_OK) return;
const std::string reason = message ? message : sqlite3_errmsg(db);
sqlite3_free(message);
throw std::runtime_error(reason);
}
 
~Measure() {
sqlite3_close(db);
spatialite_cleanup_ex(cache);
}
 
double area(const std::string& wkt, int srid) {
Statement query = prepare("SELECT ST_Area(ST_Transform(GeomFromText(?1, 4326), ?2))");
sqlite3_bind_text(query.get(), 1, wkt.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(query.get(), 2, srid);
return number(query.get());
}
 
double distance(const std::string& a, const std::string& b, int srid) {
Statement query = prepare("SELECT ST_Distance(ST_Transform(GeomFromText(?1, 4326), ?3), ST_Transform(GeomFromText(?2, 4326), ?3))");
sqlite3_bind_text(query.get(), 1, a.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(query.get(), 2, b.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(query.get(), 3, srid);
return number(query.get());
}
 
// On the WGS 84 ellipsoid, in metres, with no projection in between.
double geodesicDistance(const std::string& a, const std::string& b) {
Statement query = prepare("SELECT ST_Distance(GeomFromText(?1, 4326), GeomFromText(?2, 4326), 1)");
sqlite3_bind_text(query.get(), 1, a.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(query.get(), 2, b.c_str(), -1, SQLITE_TRANSIENT);
return number(query.get());
}
 
private:
using Statement = std::unique_ptr<sqlite3_stmt, int (*)(sqlite3_stmt*)>;
 
Statement prepare(const char* sql) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nullptr) != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(db));
return Statement(statement, sqlite3_finalize);
}
 
// SpatiaLite answers NULL, not an error, for WKT it cannot read or an SRID it does not know.
double number(sqlite3_stmt* statement) {
if (sqlite3_step(statement) != SQLITE_ROW) throw std::runtime_error(sqlite3_errmsg(db));
if (sqlite3_column_type(statement, 0) == SQLITE_NULL) throw std::invalid_argument("cannot measure: check the WKT and the SRID");
return sqlite3_column_double(statement, 0);
}
 
sqlite3* db = nullptr;
void* cache = nullptr;
};
main.js
import { initNative, Measure } from './native/measure.h';
 
await initNative();
const measure = await new Measure();
const block = 'POLYGON((28.97 41.00, 28.99 41.00, 28.99 41.01, 28.97 41.01, 28.97 41.00))';
console.log(`${(await measure.area(block, 4326)).toFixed(6)} square degrees, ${Math.round(await measure.area(block, 32635))} m²`);
const istanbul = 'POINT(28.9784 41.0082)';
const ankara = 'POINT(32.8597 39.9334)';
const projected = await measure.distance(istanbul, ankara, 32635);
const geodesic = await measure.geodesicDistance(istanbul, ankara);
console.log(`${Math.round(projected)} m in UTM zone 35N, ${Math.round(geodesic)} m on the ellipsoid`);
输出首次运行需下载 23.8 MB
0.000200 square degrees, 1868349 m²
350462 m in UTM zone 35N, 350082 m on the ellipsoid

在 EPSG 代码之间重投影坐标

ST_Transform 借助 PROJ 把几何对象转换到另一个参考系,PROJ 会读取构建时预加载的 proj.db。InitSpatialMetaData(1) 把 SpatiaLite 已知的 6,559 个 EPSG 代码注册到 spatial_ref_sys 中,它们的名称也在那里。

src/native/reproject.h
#pragma once
 
// spatialite.h uses SQLite's types without including sqlite3.h, so sqlite3.h comes first.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <memory>
#include <stdexcept>
#include <string>
 
// Coordinates from one EPSG code to another with ST_Transform, which runs PROJ. InitSpatialMetaData(1)
// fills spatial_ref_sys with the 6,559 reference systems SpatiaLite knows; PROJ reads its proj.db for
// how to get from one to the other.
class Reprojector {
public:
Reprojector() {
if (sqlite3_open(":memory:", &db) != SQLITE_OK) throw std::runtime_error("cannot open the database");
cache = spatialite_alloc_connection();
spatialite_init_ex(db, cache, 0);
char* message = nullptr;
if (sqlite3_exec(db, "SELECT InitSpatialMetaData(1)", nullptr, nullptr, &message) == SQLITE_OK) return;
const std::string reason = message ? message : sqlite3_errmsg(db);
sqlite3_free(message);
throw std::runtime_error(reason);
}
 
~Reprojector() {
sqlite3_close(db);
spatialite_cleanup_ex(cache);
}
 
std::string transform(const std::string& wkt, int from, int to) {
Statement query = prepare("SELECT AsText(ST_Transform(GeomFromText(?1, ?2), ?3))");
sqlite3_bind_text(query.get(), 1, wkt.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(query.get(), 2, from);
sqlite3_bind_int(query.get(), 3, to);
return text(query.get(), "cannot transform: check the WKT and both EPSG codes");
}
 
std::string srsName(int srid) {
Statement query = prepare("SELECT ref_sys_name FROM spatial_ref_sys WHERE srid = ?1");
sqlite3_bind_int(query.get(), 1, srid);
return text(query.get(), "unknown EPSG code");
}
 
private:
using Statement = std::unique_ptr<sqlite3_stmt, int (*)(sqlite3_stmt*)>;
 
Statement prepare(const char* sql) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nullptr) != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(db));
return Statement(statement, sqlite3_finalize);
}
 
// The first column of the only row; no row, or NULL, becomes `missing` as an exception.
std::string text(sqlite3_stmt* statement, const char* missing) {
const int result = sqlite3_step(statement);
if (result != SQLITE_ROW && result != SQLITE_DONE) throw std::runtime_error(sqlite3_errmsg(db));
const unsigned char* value = result == SQLITE_ROW ? sqlite3_column_text(statement, 0) : nullptr;
if (!value) throw std::invalid_argument(missing);
return reinterpret_cast<const char*>(value);
}
 
sqlite3* db = nullptr;
void* cache = nullptr;
};
main.js
import { initNative, Reprojector } from './native/reproject.h';
 
await initNative();
const reprojector = await new Reprojector();
const istanbul = 'POINT(28.9784 41.0082)';
for (const srid of [3857, 32635]) console.log(`${await reprojector.srsName(srid)}: ${await reprojector.transform(istanbul, 4326, srid)}`);
const utm = await reprojector.transform(istanbul, 4326, 32635);
console.log(`back to ${await reprojector.srsName(4326)}: ${await reprojector.transform(utm, 32635, 4326)}`);
输出首次运行需下载 23.8 MB
WGS 84 / Pseudo-Mercator: POINT(3225860.732004 5013551.237223)
WGS 84 / UTM zone 35N: POINT(666370.505017 4541552.487191)
back to WGS 84: POINT(28.9784 41.0082)

读入 GeoJSON,写出 FeatureCollection

GeomFromGeoJSON 把 GeoJSON 几何对象读取为 SpatiaLite 几何对象,AsGeoJSON 则按你要求的小数位数四舍五入后把它写回。SQLite 的 JSON 函数会把各行包装成一个 FeatureCollection,Leaflet、MapLibre 或 OpenLayers 可以直接加载它。

src/native/geojson_layer.h
#pragma once
 
// spatialite.h uses SQLite's types without including sqlite3.h, so sqlite3.h comes first.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <memory>
#include <stdexcept>
#include <string>
 
// Features that arrive as GeoJSON geometries, stored as SpatiaLite geometries and read back as one
// GeoJSON FeatureCollection, the shape web map libraries load.
class GeoJsonLayer {
public:
GeoJsonLayer() {
if (sqlite3_open(":memory:", &db) != SQLITE_OK) throw std::runtime_error("cannot open the database");
cache = spatialite_alloc_connection();
spatialite_init_ex(db, cache, 0);
run("SELECT InitSpatialMetaData(1, 'WGS84')");
run("CREATE TABLE features (id INTEGER PRIMARY KEY, name TEXT NOT NULL)");
run("SELECT AddGeometryColumn('features', 'geom', 4326, 'GEOMETRY', 'XY')");
}
 
~GeoJsonLayer() {
sqlite3_close(db);
spatialite_cleanup_ex(cache);
}
 
// GeomFromGeoJSON returns NULL for text that is not a GeoJSON geometry, so nothing is inserted
// then and the call throws. GeoJSON is longitude and latitude, EPSG:4326.
int add(const std::string& name, const std::string& geometry) {
Statement insert = prepare(
"INSERT INTO features (name, geom) SELECT ?1, shape FROM "
"(SELECT SetSRID(GeomFromGeoJSON(?2), 4326) AS shape) WHERE shape IS NOT NULL");
sqlite3_bind_text(insert.get(), 1, name.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert.get(), 2, geometry.c_str(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(insert.get()) != SQLITE_DONE) throw std::runtime_error(sqlite3_errmsg(db));
if (sqlite3_changes(db) == 0) throw std::invalid_argument("not a GeoJSON geometry: " + name);
return static_cast<int>(sqlite3_last_insert_rowid(db));
}
 
// Every feature in insertion order, coordinates rounded to `decimals`; SQLite's JSON functions
// build the collection around the geometries AsGeoJSON writes.
std::string featureCollection(int decimals) {
Statement query = prepare(
"SELECT json_object('type', 'FeatureCollection', 'features', json_group_array(json_object("
"'type', 'Feature', 'properties', json_object('name', name), 'geometry', json(AsGeoJSON(geom, ?1))))) "
"FROM (SELECT name, geom FROM features ORDER BY id)");
sqlite3_bind_int(query.get(), 1, decimals);
if (sqlite3_step(query.get()) != SQLITE_ROW) throw std::runtime_error(sqlite3_errmsg(db));
return reinterpret_cast<const char*>(sqlite3_column_text(query.get(), 0));
}
 
private:
using Statement = std::unique_ptr<sqlite3_stmt, int (*)(sqlite3_stmt*)>;
 
Statement prepare(const char* sql) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &statement, nullptr) != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(db));
return Statement(statement, sqlite3_finalize);
}
 
void run(const char* sql) {
char* message = nullptr;
if (sqlite3_exec(db, sql, nullptr, nullptr, &message) == SQLITE_OK) return;
const std::string reason = message ? message : sqlite3_errmsg(db);
sqlite3_free(message);
throw std::runtime_error(reason);
}
 
sqlite3* db = nullptr;
void* cache = nullptr;
};
main.js
import { initNative, GeoJsonLayer } from './native/geojson_layer.h';
 
await initNative();
const layer = await new GeoJsonLayer();
await layer.add('Galata Tower', '{"type":"Point","coordinates":[28.974128,41.025638]}');
await layer.add('Galata Bridge', '{"type":"LineString","coordinates":[[28.973364,41.019634],[28.971392,41.024021]]}');
console.log(await layer.featureCollection(5));
输出首次运行需下载 23.8 MB
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Galata Tower"},"geometry":{"type":"Point","coordinates":[28.97413,41.02564]}},{"type":"Feature","properties":{"name":"Galata Bridge"},"geometry":{"type":"LineString","coordinates":[[28.97336,41.01963],[28.97139,41.02402]]}}]}

空间 SQL 命令行工具

WASI 没有 JavaScript 绑定:程序就是一个把 SpatiaLite 与 SQLite、GEOS 和 PROJ 链接在一起的 main(),构建成一个 .wasm,再用 wasmtime 运行。它对当前目录中的数据库文件执行 SQL,并以 WKT 形式输出几何对象,它写出的文件可以在 QGIS 和 GDAL 中打开。ST_Transform 读取 PROJ 的 proj.db,构建时会把它复制到 dist/data/proj:第二个 --dir 标志挂载该文件夹,PROJ_DATA 则告诉 PROJ 它在哪里。

crossbind.config.js
import spatialiteWasi from '@crossbind/port-spatialite-wasi/crossbind.config.js';
 
export default {
general: { name: 'spatialite-tool' },
dependencies: [spatialiteWasi],
// The program and PROJ's data folder land in dist/, next to each other.
paths: { config: import.meta.url, output: 'dist' },
};
src/native/main.cpp
// A command-line spatial SQL runner for WASI:
// spatialite-tool <database> "<sql>" runs the SQL against the database file
// spatialite-tool <database> reads the SQL from standard input
// SpatiaLite's functions are registered on the connection, so the SQL can create geometry columns,
// measure and transform. Rows print as the sqlite3 shell prints them, columns joined by |, with any
// geometry written as WKT, and a summary line follows. ST_Transform needs PROJ's proj.db: point
// PROJ_DATA at the folder the build writes to .crossbind/build/data/proj.
#include <sqlite3.h>
#include <spatialite.h>
 
#include <cstdio>
#include <string>
#include <vector>
 
// The WASI build of SQLite leaves extension loading out, but SpatiaLite calls
// sqlite3_enable_load_extension when it opens a connection of its own, so the link needs a
// definition. Nothing can be loaded here, and SpatiaLite ignores the answer.
extern "C" int sqlite3_enable_load_extension(sqlite3*, int) { return SQLITE_ERROR; }
 
namespace {
 
std::string readAll(FILE* file) {
std::string text;
std::vector<char> buffer(64 * 1024);
size_t read = 0;
while ((read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0) text.append(buffer.data(), read);
return text;
}
 
// A cell as text; a blob that holds a SpatiaLite geometry prints as its WKT.
std::string cell(sqlite3_stmt* statement, int column, sqlite3_stmt* wkt) {
if (sqlite3_column_type(statement, column) == SQLITE_BLOB) {
sqlite3_reset(wkt);
sqlite3_bind_blob(wkt, 1, sqlite3_column_blob(statement, column), sqlite3_column_bytes(statement, column), SQLITE_TRANSIENT);
if (sqlite3_step(wkt) == SQLITE_ROW && sqlite3_column_type(wkt, 0) != SQLITE_NULL) return reinterpret_cast<const char*>(sqlite3_column_text(wkt, 0));
}
const unsigned char* text = sqlite3_column_text(statement, column);
return text ? reinterpret_cast<const char*>(text) : "";
}
 
} // namespace
 
int main(int argc, char** argv) {
if (argc < 2 || argc > 3) {
std::fprintf(stderr, "usage: spatialite-tool <database> [sql] (without sql, reads it from standard input)\n");
return 2;
}
const std::string sql = argc == 3 ? argv[2] : readAll(stdin);
sqlite3* db = nullptr;
if (sqlite3_open(argv[1], &db) != SQLITE_OK) {
std::fprintf(stderr, "%s: %s\n", argv[1], sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
void* cache = spatialite_alloc_connection();
spatialite_init_ex(db, cache, 0);
sqlite3_stmt* wkt = nullptr;
sqlite3_prepare_v2(db, "SELECT AsText(?1)", -1, &wkt, nullptr);
int statements = 0;
int status = 0;
const char* rest = sql.c_str();
const char* end = rest + sql.size();
while (rest < end && status == 0) {
sqlite3_stmt* statement = nullptr;
if (sqlite3_prepare_v2(db, rest, static_cast<int>(end - rest), &statement, &rest) != SQLITE_OK) {
std::fprintf(stderr, "sql: %s\n", sqlite3_errmsg(db));
status = 1;
break;
}
if (!statement) continue;
statements += 1;
int result;
while ((result = sqlite3_step(statement)) == SQLITE_ROW) {
for (int column = 0; column < sqlite3_column_count(statement); column += 1) {
std::printf("%s%s", column ? "|" : "", cell(statement, column, wkt).c_str());
}
std::printf("\n");
}
if (result != SQLITE_DONE) {
std::fprintf(stderr, "sql: %s\n", sqlite3_errmsg(db));
status = 1;
}
sqlite3_finalize(statement);
}
if (status == 0) {
std::printf("spatialite %s, %s: %d statement%s, %d rows changed\n", spatialite_version(), argv[1], statements, statements == 1 ? "" : "s",
sqlite3_total_changes(db));
}
sqlite3_finalize(wkt);
sqlite3_close(db);
spatialite_cleanup_ex(cache);
return status;
}
shell
npx crossbind build -p wasi -e wasi -b release
wasmtime run --dir=. --dir=dist/data/proj::/data/proj --env PROJ_DATA=/data/proj dist/spatialite-tool-wasi-wasm32-st-release.wasm cities.db < cities.sql
wasmtime run --dir=. --dir=dist/data/proj::/data/proj --env PROJ_DATA=/data/proj dist/spatialite-tool-wasi-wasm32-st-release.wasm cities.db "SELECT name, ST_Transform(geom, 32635) FROM cities ORDER BY name"
wasmtime run --dir=. --dir=dist/data/proj::/data/proj --env PROJ_DATA=/data/proj dist/spatialite-tool-wasi-wasm32-st-release.wasm cities.db "SELECT name, CAST(Round(ST_Distance(geom, MakePoint(28.9784, 41.0082, 4326), 1) / 1000) AS INTEGER) AS km FROM cities ORDER BY km"
output
1
1
spatialite 5.1.0, cities.db: 4 statements, 293 rows changed
Ankara|POINT(1000822.269819 4436835.643104)
Istanbul|POINT(666370.505017 4541552.487191)
Izmir|POINT(512464.98383 4252836.769027)
spatialite 5.1.0, cities.db: 1 statement, 0 rows changed
Istanbul|0
Izmir|327
Ankara|350
spatialite 5.1.0, cities.db: 1 statement, 0 rows changed
输入关键词,搜索指南的所有页面和章节。
↑↓ 选择↵ 打开esc 关闭