georust / geos

Rust bindings for GEOS
https://docs.rs/geos/
MIT License
122 stars 41 forks source link

How to iterate over points in a Polygon exterior ring? #132

Closed eamonnmcevoy closed 1 year ago

eamonnmcevoy commented 1 year ago

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());
mthh commented 1 year ago

I think you need to use the CoordSeq struct to iterate over the coordinates of your exterior ring, with something like :

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));
}
eamonnmcevoy commented 1 year ago

Perfect, thank you!