Skip to content

Commit

Permalink
Merge #375
Browse files Browse the repository at this point in the history
375: Add Geometry::from_geojson r=metasim a=lnicola

- [x] I agree to follow the project's [code of conduct](https://github.com/georust/gdal/blob/master/CODE_OF_CONDUCT.md).
- [x] I added an entry to `CHANGES.md` if knowledge of this change could be valuable to users.
---



Co-authored-by: Laurențiu Nicola <[email protected]>
  • Loading branch information
bors[bot] and lnicola authored Mar 4, 2023
2 parents 1a4144d + 242de1d commit 86bf252
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

- Added `Geometry::from_geojson`

- <https://github.com/georust/gdal/pull/375>

- Added `CslStringList::add_string`

- <https://github.com/georust/gdal/pull/364>
Expand Down
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 86bf252

Please sign in to comment.