egui_map_view/
lib.rs

1#![warn(missing_docs)]
2
3//! A simple map view widget for `egui`.
4//!
5//! This crate provides a `Map` widget that can be used to display a map from a tile server.
6//! It supports panning, zooming, and displaying the current mouse position in geographical coordinates.
7//!
8//! # Example
9//!
10//! ```no_run
11//! use eframe::egui;
12//! use egui_map_view::{Map, config::OpenStreetMapConfig};
13//!
14//! struct MyApp {
15//!     map: Map,
16//! }
17//!
18//! impl Default for MyApp {
19//!     fn default() -> Self {
20//!         Self {
21//!             map: Map::new(OpenStreetMapConfig::default()),
22//!         }
23//!     }
24//! }
25//!
26//! impl eframe::App for MyApp {
27//!     fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
28//!         egui::CentralPanel::default()
29//!             .frame(egui::Frame::NONE)
30//!             .show(ctx, |ui| {
31//!                if ui.add(&mut self.map).clicked() {
32//!                    if let Some(pos) = self.map.mouse_pos {
33//!                        println!("Map clicked at {} x {}", pos.lon, pos.lat);
34//!                    }
35//!                };
36//!             });
37//!     }
38//! }
39//! ```
40
41/// Configuration traits and types for the map widget.
42pub mod config;
43
44/// Map layers.
45#[cfg(feature = "layers")]
46pub mod layers;
47
48/// Map projection.
49pub mod projection;
50
51use eframe::egui;
52use egui::{Color32, NumExt, Rect, Response, Sense, Ui, Vec2, Widget, pos2};
53use eyre::{Context, Result};
54use log::{debug, error};
55use once_cell::sync::Lazy;
56use poll_promise::Promise;
57use std::collections::{BTreeMap, HashMap};
58use std::sync::Arc;
59use thiserror::Error;
60
61use crate::config::MapConfig;
62use crate::layers::Layer;
63use crate::projection::{GeoPos, MapProjection};
64
65// The size of a map tile in pixels.
66const TILE_SIZE: u32 = 256;
67/// The minimum zoom level.
68pub const MIN_ZOOM: u8 = 0;
69/// The maximum zoom level.
70pub const MAX_ZOOM: u8 = 19;
71
72// Reuse the reqwest client for all tile downloads by making it a static variable.
73static CLIENT: Lazy<reqwest::blocking::Client> = Lazy::new(|| {
74    reqwest::blocking::Client::builder()
75        .user_agent(format!(
76            "{}/{}",
77            env!("CARGO_PKG_NAME"),
78            env!("CARGO_PKG_VERSION")
79        ))
80        .build()
81        .expect("Failed to build reqwest client")
82});
83
84/// Errors that can occur while using the map widget.
85#[derive(Error, Debug)]
86pub enum MapError {
87    /// An error occurred while making a web request.
88    #[error("Connection error")]
89    ConnectionError(#[from] reqwest::Error),
90
91    /// A map tile failed to download.
92    #[error("A map tile failed to download. HTTP Status: `{0}`")]
93    TileDownloadError(String),
94
95    /// The downloaded tile bytes could not be converted to an image.
96    #[error("Unable to convert downloaded map tile bytes as image")]
97    TileBytesConversionError(#[from] image::ImageError),
98}
99
100/// A unique identifier for a map tile.
101#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
102pub struct TileId {
103    /// The zoom level.
104    pub z: u8,
105
106    /// The x-coordinate of the tile.
107    pub x: u32,
108
109    /// The y-coordinate of the tile.
110    pub y: u32,
111}
112
113impl TileId {
114    fn to_url(&self, config: &dyn MapConfig) -> String {
115        config.tile_url(self)
116    }
117}
118
119/// The state of a tile in the cache.
120enum Tile {
121    /// The tile is being downloaded.
122    Loading(Promise<Result<egui::ColorImage, Arc<eyre::Report>>>),
123
124    /// The tile is in memory.
125    Loaded(egui::TextureHandle),
126
127    /// The tile failed to download.
128    Failed(Arc<eyre::Report>),
129}
130
131/// The map widget.
132pub struct Map {
133    /// The geographical center of the map. (longitude, latitude)
134    pub center: GeoPos,
135
136    /// The zoom level of the map.
137    pub zoom: u8,
138
139    tiles: HashMap<TileId, Tile>,
140
141    /// The geographical position under the mouse pointer, if any. (longitude, latitude)
142    pub mouse_pos: Option<GeoPos>,
143
144    /// Configuration for the map, such as the tile server URL.
145    config: Box<dyn MapConfig>,
146
147    /// Layers to be drawn on top of the base map.
148    layers: BTreeMap<String, Box<dyn Layer>>,
149}
150
151impl Map {
152    /// Creates a new `Map` widget.
153    ///
154    /// # Arguments
155    ///
156    /// * `config` - A type that implements `MapConfig`, which provides configuration for the map.
157    pub fn new<C: MapConfig + 'static>(config: C) -> Self {
158        let center = GeoPos::from(config.default_center());
159        let zoom = config.default_zoom();
160        Self {
161            tiles: HashMap::new(),
162            mouse_pos: None,
163            config: Box::new(config),
164            center,
165            zoom,
166            layers: BTreeMap::new(),
167        }
168    }
169
170    /// Adds a layer to the map.
171    pub fn add_layer(&mut self, key: impl Into<String>, layer: impl Layer + 'static) {
172        self.layers.insert(key.into(), Box::new(layer));
173    }
174
175    /// Remove a layer from the map
176    pub fn remove_layer(&mut self, key: &str) -> bool {
177        if self.layers.remove(key).is_some() {
178            true
179        } else {
180            false
181        }
182    }
183
184    /// Get a reference to the layers.
185    pub fn layers(&self) -> &BTreeMap<String, Box<dyn Layer>> {
186        &self.layers
187    }
188
189    /// Get a mutable reference to the layers.
190    pub fn layers_mut(&mut self) -> &mut BTreeMap<String, Box<dyn Layer>> {
191        &mut self.layers
192    }
193
194    /// Get a reference to a specific layer.
195    pub fn layer<T: Layer>(&self, key: &str) -> Option<&T> {
196        self.layers
197            .get(key)
198            .and_then(|layer| layer.as_any().downcast_ref::<T>())
199    }
200
201    /// Get a mutable reference to a specific layer.
202    pub fn layer_mut<T: Layer>(&mut self, key: &str) -> Option<&mut T> {
203        self.layers
204            .get_mut(key)
205            .and_then(|layer| layer.as_any_mut().downcast_mut::<T>())
206    }
207
208    /// Handles user input for panning and zooming.
209    fn handle_input(&mut self, ui: &Ui, rect: &Rect, response: &Response) {
210        // Handle panning
211        if response.dragged() {
212            let delta = response.drag_delta();
213            let center_in_tiles_x = lon_to_x(self.center.lon, self.zoom);
214            let center_in_tiles_y = lat_to_y(self.center.lat, self.zoom);
215
216            let mut new_center_x = center_in_tiles_x - (delta.x as f64 / TILE_SIZE as f64);
217            let mut new_center_y = center_in_tiles_y - (delta.y as f64 / TILE_SIZE as f64);
218
219            // Clamp the new center to the map boundaries.
220            let world_size_in_tiles = 2.0_f64.powi(self.zoom as i32);
221            let view_size_in_tiles_x = rect.width() as f64 / TILE_SIZE as f64;
222            let view_size_in_tiles_y = rect.height() as f64 / TILE_SIZE as f64;
223
224            let min_center_x = view_size_in_tiles_x / 2.0;
225            let max_center_x = world_size_in_tiles - view_size_in_tiles_x / 2.0;
226            let min_center_y = view_size_in_tiles_y / 2.0;
227            let max_center_y = world_size_in_tiles - view_size_in_tiles_y / 2.0;
228
229            // If the map is smaller than the viewport, center it. Otherwise, clamp the center.
230            new_center_x = if min_center_x > max_center_x {
231                world_size_in_tiles / 2.0
232            } else {
233                new_center_x.clamp(min_center_x, max_center_x)
234            };
235            new_center_y = if min_center_y > max_center_y {
236                world_size_in_tiles / 2.0
237            } else {
238                new_center_y.clamp(min_center_y, max_center_y)
239            };
240
241            self.center = (
242                x_to_lon(new_center_x, self.zoom),
243                y_to_lat(new_center_y, self.zoom),
244            )
245                .into();
246        }
247
248        // Handle double-click to zoom and center
249        if response.double_clicked() {
250            if let Some(pointer_pos) = response.interact_pointer_pos() {
251                let new_zoom = (self.zoom + 1).clamp(MIN_ZOOM, MAX_ZOOM);
252
253                if new_zoom != self.zoom {
254                    // Determine the geo-coordinate under the mouse cursor before the zoom
255                    let mouse_rel = pointer_pos - rect.min;
256                    let center_x = lon_to_x(self.center.lon, self.zoom);
257                    let center_y = lat_to_y(self.center.lat, self.zoom);
258                    let widget_center_x = rect.width() as f64 / 2.0;
259                    let widget_center_y = rect.height() as f64 / 2.0;
260
261                    let target_x =
262                        center_x + (mouse_rel.x as f64 - widget_center_x) / TILE_SIZE as f64;
263                    let target_y =
264                        center_y + (mouse_rel.y as f64 - widget_center_y) / TILE_SIZE as f64;
265
266                    let new_center_lon = x_to_lon(target_x, self.zoom);
267                    let new_center_lat = y_to_lat(target_y, self.zoom);
268
269                    // Set the new zoom level and center the map on the clicked location
270                    self.zoom = new_zoom;
271                    self.center = (new_center_lon, new_center_lat).into();
272                }
273            }
274        }
275
276        // Handle scroll-to-zoom
277        if response.hovered() {
278            if let Some(mouse_pos) = response.hover_pos() {
279                let mouse_rel = mouse_pos - rect.min;
280
281                // Determine the geo-coordinate under the mouse cursor.
282                let center_x = lon_to_x(self.center.lon, self.zoom);
283                let center_y = lat_to_y(self.center.lat, self.zoom);
284                let widget_center_x = rect.width() as f64 / 2.0;
285                let widget_center_y = rect.height() as f64 / 2.0;
286
287                let target_x = center_x + (mouse_rel.x as f64 - widget_center_x) / TILE_SIZE as f64;
288                let target_y = center_y + (mouse_rel.y as f64 - widget_center_y) / TILE_SIZE as f64;
289
290                let scroll = ui.input(|i| i.raw_scroll_delta.y);
291                if scroll != 0.0 {
292                    let old_zoom = self.zoom;
293                    let mut new_zoom = (self.zoom as i32 + scroll.signum() as i32)
294                        .clamp(MIN_ZOOM as i32, MAX_ZOOM as i32)
295                        as u8;
296
297                    // If we are zooming out, check if the new zoom level is valid.
298                    if scroll < 0.0 {
299                        let world_pixel_size = 2.0_f64.powi(new_zoom as i32) * TILE_SIZE as f64;
300                        // If the world size would become smaller than the widget size, reject the zoom.
301                        if world_pixel_size < rect.width() as f64
302                            || world_pixel_size < rect.height() as f64
303                        {
304                            new_zoom = old_zoom; // Effectively cancel the zoom by reverting to the old value.
305                        }
306                    }
307
308                    if new_zoom != old_zoom {
309                        let target_lon = x_to_lon(target_x, old_zoom);
310                        let target_lat = y_to_lat(target_y, old_zoom);
311
312                        // Set the new zoom level
313                        self.zoom = new_zoom;
314
315                        // Adjust the map center so the geo-coordinate under the mouse remains the
316                        // same
317                        let new_target_x = lon_to_x(target_lon, new_zoom);
318                        let new_target_y = lat_to_y(target_lat, new_zoom);
319
320                        let new_center_x = new_target_x
321                            - (mouse_rel.x as f64 - widget_center_x) / TILE_SIZE as f64;
322                        let new_center_y = new_target_y
323                            - (mouse_rel.y as f64 - widget_center_y) / TILE_SIZE as f64;
324
325                        self.center = (
326                            x_to_lon(new_center_x, new_zoom),
327                            y_to_lat(new_center_y, new_zoom),
328                        )
329                            .into();
330                    }
331                }
332            }
333        }
334    }
335
336    /// Draws the attribution text.
337    fn draw_attribution(&self, ui: &mut Ui, rect: &Rect) {
338        // Check if the widget is scrolled out of view or clipped.
339        if !ui.is_rect_visible(*rect) {
340            return;
341        }
342
343        if let Some(attribution) = self.config.attribution() {
344            let (_text_color, bg_color) = if ui.visuals().dark_mode {
345                (Color32::from_gray(230), Color32::from_black_alpha(150))
346            } else {
347                (Color32::from_gray(80), Color32::from_white_alpha(150))
348            };
349
350            let frame = egui::Frame::NONE
351                .inner_margin(egui::Margin::same(5)) // A bit of padding around the label/URL element
352                .fill(bg_color)
353                .corner_radius(3.0); // Round the edges
354
355            egui::Area::new(ui.id().with("attribution"))
356                // pivot(egui::Align2::LEFT_BOTTOM) tells the Area that its position should be
357                //  calculated from its bottom-left corner, not its top-left.
358                .pivot(egui::Align2::LEFT_BOTTOM)
359                // fixed_pos(rect.left_bottom() + egui::vec2(5.0, -5.0)) now positions the Area's
360                //  bottom-left corner at the map's bottom-left corner, with a small margin to bring
361                //  it nicely inside the map's bounds.
362                .fixed_pos(rect.left_bottom() + egui::vec2(5.0, -5.0))
363                .show(ui.ctx(), |ui| {
364                    frame.show(ui, |ui| {
365                        ui.style_mut().override_text_style = Some(egui::TextStyle::Small);
366                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); // Don't wrap attribution text.
367
368                        if let Some(url) = self.config.attribution_url() {
369                            ui.hyperlink_to(attribution, url);
370                        } else {
371                            ui.label(attribution);
372                        }
373                    });
374                });
375        }
376    }
377}
378
379/// Converts longitude to the x-coordinate of a tile at a given zoom level.
380fn lon_to_x(lon: f64, zoom: u8) -> f64 {
381    (lon + 180.0) / 360.0 * (2.0_f64.powi(zoom as i32))
382}
383
384/// Converts latitude to the y-coordinate of a tile at a given zoom level.
385fn lat_to_y(lat: f64, zoom: u8) -> f64 {
386    (1.0 - lat.to_radians().tan().asinh() / std::f64::consts::PI) / 2.0
387        * (2.0_f64.powi(zoom as i32))
388}
389
390/// Converts the x-coordinate of a tile to longitude at a given zoom level.
391fn x_to_lon(x: f64, zoom: u8) -> f64 {
392    x / (2.0_f64.powi(zoom as i32)) * 360.0 - 180.0
393}
394
395/// Converts the y-coordinate of a tile to latitude at a given zoom level.
396fn y_to_lat(y: f64, zoom: u8) -> f64 {
397    let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y / (2.0_f64.powi(zoom as i32));
398    n.sinh().atan().to_degrees()
399}
400
401/// Draws the map tiles.
402pub(crate) fn draw_map(
403    tiles: &mut HashMap<TileId, Tile>,
404    config: &dyn MapConfig,
405    painter: &egui::Painter,
406    projection: &MapProjection,
407) {
408    let visible_tiles: Vec<_> = visible_tiles(projection).collect();
409    for (tile_id, tile_pos) in visible_tiles {
410        load_tile(tiles, config, &painter.ctx(), tile_id);
411        draw_tile(tiles, painter, &tile_id, tile_pos, Color32::WHITE);
412    }
413}
414
415/// Returns an iterator over the visible tiles.
416pub(crate) fn visible_tiles(
417    projection: &MapProjection,
418) -> impl Iterator<Item = (TileId, egui::Pos2)> {
419    let center_x = lon_to_x(projection.center_lon, projection.zoom);
420    let center_y = lat_to_y(projection.center_lat, projection.zoom);
421
422    let widget_center_x = projection.widget_rect.width() / 2.0;
423    let widget_center_y = projection.widget_rect.height() / 2.0;
424
425    let x_min = (center_x - widget_center_x as f64 / TILE_SIZE as f64).floor() as i32;
426    let y_min = (center_y - widget_center_y as f64 / TILE_SIZE as f64).floor() as i32;
427    let x_max = (center_x + widget_center_x as f64 / TILE_SIZE as f64).ceil() as i32;
428    let y_max = (center_y + widget_center_y as f64 / TILE_SIZE as f64).ceil() as i32;
429
430    let zoom = projection.zoom;
431    let rect_min = projection.widget_rect.min;
432    (x_min..=x_max).flat_map(move |x| {
433        (y_min..=y_max).map(move |y| {
434            let tile_id = TileId {
435                z: zoom,
436                x: x as u32,
437                y: y as u32,
438            };
439            let screen_x = widget_center_x + (x as f64 - center_x) as f32 * TILE_SIZE as f32;
440            let screen_y = widget_center_y + (y as f64 - center_y) as f32 * TILE_SIZE as f32;
441            let tile_pos = rect_min + Vec2::new(screen_x, screen_y);
442            (tile_id, tile_pos)
443        })
444    })
445}
446
447/// map loads tile as a texture
448pub(crate) fn load_tile(
449    tiles: &mut HashMap<TileId, Tile>,
450    config: &dyn MapConfig,
451    ctx: &egui::Context,
452    tile_id: TileId,
453) {
454    let tile_state = tiles.entry(tile_id).or_insert_with(|| {
455        let url = tile_id.to_url(config);
456        let promise =
457            Promise::spawn_thread("download_tile", move || -> Result<_, Arc<eyre::Report>> {
458                let result: Result<_, eyre::Report> = (|| {
459                    debug!("Downloading tile from {}", &url);
460                    let response = CLIENT.get(&url).send().map_err(MapError::from)?;
461
462                    if !response.status().is_success() {
463                        return Err(MapError::TileDownloadError(response.status().to_string()));
464                    }
465
466                    let bytes = response.bytes().map_err(MapError::from)?.to_vec();
467                    let image = image::load_from_memory(&bytes)
468                        .map_err(MapError::from)?
469                        .to_rgba8();
470
471                    let size = [image.width() as _, image.height() as _];
472                    let pixels = image.into_raw();
473                    Ok(egui::ColorImage::from_rgba_unmultiplied(size, &pixels))
474                })()
475                .with_context(|| format!("Failed to download tile from {}", &url));
476
477                result.map_err(Arc::new)
478            });
479        Tile::Loading(promise)
480    });
481
482    // If the tile is loading, check if the promise is ready and update the state.
483    // This is done before matching on the state, so that we can immediately draw
484    // the tile if it has just finished loading.
485    if let Tile::Loading(promise) = tile_state {
486        if let Some(result) = promise.ready() {
487            match result {
488                Ok(color_image) => {
489                    let texture = ctx.load_texture(
490                        format!("tile_{}_{}_{}", tile_id.z, tile_id.x, tile_id.y),
491                        color_image.clone(),
492                        Default::default(),
493                    );
494                    *tile_state = Tile::Loaded(texture);
495                }
496                Err(e) => {
497                    error!("{:?}", e);
498                    *tile_state = Tile::Failed(e.clone());
499                }
500            }
501        }
502    }
503}
504
505/// Draws a single map tile.
506pub(crate) fn draw_tile(
507    tiles: &HashMap<TileId, Tile>,
508    painter: &egui::Painter,
509    tile_id: &TileId,
510    tile_pos: egui::Pos2,
511    tint: Color32,
512) {
513    let tile_rect = Rect::from_min_size(tile_pos, Vec2::new(TILE_SIZE as f32, TILE_SIZE as f32));
514    let tile_state = tiles.get(tile_id).unwrap();
515    match tile_state {
516        Tile::Loading(_) => {
517            // Draw a gray background and a border for the placeholder.
518            painter.rect_filled(tile_rect, 0.0, Color32::from_gray(220));
519            painter.rect_stroke(
520                tile_rect,
521                0.0,
522                egui::Stroke::new(1.0, Color32::GRAY),
523                egui::StrokeKind::Inside,
524            );
525
526            // Draw a question mark in the center.
527            painter.text(
528                tile_rect.center(),
529                egui::Align2::CENTER_CENTER,
530                "?",
531                egui::FontId::proportional(40.0),
532                Color32::ORANGE,
533            );
534
535            // The tile is still loading, so we need to tell egui to repaint.
536            painter.ctx().request_repaint();
537        }
538        Tile::Loaded(texture) => {
539            painter.image(
540                texture.id(),
541                tile_rect,
542                Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
543                tint,
544            );
545        }
546        Tile::Failed(e) => {
547            // Draw a gray background and a border for the placeholder.
548            painter.rect_filled(tile_rect, 0.0, Color32::from_gray(220));
549            painter.rect_stroke(
550                tile_rect,
551                0.0,
552                egui::Stroke::new(1.0, Color32::GRAY),
553                egui::StrokeKind::Inside,
554            );
555
556            // Draw a red exclamation mark in the center.
557            painter.text(
558                tile_rect.center(),
559                egui::Align2::CENTER_CENTER,
560                "!",
561                egui::FontId::proportional(40.0),
562                Color32::RED,
563            );
564
565            // Log the error message
566            error!("Failed to load tile: {:?}", e);
567        }
568    }
569}
570
571impl Widget for &mut Map {
572    fn ui(self, ui: &mut Ui) -> Response {
573        // Give it a minimum size so that it does not become too small
574        // in a horizontal layout. Use tile size as minimum.
575        let desired_size = if ui.layout().main_dir().is_horizontal() {
576            // In a horizontal layout, we want to be a square of a reasonable size.
577            let side = TILE_SIZE as f32;
578            Vec2::splat(side)
579        } else {
580            // In a vertical layout, we want to fill the available space, but only width
581            let mut available_size = ui
582                .available_size()
583                .at_least(Vec2::new(TILE_SIZE as f32, TILE_SIZE as f32));
584            available_size.y = TILE_SIZE as f32;
585            available_size
586        };
587
588        let response = ui.allocate_response(desired_size, Sense::drag().union(Sense::click()));
589        let rect = response.rect;
590
591        // Create a projection for input handling, based on the state before any changes.
592        let input_projection = MapProjection::new(self.zoom, self.center, rect);
593
594        let mut input_handled_by_layer = false;
595        for layer in self.layers.values_mut() {
596            if layer.handle_input(&response, &input_projection) {
597                input_handled_by_layer = true;
598                break; // Stop after the first layer handles the input.
599            }
600        }
601
602        if !input_handled_by_layer {
603            self.handle_input(ui, &rect, &response);
604
605            // Change the cursor icon when dragging or hovering over the map.
606            if response.dragged() {
607                ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
608            } else if response.hovered() {
609                ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
610            }
611        }
612
613        // Update mouse position.
614        self.mouse_pos = response
615            .hover_pos()
616            .map(|pos| input_projection.unproject(pos));
617
618        // Create a new projection for drawing, with the updated map state.
619        let draw_projection = MapProjection::new(self.zoom, self.center, rect);
620
621        let painter = ui.painter_at(rect);
622        painter.rect_filled(rect, 0.0, Color32::from_rgb(220, 220, 220)); // Background
623
624        draw_map(
625            &mut self.tiles,
626            self.config.as_ref(),
627            &painter,
628            &draw_projection,
629        );
630
631        for layer in self.layers.values() {
632            layer.draw(&painter, &draw_projection);
633        }
634
635        self.draw_attribution(ui, &rect);
636
637        response
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644    use crate::config::OpenStreetMapConfig;
645
646    const EPSILON: f64 = 1e-9;
647
648    #[test]
649    fn test_coord_conversion_roundtrip() {
650        let original_lon = 24.93545;
651        let original_lat = 60.16952;
652        let zoom: u8 = 10;
653
654        let x = lon_to_x(original_lon, zoom);
655        let y = lat_to_y(original_lat, zoom);
656
657        let final_lon = x_to_lon(x, zoom);
658        let final_lat = y_to_lat(y, zoom);
659
660        assert!((original_lon - final_lon).abs() < EPSILON);
661        assert!((original_lat - final_lat).abs() < EPSILON);
662
663        let original_lon = -122.4194;
664        let original_lat = 37.7749;
665
666        let x = lon_to_x(original_lon, zoom);
667        let y = lat_to_y(original_lat, zoom);
668
669        let final_lon = x_to_lon(x, zoom);
670        let final_lat = y_to_lat(y, zoom);
671
672        assert!((original_lon - final_lon).abs() < EPSILON);
673        assert!((original_lat - final_lat).abs() < EPSILON);
674    }
675
676    #[test]
677    fn test_y_to_lat_conversion() {
678        // y, zoom, expected_lat
679        let test_cases = vec![
680            // Equator
681            (0.5, 0, 0.0),
682            (128.0, 8, 0.0),
683            // Near poles (Mercator projection limits)
684            (0.0, 0, 85.0511287798),
685            (1.0, 0, -85.0511287798),
686            (0.0, 8, 85.0511287798),
687            (256.0, 8, -85.0511287798),
688            // Helsinki
689            (9.262574089998255, 5, 60.16952),
690            // London
691            (85.12653378959828, 8, 51.5074),
692        ];
693
694        for (y, zoom, expected_lat) in test_cases {
695            assert!((y_to_lat(y, zoom) - expected_lat).abs() < EPSILON);
696        }
697    }
698
699    #[test]
700    fn test_lat_to_y_conversion() {
701        // lat, zoom, expected_y
702        let test_cases = vec![
703            // Equator
704            (0.0, 0, 0.5),
705            (0.0, 8, 128.0),
706            // Near poles (Mercator projection limits)
707            (85.0511287798, 0, 0.0),
708            (-85.0511287798, 0, 1.0),
709            (85.0511287798, 8, 0.0),
710            (-85.0511287798, 8, 256.0),
711            // Helsinki
712            (60.16952, 5, 9.262574089998255),
713            // London
714            (51.5074, 8, 85.12653378959828),
715        ];
716
717        for (lat, zoom, expected_y) in test_cases {
718            assert!((lat_to_y(lat, zoom) - expected_y).abs() < EPSILON);
719        }
720    }
721
722    #[test]
723    fn test_x_to_lon_conversion() {
724        // x, zoom, expected_lon
725        let test_cases = vec![
726            // Center of the map
727            (0.5, 0, 0.0),
728            (128.0, 8, 0.0),
729            // Edges of the map
730            (0.0, 0, -180.0),
731            (1.0, 0, 180.0),
732            (0.0, 8, -180.0),
733            (256.0, 8, 180.0),
734            // Helsinki
735            (18.216484444444444, 5, 24.93545),
736        ];
737
738        for (x, zoom, expected_lon) in test_cases {
739            assert!((x_to_lon(x, zoom) - expected_lon).abs() < EPSILON);
740        }
741    }
742
743    #[test]
744    fn test_lon_to_x_conversion() {
745        // lon, zoom, expected_x
746        let test_cases = vec![
747            // Center of the map
748            (0.0, 0, 0.5),
749            (0.0, 8, 128.0),
750            // Edges of the map
751            (-180.0, 0, 0.0),
752            (180.0, 0, 1.0), // upper bound is exclusive for tiles, but not for coordinate space
753            (-180.0, 8, 0.0),
754            (180.0, 8, 256.0),
755            // Helsinki
756            (24.93545, 5, 18.216484444444444),
757            // London
758            (-0.1275, 8, 127.90933333333333),
759        ];
760
761        for (lon, zoom, expected_x) in test_cases {
762            assert!((lon_to_x(lon, zoom) - expected_x).abs() < EPSILON);
763        }
764    }
765
766    #[test]
767    fn test_tile_id_to_url() {
768        let config = OpenStreetMapConfig::default();
769        let tile_id = TileId {
770            z: 10,
771            x: 559,
772            y: 330,
773        };
774        let url = tile_id.to_url(&config);
775        assert_eq!(url, "https://tile.openstreetmap.org/10/559/330.png");
776    }
777
778    #[test]
779    fn test_map_new() {
780        let config = OpenStreetMapConfig::default();
781        let default_center = config.default_center();
782        let default_zoom = config.default_zoom();
783
784        let map = Map::new(config);
785
786        assert_eq!(map.center, default_center.into());
787        assert_eq!(map.zoom, default_zoom);
788        assert!(map.mouse_pos.is_none());
789        assert!(map.tiles.is_empty());
790    }
791}