egui-map-view 0.5.0

An slippy map viewer for egui applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! A layer for freeform drawing on the map.
//!
//! # Example
//!
//! ```no_run
//! use eframe::egui;
//! use egui_map_view::{layers::drawing::DrawingLayer, layers::drawing::DrawMode, Map, config::OpenStreetMapConfig};
//!
//! struct MyApp {
//!     map: Map,
//! }
//!
//! impl Default for MyApp {
//!   fn default() -> Self {
//!     let mut map = Map::new(OpenStreetMapConfig::default());
//!      map.add_layer("drawing", DrawingLayer::default());
//!      if let Some(drawing_layer) = map.layer_mut::<DrawingLayer>("drawing") {
//!        drawing_layer.draw_mode = DrawMode::Draw;
//!      }
//!      Self { map }
//!    }
//! }
//!
//! impl eframe::App for MyApp {
//!     fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
//!         egui::CentralPanel::default().show_inside(ui, |ui| {
//!             ui.add(&mut self.map);
//!         });
//!     }
//! }
//! ```
use crate::layers::{Layer, dist_sq_to_segment, projection_factor, serde_stroke};
use crate::projection::{GeoPos, MapProjection};
use egui::{Color32, Painter, Pos2, Response, Stroke};
use serde::{Deserialize, Serialize};
use std::any::Any;

/// A polyline on the map.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Polyline(pub Vec<GeoPos>);

/// The mode of the `DrawingLayer`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DrawMode {
    /// The layer is not interactive.
    #[default]
    Disabled,
    /// The user can draw on the map.
    Draw,
    /// The user can erase drawings.
    Erase,
}

/// Layer implementation that allows the user to draw polylines on the map.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DrawingLayer {
    polylines: Vec<Polyline>,

    /// The stroke style for drawing aka line width and color.
    #[serde(with = "serde_stroke")]
    pub stroke: Stroke,

    /// The current drawing mode.
    #[serde(skip)]
    pub draw_mode: DrawMode,
}

impl DrawingLayer {
    /// Serializes the layer to a `GeoJSON` `FeatureCollection`.
    #[cfg(feature = "geojson")]
    /// Serializes the layer to a `GeoJSON` `FeatureCollection`.
    #[cfg(feature = "geojson")]
    pub fn to_geojson_str(&self, layer_id: &str) -> Result<String, serde_json::Error> {
        let features: Vec<geojson::Feature> = self
            .polylines
            .clone()
            .into_iter()
            .map(|p| {
                let mut feature = geojson::Feature::from(p);
                if let Some(properties) = &mut feature.properties {
                    properties.insert(
                        "stroke_width".to_string(),
                        serde_json::Value::from(self.stroke.width),
                    );
                    properties.insert(
                        "stroke_color".to_string(),
                        serde_json::Value::String(self.stroke.color.to_hex()),
                    );
                    properties.insert(
                        "layer_id".to_string(),
                        serde_json::Value::String(layer_id.to_string()),
                    );
                }
                feature
            })
            .collect();

        let mut foreign_members = serde_json::Map::new();
        foreign_members.insert(
            "stroke_width".to_string(),
            serde_json::Value::from(self.stroke.width),
        );
        foreign_members.insert(
            "stroke_color".to_string(),
            serde_json::Value::String(self.stroke.color.to_hex()),
        );
        foreign_members.insert(
            "layer_id".to_string(),
            serde_json::Value::String(layer_id.to_string()),
        );

        let feature_collection = geojson::FeatureCollection {
            bbox: None,
            features,
            foreign_members: Some(foreign_members),
        };
        serde_json::to_string(&feature_collection)
    }

    /// Deserializes a `GeoJSON` `FeatureCollection` and adds the features to the layer.
    ///
    /// If `layer_id` is provided, only features with a matching `layer_id` property will be added.
    /// If `layer_id` is `None`, all valid features will be added.
    #[cfg(feature = "geojson")]
    pub fn from_geojson_str(
        &mut self,
        s: &str,
        layer_id: Option<&str>,
    ) -> Result<(), serde_json::Error> {
        let feature_collection: geojson::FeatureCollection = serde_json::from_str(s)?;
        let new_polylines: Vec<Polyline> = feature_collection
            .features
            .iter()
            .filter_map(|f| {
                // Filter by layer_id if provided
                if let Some(target_id) = layer_id {
                    if let Some(properties) = &f.properties {
                        if let Some(val) = properties.get("layer_id") {
                            if let Some(id) = val.as_str() {
                                if id != target_id {
                                    return None;
                                }
                            } else {
                                // layer_id property exists but is not a string, treat as mismatch
                                return None;
                            }
                        } else {
                            // layer_id property missing, treat as mismatch
                            return None;
                        }
                    } else {
                        // No properties, treat as mismatch
                        return None;
                    }
                }

                let polyline = Polyline::try_from(f.clone()).ok();
                if polyline.is_some()
                    && let Some(properties) = &f.properties
                {
                    if let Some(value) = properties.get("stroke_width")
                        && let Some(width) = value.as_f64()
                    {
                        self.stroke.width = width as f32;
                    }
                    if let Some(value) = properties.get("stroke_color")
                        && let Some(s) = value.as_str()
                        && let Ok(color) = Color32::from_hex(s)
                    {
                        self.stroke.color = color;
                    }
                }
                polyline
            })
            .collect();
        self.polylines.extend(new_polylines);

        if let Some(foreign_members) = feature_collection.foreign_members {
            if let Some(value) = foreign_members.get("stroke_width")
                && let Some(width) = value.as_f64()
            {
                self.stroke.width = width as f32;
            }
            if let Some(value) = foreign_members.get("stroke_color")
                && let Some(s) = value.as_str()
                && let Ok(color) = Color32::from_hex(s)
            {
                self.stroke.color = color;
            }
        }

        Ok(())
    }

