I’m trying to convert from Shape
to a JSON string but I couldn’t create a string for Polygon
, I searched but I couldn’t find something that helps me.
In the code shows other types different to polygon bbox
and rings
, but with these types I can’t get structure of polygon
Full code from function
[dependencies]
shapefile = "0.6"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use shapefile::{ShapeReader, Shape, Polygon};
use serde_json::to_string;
use serde::Serialize;
fn shapes_to_json(path: &str) -> String {
let mut reader = match ShapeReader::from_path(path) {
Ok(reader) => reader,
Err(_) => return String::new(),
};
let mut geometries = Vec::new();
for shape in reader.iter_shapes() {
match shape {
Ok(Shape::Point(point)) => {
geometries.push(Geometry::Point {
coordinates: [point.x, point.y],
});
},
Ok(Shape::Polyline(polyline)) => {
let parts: Vec<Vec<[f64; 2]>> = polyline.parts().iter().map(|part| {
part.iter().map(|p| [p.x, p.y]).collect()
}).collect();
geometries.push(Geometry::LineString {
coordinates: parts.concat(),
});
},
Ok(Shape::Polygon(Polygon { points, parts })) => {
geometries.push(Geometry::Polygon {
coordinates: parts_to_coords(&parts, &points),
});
},
Err(_) => continue, // Skip or log errors
_ => {} // Optionally handle or skip other geometry types
}
}
// Convert the vector of geometries to JSON string
to_string(&geometries).unwrap_or_else(|_| String::new())
}
2