Skip to content

Commit

Permalink
Add Geometry::from_geojson
Browse files Browse the repository at this point in the history
  • Loading branch information
lnicola committed Mar 2, 2023
1 parent 1a4144d commit e1224b2
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/vector/ops/conversions/formats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,17 @@ impl Geometry {
Ok(unsafe { Geometry::with_c_geometry(c_geom, true) })
}

/// Create a geometry by parsing a
/// [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) string.
pub fn from_geojson(json: &str) -> Result<Geometry> {
let c_geojson = CString::new(json)?;
let c_geom = unsafe { gdal_sys::OGR_G_CreateGeometryFromJson(c_geojson.as_ptr()) };
if c_geom.is_null() {
return Err(_last_null_pointer_err("OGR_G_ExportToJson"));
}
Ok(unsafe { Geometry::with_c_geometry(c_geom, true) })
}

/// Serialize the geometry as WKT.
pub fn wkt(&self) -> Result<String> {
let mut c_wkt = null_mut();
Expand Down Expand Up @@ -118,4 +129,17 @@ mod tests {
let new_geom = Geometry::from_wkb(&wkb).unwrap();
assert_eq!(new_geom, orig_geom);
}

#[test]
pub fn test_geojson() {
let json = r#"{"type":"Point","coordinates":[10,20]}"#;
let geom = Geometry::from_geojson(json).unwrap();
let (x, y, _) = geom.get_point(0);
assert_eq!(x, 10.0);
assert_eq!(y, 20.0);

let json = r#"{"type":"Point","coordinates":[10,20}"#;
let res = Geometry::from_geojson(json);
assert!(res.is_err());
}
}

0 comments on commit e1224b2

Please sign in to comment.