rustspatialgeo

Rust Geo Crate: Convert between wkt::Geometry and geo:Geometry


I am experimenting with Rust for geospatial data processing. I am completely new to Rust and would appriciate if someone can explain to me how to convert between different complex types.

I found these two packages: https://crates.io/crates/geo and https://crates.io/crates/wkt. Now I have a simple rectangular Polygon that I want to convert to a wkt::Geometry and print a well-known text string.

use geo::{LineString, Polygon};
use wkt::Geometry;
let polygon = Polygon::new(
LineString::from(vec![
    (0., 0.),
    (0., 1.),
    (1., 1.),
    (1., 0.),
]),
vec![],);
// convert the polygon to well known text

Solution

  • I'm in a similar position, so I can't claim to be an expert, but I've found two solutions to this:

    1. Using https://crates.io/crates/wkt
    use geo_types::{LineString, Polygon};
    use wkt::ToWkt;
    
    let polygon = Polygon::new(
    LineString::from(vec![
        (0., 0.),
        (0., 1.),
        (1., 1.),
        (1., 0.),
    ]),
    vec![],);
    
    let geom: Geometry<f64> = polygon.into();
    let wkt = geom.to_wkt().items.pop().unwrap();
    
    println!("{}", wkt)
    
    // POLYGON((0 0,0 1,1 1,1 0,0 0))
    
    1. Using https://github.com/georust/geozero
    use geo_types::{LineString, Polygon};
    use geozero::ToWkt;
    
    let polygon = Polygon::new(
    LineString::from(vec![
        (0., 0.),
        (0., 1.),
        (1., 1.),
        (1., 0.),
    ]),
    vec![],);
    
    let geom: Geometry<f64> = polygon.into();
    let wkt = geom.to_wkt().unwrap();
    
    println!("{}", wkt)
    
    // POLYGON((0 0,0 1,1 1,1 0,0 0))