• Stars
    star
    303
  • Rank 133,083 (Top 3 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created about 4 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Zero-Copy reading and writing of geospatial data.

GeoZero

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

Zero-Copy reading and writing of geospatial data.

GeoZero defines an API for reading geospatial data formats without an intermediate representation. It defines traits which can be implemented to read and convert to an arbitrary format or render geometries directly.

Supported geometry types:

Supported dimensions: X, Y, Z, M, T

Available implementations

  • GeoJSON Reader + Writer
  • GEOS Reader + Writer
  • GDAL geometry Reader + Writer
  • WKB Reader + Writer supporting
  • WKT Reader + Writer
  • CSV Reader + Writer
  • GeoArrow WKB reader
  • SVG Writer
  • geo-types Reader + Writer
  • MVT (Mapbox Vector Tiles) Reader + Writer
  • GPX Reader

geozero-shp crates.io version docs.rs docs

  • Shapefile Reader

flatgeobuf crates.io version docs.rs docs

  • FlatGeobuf Reader

Applications

Conversion API

Convert a GeoJSON polygon to geo-types and calculate centroid:

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));
}

Full source code: geo_types.rs

Convert GeoJSON to a GEOS prepared geometry:

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));

Full source code: geos.rs

Read FlatGeobuf subset as 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()?);

Full source code: geojson.rs

Read FlatGeobuf data as geo-types geometries and calculate label position with 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:?}");
        }
    }
}

Full source code: polylabel.rs

PostGIS usage examples

Select and insert geo-types geometries with rust-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)],
);

Select and insert geo-types geometries with 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?;

Using compile-time verification requires type overrides:

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()
);

Full source code: postgis.rs

Processing API

Count vertices of an input geometry:

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)?;

Full source code: geozero-api.rs

Find maximal height in 3D polygons:

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)?;
}

Full source code: geozero-api.rs

Render polygons:

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(())
    }
}

Full source code: flatgeobuf-gpu

Read a FlatGeobuf dataset with async HTTP client applying a bbox filter and convert to 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?;

Full source code: geojson.rs

Create a KD-tree index with kdbush:

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();

Full source code: kdbush.rs

More Repositories

1

geo

Geospatial primitives and algorithms for Rust
Rust
1,247
star
2

rstar

R*-tree spatial index for the Rust ecosystem
Rust
337
star
3

gdal

Rust bindings for GDAL
Rust
328
star
4

geojson

Library for serializing the GeoJSON vector GIS file format
Rust
222
star
5

proj

Rust bindings for the latest stable release of PROJ
Rust
131
star
6

geos

Rust bindings for GEOS
Rust
87
star
7

gpx

Rust read/write support for GPS Exchange Format (GPX)
Rust
84
star
8

geohash

Geohash for Rust
Rust
84
star
9

netcdf

High-level netCDF bindings for Rust
Rust
77
star
10

geocoding

Geocoding library for Rust.
Rust
63
star
11

rinex

RINEX and GNSS data processing πŸ›°οΈ
Rust
54
star
12

robust

Robust predicates for computational geometry
Rust
51
star
13

geotiff

Reading GeoTIFFs in Rust, nothing else!
Rust
46
star
14

wkt

Rust read/write support for well-known text (WKT)
Rust
43
star
15

geographiclib-rs

A port of geographiclib in Rust.
Rust
37
star
16

kml

Rust support for KML
Rust
24
star
17

polyline

Google Encoded Polyline encoding & decoding in Rust.
Rust
17
star
18

osm

OSM XML serialization and other OpenStreetMap utilities
Rust
16
star
19

transitfeed

Public transit serializer/deserializer and manipulation library for Rust
Rust
16
star
20

ogcapi

OGC API building blocks implemented in Rust
Rust
14
star
21

topojson

TopoJSON bindings and utilities for Rust
Rust
10
star
22

shapefile

Rust read/write support for shapefiles
HTML
7
star
23

world-file

Rust read/write support for world files
Rust
7
star
24

tilejson

Library for serializing the TileJSON file format
Rust
6
star
25

geos-sys

FFI bindings for libgeos
C++
5
star
26

georust.org

georust.org
3
star
27

geo-svg

A rust library to generate SVGs for geo-types
Rust
2
star
28

meta

The GeoRust Team repository for coordinating and discussing GeoRust projects
Shell
1
star
29

docker-images

Docker images used in the GeoRust ecosystem
Makefile
1
star