    /// Creates a new `DrawingLayer`.
    #[must_use]
    pub fn new(stroke: Stroke) -> Self {
        Self {
            polylines: Vec::new(),
            stroke,
            draw_mode: DrawMode::default(),
        }
    }
}

impl Default for DrawingLayer {
    fn default() -> Self {
        Self {
            polylines: Vec::new(),
            stroke: Stroke::new(2.0, Color32::RED),
            draw_mode: DrawMode::default(),
        }
    }
}

impl DrawingLayer {
    fn handle_draw_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        if response.hovered() {
            response.ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
        }

        if response.clicked()
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            let geo_pos = projection.unproject(pointer_pos);
            if let Some(last_line) = self.polylines.last_mut()
                && response.ctx.input(|i| i.modifiers.shift)
            {
                last_line.0.push(geo_pos);
            } else {
                // No polylines exist yet, so create a new one.
                let geo_pos2 = projection.unproject(pointer_pos + egui::vec2(1.0, 0.0));
                self.polylines.push(Polyline(vec![geo_pos, geo_pos2]));
            }
        }

        if response.drag_started() {
            self.polylines.push(Polyline(Vec::new()));
        }

        if response.dragged()
            && let Some(pointer_pos) = response.interact_pointer_pos()
            && let Some(last_line) = self.polylines.last_mut()
        {
            let geo_pos = projection.unproject(pointer_pos);
            last_line.0.push(geo_pos);
        }

        // When drawing, we consume all interactions over the map,
        // so that the map does not pan or zoom.
        response.hovered()
    }

    fn handle_erase_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        if response.hovered() {
            response.ctx.set_cursor_icon(egui::CursorIcon::NotAllowed);
        }

        if (response.dragged() || response.clicked())
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            self.erase_at(pointer_pos, projection);
        }
        response.hovered()
    }

    fn erase_at(&mut self, pointer_pos: Pos2, projection: &MapProjection) {
        let erase_radius_screen = self.stroke.width;
        let erase_radius_sq = erase_radius_screen * erase_radius_screen;

        let old_polylines = std::mem::take(&mut self.polylines);
        self.polylines = old_polylines
            .into_iter()
            .flat_map(|polyline| {
                split_polyline_by_erase_circle(
                    &polyline.0,
                    pointer_pos,
                    erase_radius_sq,
                    projection,
                )
                .into_iter()
                .map(Polyline)
            })
            .collect();
    }
}

impl Layer for DrawingLayer {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn handle_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        match self.draw_mode {
            DrawMode::Disabled => false,
            DrawMode::Draw => self.handle_draw_input(response, projection),
            DrawMode::Erase => self.handle_erase_input(response, projection),
        }
    }

    fn draw(&self, painter: &Painter, projection: &MapProjection) {
        for polyline in &self.polylines {
            if polyline.0.len() > 1 {
                let screen_points: Vec<egui::Pos2> =
                    polyline.0.iter().map(|p| projection.project(*p)).collect();
                painter.add(egui::Shape::line(screen_points, self.stroke));
            }
        }
    }
}

