GeoZero
零拷贝读写地理空间数据。
GeoZero定义了一个用于读取地理空间数据格式的API,无需中间表示。它定义了可以实现的特征,用于读取和转换为任意格式或直接渲染几何图形。
支持的几何类型:
- OGC简单要素
- SQL-MM第3部分定义的圆弧
- TIN(不规则三角网)
支持的维度:X, Y, Z, M, T
可用实现
格式 | 读取 | 写入 | 备注 |
---|---|---|---|
GeoJSON | ✅ | ✅ | |
GEOS | ✅ | ✅ | |
GDAL | ✅ | ✅ | |
WKB | ✅ | ✅ | 支持rust-postgres、SQLx和Diesel的PostGIS几何图形。同时也支持SQLx的GeoPackage几何图形。 |
WKT | ✅ | ✅ | |
CSV | ✅ | ✅ | |
SVG | ❌ | ✅ | |
geo-types | ✅ | ✅ | |
MVT(Mapbox矢量瓦片) | ✅ | ✅ | |
GPX | ✅ | ❌ | |
Shapefile | ✅ | ❌ | 通过geozero-shpcrate可用。 |
FlatGeobuf | ✅ | ❌ | 通过flatgeobufcrate可用。 |
GeoArrow | ✅ | ✅ | 通过geoarrowcrate可用。 |
GeoParquet | ✅ | ✅ | 通过geoarrowcrate可用。 |
应用
- flatgeobuf-gpu:将FlatGeobuf渲染到GPU的演示
- flatgeobuf-bevy:使用WebGPU(原生平台)和WebGL2(Web/WASM)渲染FlatGeobuf的演示
- flatgeobuf-wasm:将FlatGeobuf显示为SVG的WASM演示
转换API
将GeoJSON多边形转换为geo-types并计算质心:
let geojson = GeoJson(r#"{"type": "Polygon", "coordinates": [[[0, 0], [10, 0], [10, 6], [0, 6], [0, 0]]]}"#);
if let Ok(Geometry::Polygon(poly)) = geojson.to_geo() {
assert_eq!(poly.centroid().unwrap(), Point::new(5.0, 3.0));
}
完整源代码:geo_types.rs
将GeoJSON转换为GEOS预处理几何图形:
let geojson = GeoJson(r#"{"type": "Polygon", "coordinates": [[[0, 0], [10, 0], [10, 6], [0, 6], [0, 0]]]}"#);
let geom = geojson.to_geos().expect("GEOS转换失败");
let prepared_geom = geom.to_prepared_geom().expect("to_prepared_geom失败");
let geom2 = geos::Geometry::new_from_wkt("POINT (2.5 2.5)").expect("无效几何图形");
assert_eq!(prepared_geom.contains(&geom2), Ok(true));
完整源代码:geos.rs
将FlatGeobuf子集读取为GeoJSON:
let mut file = BufReader::new(File::open("countries.fgb")?);
let mut fgb = FgbReader::open(&mut file)?.select_bbox(8.8, 47.2, 9.5, 55.3)?;
println!("{}", fgb.to_json()?);
完整源代码:geojson.rs
将FlatGeobuf数据读取为geo-types几何图形,并使用polylabel-rs计算标签位置:
let mut file = BufReader::new(File::open("countries.fgb")?);
let mut fgb = FgbReader::open(&mut file)?.select_all()?;
while let Some(feature) = fgb.next()? {
let name: String = feature.property("name").unwrap();
if let Ok(Geometry::MultiPolygon(mpoly)) = feature.to_geo() {
if let Some(poly) = &mpoly.0.iter().next() {
let label_pos = polylabel(&poly, &0.10).unwrap();
println!("{name}: {label_pos:?}");
}
}
}
完整源代码:polylabel.rs
PostGIS使用示例
使用rust-postgres选择和插入geo-types几何图形。需要with-postgis-postgres
特性:
let mut client = Client::connect(&std::env::var("DATABASE_URL").unwrap(), NoTls)?;
let row = client.query_one(
"SELECT 'SRID=4326;POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))'::geometry",
&[],
)?;
let value: wkb::Decode<geo_types::Geometry<f64>> = row.get(0);
if let Some(geo_types::Geometry::Polygon(poly)) = value.geometry {
assert_eq!(
*poly.exterior(),
vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0)].into()
);
}
// 插入几何图形
let geom: geo_types::Geometry<f64> = geo::Point::new(1.0, 3.0).into();
let _ = client.execute(
"INSERT INTO point2d (datetimefield,geom) VALUES(now(),ST_SetSRID($1,4326))",
&[&wkb::Encode(geom)],
);
使用SQLx选择和插入geo-types几何图形。需要with-postgis-sqlx
特性:
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&env::var("DATABASE_URL").unwrap())
.await?;
让 row: (wkb::Decode<geo_types::Geometry
// 插入几何体
let geom: geo_types::Geometry
使用编译时验证需要[类型重写](https://docs.rs/sqlx/latest/sqlx/macro.query.html#force-a-differentcustom-type):
```rust,ignore
let _ = sqlx::query!(
"INSERT INTO point2d (datetimefield, geom) VALUES(now(), $1::geometry)",
wkb::Encode(geom) as _
)
.execute(&pool)
.await?;
struct PointRec {
pub geom: wkb::Decode<geo_types::Geometry<f64>>,
pub datetimefield: Option<OffsetDateTime>,
}
let rec = sqlx::query_as!(
PointRec,
r#"SELECT datetimefield, geom as "geom!: _" FROM point2d"#
)
.fetch_one(&pool)
.await?;
assert_eq!(
rec.geom.geometry.unwrap(),
geo::Point::new(10.0, 20.0).into()
);
完整源代码:postgis.rs
处理API
计算输入几何体的顶点数:
struct VertexCounter(u64);
impl GeomProcessor for VertexCounter {
fn xy(&mut self, _x: f64, _y: f64, _idx: usize) -> Result<()> {
self.0 += 1;
Ok(())
}
}
let mut vertex_counter = VertexCounter(0);
geometry.process(&mut vertex_counter, GeometryType::MultiPolygon)?;
完整源代码:geozero-api.rs
寻找3D多边形中的最大高度:
struct MaxHeightFinder(f64);
impl GeomProcessor for MaxHeightFinder {
fn coordinate(&mut self, _x: f64, _y: f64, z: Option<f64>, _m: Option<f64>, _t: Option<f64>, _tm: Option<u64>, _idx: usize) -> Result<()> {
if let Some(z) = z {
if z > self.0 {
self.0 = z
}
}
Ok(())
}
}
let mut max_finder = MaxHeightFinder(0.0);
while let Some(feature) = fgb.next()? {
let geometry = feature.geometry().unwrap();
geometry.process(&mut max_finder, GeometryType::MultiPolygon)?;
}
完整源代码:geozero-api.rs
渲染多边形:
struct PathDrawer<'a> {
canvas: &'a mut CanvasRenderingContext2D,
path: Path2D,
}
impl<'a> GeomProcessor for PathDrawer<'a> {
fn xy(&mut self, x: f64, y: f64, idx: usize) -> Result<()> {
if idx == 0 {
self.path.move_to(vec2f(x, y));
} else {
self.path.line_to(vec2f(x, y));
}
Ok(())
}
fn linestring_end(&mut self, _tagged: bool, _idx: usize) -> Result<()> {
self.path.close_path();
self.canvas.fill_path(
mem::replace(&mut self.path, Path2D::new()),
FillRule::Winding,
);
Ok(())
}
}
完整源代码:flatgeobuf-gpu
使用异步HTTP客户端读取FlatGeobuf数据集,应用边界框过滤器并转换为GeoJSON:
let url = "https://flatgeobuf.org/test/data/countries.fgb";
let mut fgb = HttpFgbReader::open(url)
.await?
.select_bbox(8.8, 47.2, 9.5, 55.3)
.await?;
let mut fout = BufWriter::new(File::create("countries.json")?);
let mut json = GeoJsonWriter::new(&mut fout);
fgb.process_features(&mut json).await?;
完整源代码:geojson.rs
使用kdbush创建KD树索引:
struct PointIndex {
pos: usize,
index: KDBush,
}
impl geozero::GeomProcessor for PointIndex {
fn xy(&mut self, x: f64, y: f64, _idx: usize) -> Result<()> {
self.index.add_point(self.pos, x, y);
self.pos += 1;
Ok(())
}
}
let mut points = PointIndex {
pos: 0,
index: KDBush::new(1249, DEFAULT_NODE_SIZE),
};
read_geojson_geom(&mut f, &mut points)?;
points.index.build_index();
完整源代码:kdbush.rs