Skip to main content

egui_map_view/layers/area/
geojson.rs

1use super::layer::AreaLayer;
2use super::types::Area;
3
4#[cfg(feature = "geojson")]
5use ::geojson::{Feature, FeatureCollection};
6
7impl AreaLayer {
8    /// Serializes the layer to a `GeoJSON` `FeatureCollection`.
9    #[cfg(feature = "geojson")]
10    pub fn to_geojson_str(&self) -> Result<String, serde_json::Error> {
11        let features: Vec<Feature> = self
12            .areas
13            .clone()
14            .into_iter()
15            .map(Feature::from)
16            .collect();
17        let mut foreign_members = serde_json::Map::new();
18        foreign_members.insert(
19            "opacity".to_string(),
20            serde_json::Value::from(f64::from(self.opacity)),
21        );
22
23        let feature_collection = FeatureCollection {
24            bbox: None,
25            features,
26            foreign_members: Some(foreign_members),
27        };
28        serde_json::to_string(&feature_collection)
29    }
30
31    /// Deserializes a `GeoJSON` `FeatureCollection` and adds the features to the layer.
32    #[cfg(feature = "geojson")]
33    pub fn from_geojson_str(&mut self, s: &str) -> Result<(), serde_json::Error> {
34        let feature_collection: FeatureCollection = serde_json::from_str(s)?;
35        let new_areas: Vec<Area> = feature_collection
36            .features
37            .into_iter()
38            .filter_map(|f| Area::try_from(f).ok())
39            .collect();
40        self.areas.extend(new_areas);
41
42        if let Some(foreign_members) = feature_collection.foreign_members
43            && let Some(value) = foreign_members.get("opacity")
44            && let Some(opacity) = value.as_f64()
45        {
46            self.opacity = opacity as f32;
47        }
48        Ok(())
49    }
50}