/// Splits a polyline into multiple polylines based on whether segments are within the erase radius.
fn split_polyline_by_erase_circle(
    polyline: &[GeoPos],
    pointer_pos: Pos2,
    erase_radius_sq: f32,
    projection: &MapProjection,
) -> Vec<Vec<GeoPos>> {
    if polyline.len() < 2 {
        return vec![];
    }

    let screen_points: Vec<Pos2> = polyline.iter().map(|p| projection.project(*p)).collect();

    let mut new_polylines = Vec::new();
    let mut current_line = Vec::new();
    let mut in_visible_part = true;

    // Check if the first segment is erased to correctly set initial state.
    if dist_sq_to_segment(pointer_pos, screen_points[0], screen_points[1]) < erase_radius_sq {
        in_visible_part = false;
    } else {
        current_line.push(polyline[0]);
    }

    for i in 0..(polyline.len() - 1) {
        let p2_geo = polyline[i + 1];
        let p1_screen = screen_points[i];
        let p2_screen = screen_points[i + 1];

        let segment_is_erased =
            dist_sq_to_segment(pointer_pos, p1_screen, p2_screen) < erase_radius_sq;

        if in_visible_part {
            if segment_is_erased {
                // Transition from visible to erased.
                let t = projection_factor(pointer_pos, p1_screen, p2_screen);
                let split_point_screen = p1_screen.lerp(p2_screen, t);
                let split_point_geo = projection.unproject(split_point_screen);
                current_line.push(split_point_geo);

                if current_line.len() > 1 {
                    new_polylines.push(std::mem::take(&mut current_line));
                }
                in_visible_part = false;
            } else {
                // Continue visible part.
                current_line.push(p2_geo);
            }
        } else {
            // In erased part
            if !segment_is_erased {
                // Transition from erased to visible.
                let t = projection_factor(pointer_pos, p1_screen, p2_screen);
                let split_point_screen = p1_screen.lerp(p2_screen, t);
                let split_point_geo = projection.unproject(split_point_screen);

                // Start new line.
                current_line.push(split_point_geo);
                current_line.push(p2_geo);
                in_visible_part = true;
            }
            // Continue in erased part, do nothing.
        }
    }

    if current_line.len() > 1 {
        new_polylines.push(current_line);
    }

    new_polylines
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn drawing_layer_new() {
        let layer = DrawingLayer::default();
        assert_eq!(layer.draw_mode, DrawMode::Disabled);
        assert!(layer.polylines.is_empty());
    }

    #[test]
    fn drawing_layer_as_any() {
        let layer = DrawingLayer::default();
        assert!(layer.as_any().is::<DrawingLayer>());
    }

    #[test]
    fn drawing_layer_as_any_mut() {
        let mut layer = DrawingLayer::default();
        assert!(layer.as_any_mut().is::<DrawingLayer>());
    }

    #[test]
    fn drawing_layer_serde() {
        let mut layer = DrawingLayer::default();
        layer.draw_mode = DrawMode::Draw; // This should not be serialized.
        layer.polylines.push(Polyline(vec![
            GeoPos { lon: 1.0, lat: 2.0 },
            GeoPos { lon: 3.0, lat: 4.0 },
        ]));
        layer.stroke = Stroke::new(5.0, Color32::BLUE); // This should not be serialized.

        let json = serde_json::to_string(&layer).unwrap();

        // The serialized string should only contain polylines.
        assert!(json.contains(r##""polylines":[[{"lon":1.0,"lat":2.0},{"lon":3.0,"lat":4.0}]],"stroke":{"width":5.0,"color":"#0000ffff"}"##));
        assert!(!json.contains("draw_mode"));

        let deserialized: DrawingLayer = serde_json::from_str(&json).unwrap();

        // Check that polylines are restored correctly.
        assert_eq!(deserialized.polylines, layer.polylines);

        // Check that the stroke information is correct
        assert_eq!(deserialized.stroke.width, 5.0);
        assert_eq!(deserialized.stroke.color, Color32::BLUE);

        // Default is drawmode disabled and its not serializable
        assert_eq!(deserialized.draw_mode, DrawMode::Disabled);
    }

    #[cfg(feature = "geojson")]
    mod geojson_tests {
        use super::*;

        #[test]
        fn drawing_layer_geojson() {
            let mut layer = DrawingLayer::default();
            layer.polylines.push(Polyline(vec![
                (10.0, 20.0).into(),
                (30.0, 40.0).into(),
                (50.0, 60.0).into(),
            ]));
            layer.stroke = Stroke::new(5.0, Color32::BLUE);

            let geojson_str = layer.to_geojson_str("my_layer").unwrap();

            // Test deserialization with matching ID
            let mut new_layer = DrawingLayer::default();
            new_layer
                .from_geojson_str(&geojson_str, Some("my_layer"))
                .unwrap();

            assert_eq!(new_layer.polylines.len(), 1);
            assert_eq!(layer.polylines[0], new_layer.polylines[0]);
            assert_eq!(layer.stroke, new_layer.stroke);

            // Test deserialization with non-matching ID
            let mut other_layer = DrawingLayer::default();
            other_layer
                .from_geojson_str(&geojson_str, Some("other_layer"))
                .unwrap();
            assert_eq!(other_layer.polylines.len(), 0);

            // Test deserialization with None ID (should include all)
            let mut all_layer = DrawingLayer::default();
            all_layer.from_geojson_str(&geojson_str, None).unwrap();
            assert_eq!(all_layer.polylines.len(), 1);
        }
    }
}