#geojson #postgis #gdal #mvt #data-processing #intermediate-representation

geozero

在 WKT/WKB、GeoJSON、MVT、GDAL 和其他格式中实现零拷贝的地理空间数据读写

33 个版本

0.13.0 2024年5月16日
0.12.0 2024年2月13日
0.11.0 2023年8月28日
0.10.0 2023年7月7日
0.5.1 2020年7月9日

#4 in 地理空间

Download history 778/week @ 2024-05-03 1214/week @ 2024-05-10 3560/week @ 2024-05-17 4425/week @ 2024-05-24 5436/week @ 2024-05-31 5165/week @ 2024-06-07 3704/week @ 2024-06-14 6049/week @ 2024-06-21 6613/week @ 2024-06-28 5731/week @ 2024-07-05 5278/week @ 2024-07-12 5009/week @ 2024-07-19 4642/week @ 2024-07-26 5049/week @ 2024-08-02 4012/week @ 2024-08-09 3786/week @ 2024-08-16

18,255 每月下载量
用于 32 个 crate(24 个直接使用)

MIT/Apache

495KB
10K SLoC

GeoZero

GitHub CI build crates.io version docs.rs docs Discord Chat

零拷贝读取和写入地理空间数据。

GeoZero 定义了一个 API,用于在不使用中间表示的情况下读取地理空间数据格式。它定义了可以实现的特质,以读取和转换为任意格式或直接渲染几何体。

支持的几何类型

支持的维度:X, Y, Z, M, T

可用的实现

格式 读取 写入 备注
GeoJSON
GEOS
GDAL
WKB 支持 PostGIS 几何体,适用于 rust-postgresSQLxDiesel。还支持 GeoPackage 几何体,适用于 SQLx
WKT
CSV
SVG
geo-types
MVT (Mapbox Vector Tiles)
GPX
Shapefile 通过 geozero-shp crate 提供。
FlatGeobuf 通过 flatgeobuf crate 提供。
GeoArrow 通过 geoarrow crate 提供。
GeoParquet 通过 geoarrow crate 提供。

应用

转换 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 conversion failed");
let prepared_geom = geom.to_prepared_geom().expect("to_prepared_geom failed");
let geom2 = geos::Geometry::new_from_wkt("POINT (2.5 2.5)").expect("Invalid geometry");
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()
    );
}

// Insert geometry
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?;

let row: (wkb::Decode<geo_types::Geometry<f64>>,) =
    sqlx::query_as("SELECT 'SRID=4326;POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))'::geometry")
        .fetch_one(&pool)
        .await?;
let value = row.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()
    );
}

// Insert geometry
let geom: geo_types::Geometry<f64> = geo::Point::new(10.0, 20.0).into();
let _ = sqlx::query(
    "INSERT INTO point2d (datetimefield,geom) VALUES(now(),ST_SetSRID($1,4326))",
)
.bind(wkb::Encode(geom))
.execute(&pool)
.await?;

使用编译时验证需要类型覆盖

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客户端应用bbox过滤器读取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

依赖项

~0.8–19MB
~292K SLoC