### SQLx Integration Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Setup and usage examples for the SQLx crate. ```rust use sqlx::PgPoolOptions; let pool = PgPoolOptions::new() .max_connections(5) .connect(&env::var("DATABASE_URL")?) .await?; ``` ```rust use geozero::wkb::Encode; let geom: geo_types::Geometry = geo::Point::new(10.0, 20.0).into(); sqlx::query("INSERT INTO points (datetimefield, geom) VALUES(now(), ST_SetSRID($1, 4326))") .bind(Encode(geom)) .execute(&pool) .await?; ``` ```rust use geozero::wkb::Decode; struct PointRecord { pub datetimefield: Option, pub geom: Decode>, } let rec: PointRecord = sqlx::query_as( r#"SELECT datetimefield, geom as "geom: _" FROM points LIMIT 1"# ) .fetch_one(&pool) .await?; if let Some(geom) = rec.geom.geometry { println!("Point: {:?}", geom); } ``` ```rust use geozero::wkb::Encode; let geom: geo_types::Geometry = geo::Point::new(10.0, 20.0).into(); let _ = sqlx::query!( "INSERT INTO points (datetimefield, geom) VALUES(now(), $1::geometry)", Encode(geom) as _ ) .execute(&pool) .await?; ``` -------------------------------- ### rust-postgres Integration Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Setup and usage examples for the rust-postgres crate. ```rust use postgres::Client; let mut client = Client::connect(&db_url, NoTls)?; ``` ```rust use geozero::wkb::Encode; let geom: geo_types::Geometry = geo::Point::new(1.0, 3.0).into(); client.execute( "INSERT INTO points (datetimefield, geom) VALUES(now(), ST_SetSRID($1, 4326))", &[&Encode(geom)], )?; ``` ```rust use geozero::wkb::Decode; let row = client.query_one( "SELECT ST_AsEWKB(geom) FROM points WHERE id = $1", &[&1], )?; let decoded: Decode> = row.get(0); if let Some(polygon) = decoded.geometry.and_then(|g| g.as_polygon()) { println!("Exterior: {:?}", polygon.exterior()); } ``` -------------------------------- ### ToWkt usage examples Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Examples showing basic 2D WKT conversion, EWKT with SRID, and custom options. ```rust use geozero::{ToWkt, CoordDimensions}; let point = geo_types::Point::new(10.0, 20.0); let geom: geo_types::Geometry = point.into(); // Basic 2D WKT let wkt = geom.to_wkt()?; assert_eq!(wkt, "POINT(10 20)"); // EWKT with SRID let ewkt = geom.to_ewkt(Some(4326))?; assert_eq!(ewkt, "SRID=4326;POINT(10 20)"); // With Z coordinate let wkt_3d = geom.to_wkt_ndim(CoordDimensions::xyz())?; // Custom options let custom = geom.to_wkt_with_opts( geozero::wkt::WktDialect::Ewkt, CoordDimensions::xyzm(), Some(4326), )?; ``` -------------------------------- ### Install PostGIS System Libraries Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Commands to install PostgreSQL and PostGIS dependencies. ```bash apt-get install -y postgresql postgis ``` ```bash brew install postgresql postgis ``` -------------------------------- ### Setup PostGIS database Source: https://github.com/georust/geozero/blob/main/geozero-bench/README.md Initialize the PostGIS database and populate it with the required tables. ```bash make createdb make countries_table osm_buildings_table ``` -------------------------------- ### Install cargo-criterion Source: https://github.com/georust/geozero/blob/main/geozero-bench/README.md Install the criterion benchmarking tool required to run the performance tests. ```bash cargo install cargo-criterion ``` -------------------------------- ### Diesel Integration Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Setup and usage examples for the Diesel crate. ```rust use diesel::PgConnection; let mut connection = PgConnection::establish(&database_url)?; ``` ```rust use geozero::wkb::Encode; use diesel::prelude::*; let geom: geo_types::Geometry = geo::Point::new(1.0, 3.0).into(); diesel::insert_into(points::table) .values(( points::datetimefield.eq(now()), points::geom.eq(Encode(geom)), )) .execute(&mut connection)?; ``` ```rust use geozero::wkb::Decode; use diesel::prelude::*; let decoded: Decode> = points::table .select(points::geom) .limit(1) .first(&mut connection)?; if let Some(geom) = decoded.geometry { println!("Geometry: {:?}", geom); } ``` -------------------------------- ### WKT output format examples Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Examples of standard WKT and Extended WKT (EWKT) output formats. ```text POINT(10 20) LINESTRING(0 0, 10 10, 20 20) POLYGON((0 0, 10 0, 10 10, 0 10, 0 0)) ``` ```text SRID=4326;POINT(10 20) SRID=4326;POLYGON((0 0, 10 0, 10 10, 0 10, 0 0)) ``` -------------------------------- ### ToGdal Usage Example Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Example demonstrating conversion of WKT to GDAL geometry and calculating area. ```rust use geozero::{GeozeroGeometry, gdal::ToGdal}; let wkt = geozero::wkt::Wkt("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))".to_string()); let geom = wkt.to_gdal()?; // Use GDAL methods println!("Area: {}", geom.area()?); ``` -------------------------------- ### Install GDAL System Libraries Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Commands to install GDAL dependencies on different operating systems. ```bash apt-get install -y libgdal-dev ``` ```bash brew install gdal ``` -------------------------------- ### Start web server Source: https://github.com/georust/geozero/blob/main/geozero-bench/README.md Launch the required web server environment using docker-compose. ```bash cd ../.. docker-compose up -d ``` -------------------------------- ### Install System Dependencies Source: https://github.com/georust/geozero/blob/main/README.md Install required system libraries for GEOS and GDAL on Ubuntu-based distributions. ```sh # Ubuntu/Debian/Mint apt-get install -y libgeos-dev libgdal-dev ``` -------------------------------- ### Install GEOS System Libraries Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Commands to install GEOS dependencies on different operating systems. ```bash apt-get install -y libgeos-dev ``` ```bash brew install geos ``` -------------------------------- ### ProcessToJson Usage Example Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Example of converting a data source to a GeoJSON FeatureCollection string. ```rust use geozero::{GeozeroDatasource, geojson::{GeoJsonReader, ProcessToJson}}; use std::fs::File; let file = File::open("data.geojson")?; let mut reader = GeoJsonReader(file); let json_output = reader.to_json()?; ``` -------------------------------- ### ToGeos Usage Example Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Example demonstrating conversion of GeoJSON to GEOS geometry and performing spatial operations. ```rust use geozero::{GeozeroGeometry, geos::ToGeos}; let geojson = geozero::geojson::GeoJson(r#"{"type": "Polygon", "coordinates": [[[0,0],[10,0],[10,6],[0,6],[0,0]]]}"#); let geom = geojson.to_geos()?; // Use GEOS methods let prepared = geom.to_prepared_geom()?; let point = geos::Geometry::new_from_wkt("POINT(2.5 2.5)")?; assert_eq!(prepared.contains(&point)?, true); ``` -------------------------------- ### Database Connection Pooling Examples Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Configuration patterns for connection pooling in Postgres, SQLx, and Diesel. ```rust // Manual pool using postgres-types ``` ```rust use sqlx::PgPoolOptions; let pool = PgPoolOptions::new() .max_connections(5) .connect(&db_url) .await?; // Reuse pool across async tasks ``` ```rust use diesel::r2d2::ConnectionManager; use diesel::r2d2::Pool; let manager = ConnectionManager::::new(database_url); let pool = Pool::builder().build(manager)?; ``` -------------------------------- ### ToJson Usage Example Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Example of converting a geo_types geometry to a GeoJSON string. ```rust use geozero::{geojson::ToJson, geo_types::ToGeo}; let point = geo_types::Point::new(10.0, 20.0); let geom: geo_types::Geometry = point.into(); let json = geom.to_json()?; assert_eq!(json, r#"{"type":"Point","coordinates":[10,20]}"#); ``` -------------------------------- ### Process Shapefile to GeoJSON Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Example demonstrating reading a shapefile and converting it to GeoJSON format. ```rust use geozero::{shp::ShpReader, geojson::GeoJsonWriter}; let reader = ShpReader::from_path("data.shp")?; let mut output = Vec::new(); let mut writer = GeoJsonWriter::new(&mut output); reader.iter_features(writer)?.count(); ``` -------------------------------- ### WktWriter usage example Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Demonstrates processing GeoJSON into a WKT string using WktWriter. ```rust use geozero::{GeozeroGeometry, wkt::WktWriter, CoordDimensions}; let geojson = geozero::geojson::GeoJson(r#"{"type": "Point", "coordinates": [10, 20]}"#); let mut output = Vec::new(); let mut writer = WktWriter::new(&mut output); geojson.process_geom(&mut writer)?; let wkt_string = String::from_utf8(output)?; println!("{}", wkt_string); ``` -------------------------------- ### Implement PropertyProcessor Source: https://github.com/georust/geozero/blob/main/_autodocs/02-traits.md Example implementation of the PropertyProcessor trait to count properties. ```rust use geozero::{PropertyProcessor, ColumnValue}; struct PropertyCounter(usize); impl PropertyProcessor for PropertyCounter { fn property(&mut self, _idx: usize, name: &str, _value: &ColumnValue) -> Result { println!("Property: {}", name); self.0 += 1; Ok(false) } } let mut counter = PropertyCounter(0); // Process properties... ``` -------------------------------- ### Convert Wkb to WKT Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Example usage of Wkb structure to convert binary data to WKT format. ```rust use geozero::{GeozeroGeometry, wkb::{Wkb, ToWkb}, CoordDimensions}; let wkb = Wkb(vec![1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 64, 0, 0, 0, 0, 0, 0, 52, 192]); let wkt = wkb.to_wkt()?; assert_eq!(wkt, "POINT(10 -20)"); ``` -------------------------------- ### GeoJSON output format example Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md The expected JSON structure for a FeatureCollection output. ```json { "type": "FeatureCollection", "name": "optional_name", "features": [ {"type": "Feature", "properties": {...}, "geometry": {...}}, ... ] } ``` -------------------------------- ### NDJSON output format example Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md The expected format for newline-delimited JSON output. ```json {"type": "Feature", "properties": {...}, "geometry": {...}} {"type": "Feature", "properties": {...}, "geometry": {...}} ... ``` -------------------------------- ### Process Ewkb Geometry Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Example usage of Ewkb structure for processing geometry. ```rust use geozero::{GeozeroGeometry, wkb::Ewkb}; let ewkb = Ewkb(vec![1, 1, 0, 0, 32, 230, 16, 0, 0, ...]); geometry.process_geom(&mut processor)?; ``` -------------------------------- ### Decode Geometry from PostGIS Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Examples of using the Decode wrapper to retrieve geometries from PostGIS. ```rust use geozero::wkb::Decode; let row = client.query_one( "SELECT 'SRID=4326;POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))'::geometry", &[], )?; let value: Decode> = row.get(0); if let Some(geom) = value.geometry { println!("Geometry: {:?}", geom); } ``` ```rust use geozero::wkb::Decode; let row: (Decode>,) = sqlx::query_as("SELECT geom FROM points LIMIT 1") .fetch_one(&pool) .await?; if let Some(geom) = row.0.geometry { // Use geometry } ``` -------------------------------- ### Define 2D Geometry Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of a standard 2D point geometry. ```text POINT(10 20) ``` -------------------------------- ### Encode Geometry for PostGIS Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Examples of using the Encode wrapper to insert geometries into PostGIS. ```rust use geozero::wkb::Encode; use postgres::Client; let geom: geo_types::Geometry = geo::Point::new(1.0, 3.0).into(); client.execute( "INSERT INTO points (geom) VALUES ($1)", &[&Encode(geom)], )?; ``` ```rust use geozero::wkb::Encode; use sqlx::PgPool; let geom: geo_types::Geometry = geo::Point::new(10.0, 20.0).into(); sqlx::query("INSERT INTO points (geom) VALUES ($1)") .bind(Encode(geom)) .execute(&pool) .await?; ``` -------------------------------- ### Usage of read_wkb Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Example of reading WKB bytes using a cursor and a custom geometry processor. ```rust use geozero::{wkb::{read_wkb, WkbDialect}, GeomProcessor}; use std::io::Cursor; let wkb_bytes = vec![1, 1, 0, 0, 0, ...]; let mut cursor = Cursor::new(wkb_bytes); let mut processor = MyGeomProcessor; read_wkb(&mut cursor, &mut processor, WkbDialect::Wkb)?; ``` -------------------------------- ### Construct geometry from WKB Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Example of using the FromWkb trait to parse WKB bytes into a geo_types::Geometry. ```rust use geozero::wkb::{FromWkb, WkbDialect}; use std::io::Cursor; let wkb_bytes = vec![1, 1, 0, 0, 0, ...]; let mut cursor = Cursor::new(wkb_bytes); let geom: geo_types::Geometry = geo_types::Geometry::from_wkb(&mut cursor, WkbDialect::Ewkb)?; ``` -------------------------------- ### Read Geometry from WKT Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of reading a geometry object from a WKT string. ```rust use geozero::wkt::WktReader; let geom: geo_types::Geometry = WktReader::read_geometry("POLYGON ((0 0, 10 0, 10 6, 0 6, 0 0))")?; ``` -------------------------------- ### Use GeoJsonLineWriter for processing Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Example of using GeoJsonLineWriter to process a datasource and iterate over the resulting lines. ```rust use geozero::{GeozeroDatasource, geojson::GeoJsonLineWriter}; let mut output = Vec::new(); let mut writer = GeoJsonLineWriter::new(&mut output); datasource.process(&mut writer)?; let ndjson_string = String::from_utf8(output)?; for line in ndjson_string.lines() { println!("{}", line); } ``` -------------------------------- ### Convert geometry to SVG document Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Example of converting a polygon to an SVG document string. ```rust use geozero::{GeozeroGeometry, svg::ToSvg}; use geo_types::polygon; let geom: geo_types::Geometry = polygon![ (x: 220., y: 10.), (x: 300., y: 210.), (x: 170., y: 250.), ].into(); let svg_doc = geom.to_svg_document()?; println!("{}", svg_doc); ``` -------------------------------- ### Implement Custom GeomProcessor Source: https://github.com/georust/geozero/blob/main/_autodocs/README.md Example of defining a custom processor by implementing the GeomProcessor trait to handle coordinate data. ```rust use geozero::{GeomProcessor, error::Result}; struct MyProcessor; impl GeomProcessor for MyProcessor { fn xy(&mut self, x: f64, y: f64, idx: usize) -> Result<()> { println!("{} {}", x, y); Ok(()) } } ``` -------------------------------- ### Convert WKT to JSON Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of converting a WKT string wrapper to JSON format. ```rust use geozero::{GeozeroGeometry, wkt::WktStr, ToJson}; let wkt = WktStr("POINT(10 20)"); let json = wkt.to_json()?; ``` -------------------------------- ### Define 3D Geometry Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Examples of 3D point geometries using Z coordinates. ```text POINT Z (10 20 30) POINT(10 20 30) // Also valid ``` -------------------------------- ### Apply Coordinate Offset Source: https://github.com/georust/geozero/blob/main/_autodocs/02-traits.md Example usage of pre_process_xy to apply an offset to all coordinates during geometry processing. ```rust // Example: Add offset to all coordinates let mut output = Vec::new(); let mut writer = WktWriter::new(&mut output).pre_process_xy(|x, y| { *x += 1.0; *y += 1.0; }); geometry.process_geom(&mut writer)?; ``` -------------------------------- ### Write geometry to WKB Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Example of using WkbWriter to process GeoJSON into a WKB byte vector. ```rust use geozero::{GeozeroGeometry, wkb::WkbWriter, CoordDimensions}; use std::io::Cursor; let geojson = geozero::geojson::GeoJson(r#"{"type": "Point", "coordinates": [10, 20]}"#); let mut wkb_output = Vec::new(); let mut writer = WkbWriter::new(&mut wkb_output); geojson.process_geom(&mut writer)?; println!("WKB length: {}", wkb_output.len()); ``` -------------------------------- ### Use GeoJsonWriter for processing Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Example of using GeoJsonWriter to process a datasource and convert the output to a string. ```rust use geozero::{GeozeroDatasource, geojson::GeoJsonWriter}; let mut output = Vec::new(); let mut writer = GeoJsonWriter::new(&mut output); datasource.process(&mut writer)?; let json_string = String::from_utf8(output)?; println!("{}", json_string); ``` -------------------------------- ### Prepare benchmark data Source: https://github.com/georust/geozero/blob/main/geozero-bench/README.md Navigate to the data directory and execute the make command to prepare the necessary test files. ```bash cd tests/data make ``` -------------------------------- ### Full stack configuration Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable all available optional formats and database integrations. ```toml geozero = { version = "0.14", features = [ "with-csv", "with-gdal", "with-geo", "with-geojson", "with-geos", "with-gpkg", "with-gpx", "with-postgis-postgres", "with-postgis-sqlx", "with-postgis-diesel", "with-shp", "with-svg", "with-tessellator", "with-wkb", "with-wkt", "with-mvt", ] } ``` -------------------------------- ### Display geozero CLI help Source: https://github.com/georust/geozero/blob/main/geozero-cli/README.md Shows the available commands and options for the geozero CLI. ```bash geozero --help ``` -------------------------------- ### Enable WKB Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables Well-Known Binary support for database integration. ```toml [features] with-wkb = ["byteorder"] ``` -------------------------------- ### Execute benchmarks Source: https://github.com/georust/geozero/blob/main/geozero-bench/README.md Set the database connection string and run the criterion benchmark suite. ```bash export DATABASE_URL=postgresql://$USER@localhost/geozerobench?sslmode=disable cargo criterion ``` -------------------------------- ### Query and Insert GeoPackage WKB with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Requires the with-gpkg feature. Shows how to query geometries and insert them with an envelope. ```rust use geozero::wkb::{Encode, Decode}; use sqlx::sqlite::SqlitePool; // Query let row: (Decode>,) = sqlx::query_as("SELECT geom FROM features LIMIT 1") .fetch_one(&pool) .await?; // Insert with envelope let envelope = vec![0.0, 0.0, 10.0, 10.0]; let encoded = geom.to_gpkg_wkb(CoordDimensions::xy(), None, envelope)?; ``` -------------------------------- ### Configure PostGIS with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable the with-postgis-sqlx feature for async/await support and SQLx trait implementations. ```toml [features] with-postgis-sqlx = ["sqlx", "wkb"] ``` -------------------------------- ### Enable WKT Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables Well-Known Text parsing and writing. ```toml [features] with-wkt = ["wkt"] ``` -------------------------------- ### Insert and Decode WKB with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Requires the with-postgis-sqlx feature. Demonstrates both insertion and retrieval of geometries using SQLx. ```rust use geozero::wkb::Encode; use sqlx::PgPool; let geom: geo_types::Geometry = geo::Point::new(10.0, 20.0).into(); sqlx::query("INSERT INTO points (geom) VALUES ($1)") .bind(Encode(geom)) .execute(&pool) .await?; // Decode let row: (geozero::wkb::Decode>,) = sqlx::query_as("SELECT geom FROM points LIMIT 1") .fetch_one(&pool) .await?; if let Some(geom) = row.0.geometry { println!("Geometry: {:?}", geom); } ``` -------------------------------- ### Define 4D Geometry Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of a 4D point geometry with Z and M coordinates. ```text POINT ZM (10 20 30 100) ``` -------------------------------- ### Define 2D Geometry with Measurement Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of a 2D point geometry with an M coordinate. ```text POINT M (10 20 100) ``` -------------------------------- ### Initialize GpxReader Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Constructor for GpxReader. ```rust pub fn new(reader: R) -> Self ``` -------------------------------- ### Convert geometries to WKB formats Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Demonstrates usage of ToWkb methods to generate OGC WKB, EWKB, and GeoPackage binary representations from geo-types geometries. ```rust use geozero::{ToWkb, CoordDimensions}; let point = geo_types::Point::new(10.0, -20.0); let geom: geo_types::Geometry = point.into(); // OGC WKB (2D) let wkb = geom.to_wkb(CoordDimensions::xy())?; // EWKB with SRID let ewkb = geom.to_ewkb(CoordDimensions::xyz(), Some(4326))?; // GeoPackage with envelope let envelope = vec![10.0, -20.0, 10.0, -20.0]; let gpkg = geom.to_gpkg_wkb(CoordDimensions::xy(), Some(4326), envelope)?; ``` -------------------------------- ### Initialize ShpReader Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Constructor for creating a reader instance from a file path. ```rust impl ShpReader { pub fn from_path>(path: P) -> Result } ``` -------------------------------- ### Convert GeoJson to geo-types Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Example of converting GeoJson to a geo-types Geometry and calculating its area. ```rust use geozero::{GeozeroGeometry, geo_types::ToGeo}; let geojson = geozero::geojson::GeoJson(r#"{"type": "Polygon", "coordinates": [[[0,0],[10,0],[10,6],[0,6],[0,0]]]}"#); let geom: geo_types::Geometry = geojson.to_geo()?; if let Some(poly) = geom.as_polygon() { println!("Area: {}", poly.unsigned_area()); } ``` -------------------------------- ### Perform Automatic Type Conversion Source: https://github.com/georust/geozero/blob/main/_autodocs/09-types-reference.md Example of converting ColumnValue variants using PropertyReadType. ```rust // Automatic type conversion let int_val: i32 = value.into()?; let string_val: String = value.into()?; ``` -------------------------------- ### WkbWriter constructors Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Methods to initialize a WkbWriter with default or custom options. ```rust impl WkbWriter { pub fn new(out: W) -> Self pub fn with_opts( out: W, dialect: WkbDialect, dims: CoordDimensions, srid: Option, envelope: Vec, ) -> Self } ``` -------------------------------- ### Enable GeoPackage Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables GeoPackage WKB dialect support. ```toml [features] with-gpkg = [] ``` -------------------------------- ### Process Ewkt Geometry Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Example of processing an EWKT string using a geometry processor. ```rust use geozero::{GeozeroGeometry, wkt::EwktStr}; let ewkt = EwktStr("SRID=4326;POINT(10 20)"); ewkt.process_geom(&mut my_processor)?; ``` -------------------------------- ### Database-focused configuration Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable features optimized for database operations using SQLx. ```toml geozero = { version = "0.14", features = [ "with-wkb", "with-postgis-sqlx", "with-geo", ] } ``` -------------------------------- ### Configure PostGIS with rust-postgres Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable the with-postgis-postgres feature to support automatic conversion for the postgres wire protocol. ```toml [features] with-postgis-postgres = ["postgres", "postgres-types", "wkb"] ``` -------------------------------- ### Database Integration with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/README.md Demonstrates encoding geometries for insertion and decoding geometries from query results using SQLx. ```rust use geozero::wkb::Encode; // Insert sqlx::query("INSERT INTO geom (geom) VALUES ($1)") .bind(Encode(my_geometry)) .execute(&pool) .await? // Query let (Decode(geom),) = sqlx::query_as("SELECT geom FROM table") .fetch_one(&pool) .await? ``` -------------------------------- ### Initialize MvtWriter Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Constructors for creating a new MvtWriter instance with or without coordinate scaling. ```rust impl MvtWriter { pub fn new( extent: u32, left: f64, bottom: f64, right: f64, top: f64, ) -> Result pub fn new_unscaled(extent: u32) -> Result } ``` -------------------------------- ### ShpReader::from_path Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Constructs a new ShpReader instance from a given file path. ```APIDOC ## ShpReader::from_path ### Description Creates a new ShpReader instance to read a Shapefile from the specified file path. ### Signature `pub fn from_path>(path: P) -> Result` ### Parameters - **path** (P: AsRef) - Required - The file path to the .shp file. ``` -------------------------------- ### Enable Shapefile Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables reading of legacy Shapefile datasets. ```toml [features] with-shp = ["dbase", "scroll"] ``` -------------------------------- ### Create a KD-tree index for points Source: https://github.com/georust/geozero/blob/main/README.md Populate a KDBush index by implementing the xy processor method to add points during geometry traversal. ```rust 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(); ``` -------------------------------- ### WktWriter constructors Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Constructors for initializing WktWriter with default or custom dialect, dimensions, and SRID settings. ```rust impl WktWriter { pub fn new(out: W) -> Self pub fn with_opts( out: W, dialect: WktDialect, dims: CoordDimensions, srid: Option, ) -> Self } ``` -------------------------------- ### Convert GeoJSON to MVT Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Example usage of the ToMvt trait to convert GeoJSON data into an MVT feature. ```rust use geozero::{GeozeroGeometry, mvt::ToMvt, CoordDimensions}; let geojson = geozero::geojson::GeoJson(r#"{"type": "Point", "coordinates": [10, 20]}"#); // Convert with map bounds and tile extent let feature = geojson.to_mvt( 4096, // extent -180.0, // left (map bounds) -85.0, // bottom 180.0, // right 85.0, // top )?; ``` -------------------------------- ### Enable GPX Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables reading of GPS traces and waypoints. ```toml [features] with-gpx = ["gpx"] ``` -------------------------------- ### Configure geozero dependencies in Cargo.toml Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Recommended configuration for standard use cases involving GeoJSON and WKB support. ```toml geozero = { version = "0.14", features = ["with-geojson", "with-wkb"] } ``` -------------------------------- ### Minimal Geozero configuration Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable only GeoJSON support to keep dependencies minimal. ```toml geozero = { version = "0.14", features = ["with-geojson"] } ``` -------------------------------- ### Construct GeoJsonLineWriter Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Constructor methods for initializing a GeoJsonLineWriter. ```rust impl GeoJsonLineWriter { pub fn new(out: W) -> Self pub fn with_dims(out: W, dims: CoordDimensions) -> Self } ``` -------------------------------- ### Enable MVT Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables Mapbox Vector Tiles support. ```toml [features] with-mvt = ["prost"] ``` -------------------------------- ### Manage TagsBuilder methods Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Methods for initializing and adding tags to the TagsBuilder. ```rust impl TagsBuilder { pub fn new() -> Self pub fn push(&mut self, key: u32, value: u32) } ``` -------------------------------- ### Format conversion hub configuration Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enable multiple format features to support conversion between GeoJSON, WKT, WKB, and geo types. ```toml geozero = { version = "0.14", features = [ "with-geojson", "with-wkt", "with-wkb", "with-geo", ] } ``` -------------------------------- ### Define Wkb Structure Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md OGC Standard WKB (Well-Known Binary format) implementation. ```rust pub struct Wkb(pub Vec); ``` -------------------------------- ### Run tests with feature flags Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Commands to execute tests with varying feature sets, including all features, specific combinations, or no default features. ```bash cargo test --all-features ``` ```bash cargo test --features "with-geojson,with-wkt" ``` ```bash cargo test --no-default-features --features "with-geojson" ``` -------------------------------- ### Initialize SvgWriter Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Constructor for SvgWriter. ```rust impl SvgWriter { pub fn new(out: W, is_document: bool) -> Self } ``` -------------------------------- ### Enable GDAL Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables integration with the GDAL library for advanced operations. ```toml [features] with-gdal = ["gdal"] ``` -------------------------------- ### Insert geometry using SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Bind the Encode wrapper to a SQLx query for asynchronous database insertion. ```rust use geozero::wkb::Encode; use sqlx::PgPool; let geom = geo::Point::new(10.0, 20.0).into(); sqlx::query("INSERT INTO geometries (geom) VALUES ($1)") .bind(Encode(geom)) .execute(&pool) .await?; ``` -------------------------------- ### Define WKT Wrapper Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Generic wrapper for WKT strings. ```rust pub struct Wkt(pub S); ``` -------------------------------- ### Define MySQLWkb Structure Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md MySQL spatial WKB format. ```rust pub struct MySQLWkb(pub Vec); ``` -------------------------------- ### Compile-time Query Verification with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Ensures query compatibility with the database schema at compile time. ```rust // This compiles only if the query matches the database schema let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM points") .fetch_one(&pool) .await?; ``` -------------------------------- ### Enable CSV Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables CSV reading and writing capabilities. ```toml [features] with-csv = ["csv"] ``` -------------------------------- ### Enable geo-types Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables integration with the geo-types crate. ```toml [features] with-geo = ["geo-types"] ``` -------------------------------- ### Insert WKB with rust-postgres Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md Requires the with-postgis-postgres feature. Uses the Encode wrapper to insert geo_types geometries into PostGIS. ```rust use geozero::wkb::Encode; use postgres::Client; let geom: geo_types::Geometry = geo::Point::new(1.0, 3.0).into(); client.execute( "INSERT INTO points (geom) VALUES ($1)", &[&Encode(geom)], )?; ``` -------------------------------- ### Process geometry with GeozeroGeometry Source: https://github.com/georust/geozero/blob/main/_autodocs/02-traits.md Demonstrates converting GeoJSON to WKT format using the GeozeroGeometry trait. ```rust use geozero::{GeozeroGeometry, wkt::WktWriter}; let json_str = r#"{"type": "Point", "coordinates": [10, 20]}"#; let geojson = geozero::geojson::GeoJson(json_str); let mut wkt_output = Vec::new(); let mut wkt_writer = WktWriter::new(&mut wkt_output); geojson.process_geom(&mut wkt_writer)?; println!("{}", String::from_utf8(wkt_output)?); // Output: POINT(10 20) ``` -------------------------------- ### Unit Test Geometry Conversion and Processing in Rust Source: https://github.com/georust/geozero/blob/main/_autodocs/08-patterns-and-examples.md Demonstrates testing GeoJSON to WKT conversion and custom geometry processor vertex counting. ```rust #[cfg(test)] mod tests { use geozero::{GeozeroGeometry, geojson::GeoJson, wkt::ToWkt}; #[test] fn test_geojson_to_wkt() -> Result<(), Box> { let geojson = GeoJson(r#"{"type": "Point", "coordinates": [10, 20]}"#); let wkt = geojson.to_wkt()?; assert_eq!(wkt, "POINT(10 20)"); Ok(()) } #[test] fn test_polygon_processing() -> Result<(), Box> { let geojson = GeoJson( r#"{"type": "Polygon", "coordinates": [[[0,0],[10,0],[10,6],[0,6],[0,0]]]}"# ); let mut processor = TestProcessor::new(); geojson.process_geom(&mut processor)?; assert_eq!(processor.vertex_count, 5); Ok(()) } } ``` -------------------------------- ### Implement Batch Processing with FeatureProcessor Source: https://github.com/georust/geozero/blob/main/_autodocs/08-patterns-and-examples.md Demonstrates how to implement the FeatureProcessor trait to group features into batches and process them upon reaching a specific size. ```rust use geozero::{GeozeroDatasource, FeatureProcessor, error::Result}; struct BatchProcessor { count: usize, batch_size: usize, current_batch: Vec, } impl FeatureProcessor for BatchProcessor { fn feature_end(&mut self, _idx: u64) -> Result<()> { self.current_batch.push(format!("Feature {}", self.count)); self.count += 1; if self.current_batch.len() >= self.batch_size { self.process_batch()?; self.current_batch.clear(); } Ok(()) } fn dataset_end(&mut self) -> Result<()> { if !self.current_batch.is_empty() { self.process_batch()?; } Ok(()) } } impl BatchProcessor { fn process_batch(&self) -> Result<()> { // Process batch of features Ok(()) } } ``` -------------------------------- ### Convert Geozero Results Source: https://github.com/georust/geozero/blob/main/_autodocs/08-patterns-and-examples.md Demonstrates converting Geozero operations into standard Result types for both synchronous and asynchronous contexts. ```rust // Convert to standard Result use geozero::error::GeozeroError; fn my_function() -> std::result::Result> { let geom = some_geozero_operation()?; Ok(format!("{:?}", geom)) } // In async code async fn my_async_function() -> Result { let data = some_async_geozero_operation().await?; Ok(format!("{:?}", data)) } ``` -------------------------------- ### Query Geometry Records with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/08-patterns-and-examples.md Fetches geometry data from a database using the FromRow derive macro and WKB decoding. ```rust use geozero::wkb::Decode; use sqlx::{PgPool, FromRow}; #[derive(FromRow)] struct GeometryRecord { id: i32, geom: Decode>, name: String, } async fn fetch_geometries(pool: &PgPool) -> Result, sqlx::Error> { sqlx::query_as::<_, GeometryRecord>( "SELECT id, geom, name FROM features WHERE geom IS NOT NULL" ) .fetch_all(pool) .await } ``` -------------------------------- ### Process GeoJson to WKT Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Demonstrates converting a GeoJson struct to WKT format. ```rust use geozero::{GeozeroGeometry, geojson::GeoJson, wkt::ToWkt}; let geojson = GeoJson(r#"{"type": "Point", "coordinates": [10, 20]}"#); let wkt = geojson.to_wkt()?; assert_eq!(wkt, "POINT(10 20)"); ``` -------------------------------- ### Enable SVG Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables SVG output for vector graphics. ```toml [features] with-svg = [] ``` -------------------------------- ### Convert WKB to WKT Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Use this snippet to parse WKB data into a WktString. Ensure the reader is initialized and the appropriate WkbDialect is specified. ```rust use geozero::wkb::{FromWkb, WkbDialect}; let geom: geozero::wkt::WktString = geozero::wkt::WktString::from_wkb(&mut reader, WkbDialect::Ewkb)?; ``` -------------------------------- ### Process Geometries and Conversions Source: https://github.com/georust/geozero/blob/main/_autodocs/README.md Standard entry points for processing single geometries or multiple features, along with common format conversion methods. ```rust // Single geometry geometry.process_geom(&mut processor)? // Multiple features datasource.process(&mut processor)? // Conversions geometry.to_wkt()? geometry.to_json()? geometry.to_wkb(CoordDimensions::xyz())? ``` -------------------------------- ### Define WKT Dialects Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Enumeration for supported WKT formats including standard OGC and Extended WKT. ```rust pub enum WktDialect { Wkt, // OGC Standard WKT (ISO/IEC 19125-1) Ewkt, // Extended WKT with SRID } ``` -------------------------------- ### Geozero Module Structure Source: https://github.com/georust/geozero/blob/main/_autodocs/00-index.md Visual representation of the core modules available in the Geozero crate. ```text geozero ├── error – GeozeroError, Result ├── api – GeozeroGeometry, GeozeroDatasource, FeatureAccess ├── geometry_processor – GeomProcessor trait, CoordDimensions ├── feature_processor – FeatureProcessor trait ├── property_processor – PropertyProcessor trait, ColumnValue ├── bounds – BoundsProcessor └── (12 format modules, see below) ``` -------------------------------- ### Insert GeoPackage Geometry with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Requires the with-gpkg feature flag. Encodes geometry to GeoPackage WKB format before insertion. ```rust use geozero::wkb::Encode; use geozero::CoordDimensions; let geom: geo_types::Geometry = geo::Point::new(10.0, 20.0).into(); let envelope = vec![10.0, 20.0, 10.0, 20.0]; let gpkg_wkb = geom.to_gpkg_wkb(CoordDimensions::xy(), None, envelope)?; sqlx::query("INSERT INTO features (geom) VALUES ($1)") .bind(gpkg_wkb) .execute(&pool) .await?; ``` -------------------------------- ### Define SpatiaLiteWkb Structure Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md SpatiaLite WKB format (SQLite extension). ```rust pub struct SpatiaLiteWkb(pub Vec); ``` -------------------------------- ### Convert geospatial file formats Source: https://github.com/georust/geozero/blob/main/geozero-cli/README.md Converts data from one geospatial format to another using the CLI. ```bash geozero cities.geojson cities.fgb ``` -------------------------------- ### Bulk Insert Geometries with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/08-patterns-and-examples.md Uses a transaction to insert multiple geometries into a PostgreSQL database. Requires an active PgPool connection. ```rust use geozero::wkb::Encode; use sqlx::PgPool; async fn bulk_insert_geometries( pool: &PgPool, geometries: Vec>, ) -> Result<(), sqlx::Error> { let mut tx = pool.begin().await?; for geom in geometries { sqlx::query("INSERT INTO geometries (geom) VALUES ($1)") .bind(Encode(geom)) .execute(&mut *tx) .await?; } tx.commit().await?; Ok(()) } ``` -------------------------------- ### Construct GeoJsonWriter Source: https://github.com/georust/geozero/blob/main/_autodocs/03-geojson.md Constructor methods for initializing a GeoJsonWriter with an output writer and optional coordinate dimensions. ```rust impl GeoJsonWriter { pub fn new(out: W) -> Self pub fn with_dims(out: W, dims: CoordDimensions) -> Self } ``` -------------------------------- ### SQLx compile-time verification Source: https://github.com/georust/geozero/blob/main/README.md Uses type overrides for compile-time verification with SQLx queries. ```rust 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>, pub datetimefield: Option, } 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() ); ``` -------------------------------- ### Define Ewkt Wrapper Source: https://github.com/georust/geozero/blob/main/_autodocs/05-wkt.md Wrapper for Extended WKT containing SRID and geometry text. ```rust pub struct Ewkt(pub S); ``` -------------------------------- ### Define GeoZero Dependencies Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Dependency tree showing direct and conditional feature-based dependencies. ```text geozero ├── thiserror (error handling) └── byteorder (for coordinate encoding, used in most operations) ``` ```text geozero[with-wkt] └── wkt ├── nom └── serde_json (optional) ``` ```text geozero[with-geojson] ├── geojson │ └── serde_json │ └── serde └── serde_json ``` ```text geozero[with-postgis-sqlx] ├── sqlx │ ├── tokio (async runtime) │ ├── sqlx-postgres │ └── serde └── wkb (WKB support) ``` ```text geozero[with-geos] └── geos └── libgeos (system library) ``` ```text geozero[with-gdal] └── gdal ├── gdal-sys (system bindings) └── libgdal (system library) ``` -------------------------------- ### Enable GEOS Support Source: https://github.com/georust/geozero/blob/main/_autodocs/10-feature-flags.md Enables integration with the GEOS library for spatial predicates. ```toml [features] with-geos = ["geos"] ``` -------------------------------- ### Define GpkgWkb Structure Source: https://github.com/georust/geozero/blob/main/_autodocs/04-wkb.md GeoPackage WKB format (includes envelope header). ```rust pub struct GpkgWkb(pub Vec); ``` -------------------------------- ### Implement CsvWriter Source: https://github.com/georust/geozero/blob/main/_autodocs/06-formats.md Writer for outputting geometries as CSV with WKT geometry columns. ```rust pub struct CsvWriter { out: W, } ``` ```rust impl CsvWriter { pub fn new(out: W) -> Self } ``` ```text x,y,property1,property2 10,20,value1,value2 ``` ```rust use geozero::{GeozeroDatasource, csv::CsvWriter}; let mut output = Vec::new(); let mut writer = CsvWriter::new(&mut output); datasource.process(&mut writer)?; let csv_string = String::from_utf8(output)?; println!("{}", csv_string); ``` -------------------------------- ### Insert Geometries into PostGIS Source: https://github.com/georust/geozero/blob/main/_autodocs/00-index.md Use the WKB encoder to insert geometries into a database via SQLx. ```rust use geozero::wkb::Encode; sqlx::query("INSERT INTO geom_table (geom) VALUES ($1)") .bind(Encode(my_geometry)) .execute(&pool) .await? ``` -------------------------------- ### Batch insert geometries with SQLx Source: https://github.com/georust/geozero/blob/main/_autodocs/07-geos-gdal-postgis.md Uses a database transaction to perform atomic multi-row inserts for improved performance. ```rust use sqlx::Transaction; let mut tx = pool.begin().await?; for geom in geometries { sqlx::query("INSERT INTO points (geom) VALUES ($1)") .bind(Encode(geom)) .execute(&mut *tx) .execute(&pool) .await?; } tx.commit().await?; ```