How to iterate over points in the exterior ring of a geos::Polygon in rust

103 Views Asked by At

I have a geometry representing a polygon, I want to iterate of the points in the exterior ring. I tried following the same approach as this question but it doesn't seem to work in rust.

The get_exterior_ring function returns a ConstGeometry of type LinearRing. If I call get_num_points on this geometry it returns an error

 Err(
    GenericError(
        "Geometry must be a LineString",
    ),
)
let test_polygon: Polygon = Polygon::new(
  LineString(vec![
    Coord::from((4.9147899, 52.3735245)),
    Coord::from((4.9148563, 52.3735048)),
    Coord::from((4.9148865, 52.3735437)),
    Coord::from((4.9148248, 52.3735613)),
    Coord::from((4.9147899, 52.3735245)),
  ]),
  vec![LineString(vec![])],
);
let geometry: geos::Geometry = (&test_polygon).try_into().unwrap();
let linear_ring: ConstGeometry  = geometry.get_exterior_ring().unwrap();
dbg!(linear_ring.get_num_points().err());
1

There are 1 best solutions below

0
Eamonn McEvoy On

Answered here: https://github.com/georust/geos/issues/132

use geos::{ConstGeometry, CoordSeq, Geom};

let test_polygon: Polygon = Polygon::new(
    LineString(vec![
        Coord::from((4.9147899, 52.3735245)),
        Coord::from((4.9148563, 52.3735048)),
        Coord::from((4.9148865, 52.3735437)),
        Coord::from((4.9148248, 52.3735613)),
        Coord::from((4.9147899, 52.3735245)),
    ]),
    vec![LineString(vec![])],
);
let geometry: geos::Geometry = (&test_polygon).try_into().unwrap();
let linear_ring: ConstGeometry  = geometry.get_exterior_ring().unwrap();
let coord_seq: CoordSeq = linear_ring.get_coord_seq().unwrap();

let size = coord_seq.size().unwrap();
println!("coord_seq size: {}", size);

for i in 0..size {
    let (x, y) = (coord_seq.get_x(i).unwrap(), coord_seq.get_y(i).unwrap());
    println!("coord of point n°{}: {:?}", i, (x, y));
}