From e1224b2e88b872748387401f1070fb753a348b66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Thu, 2 Mar 2023 20:08:47 +0200 Subject: [PATCH] Add Geometry::from_geojson --- src/vector/ops/conversions/formats.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/vector/ops/conversions/formats.rs b/src/vector/ops/conversions/formats.rs index a3a82db9..e21a9b5d 100644 --- a/src/vector/ops/conversions/formats.rs +++ b/src/vector/ops/conversions/formats.rs @@ -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 { + 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 { let mut c_wkt = null_mut(); @@ -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()); + } }