Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Walkers is a slippy map widget for egui. It runs natively and in the browser.

Each chapter of this book is built around a demo, a small app showing one feature. It runs right in the page, followed by its code. Every demo runs natively too, from Walkers’ repository:

cargo run -p demos -- raster

Raster tiles

OpenStreetMap’s raster tiles, the shortest way to a map.

Raster tiles are pictures, drawn as they come. HttpTiles fetches them from a tile server and keeps them, MapMemory keeps the map’s position and zoom between frames, and Map is the widget itself, built anew in every frame.

use eframe::{App, CreationContext, Frame};
use egui::Ui;
use walkers::{HttpTiles, Map, MapMemory, Tiles, lon_lat, sources::OpenStreetMap};

pub struct RasterMap {
    tiles: HttpTiles,
    map_memory: MapMemory,
}

impl RasterMap {
    pub fn new(cc: &CreationContext<'_>) -> Self {
        Self {
            tiles: HttpTiles::new(OpenStreetMap, cc.egui_ctx.clone()),
            map_memory: MapMemory::default(),
        }
    }
}

impl App for RasterMap {
    fn ui(&mut self, ui: &mut Ui, _frame: &mut Frame) {
        let attribution = self.tiles.attribution();
        let wroclaw = lon_lat(17.03664, 51.09916);

        Map::new(Some(&mut self.tiles), &mut self.map_memory, wroclaw).show(ui, |ui, _, _, _| {
            ui.hyperlink_to(attribution.text, attribution.url);
        });
    }
}

Tile servers ask to be credited, so the closure passed to show puts a link to the attribution on top of the map. Before shipping an app using OpenStreetMap’s tiles, read its tile usage policy.

Vector tiles

OpenFreeMap’s vector tiles, drawn with Waymark, Walkers’ own style.

Vector tiles carry the map’s geometry and names rather than a picture of them, so it is the style that decides how they look. A StyledSources draws a Style from sources it names, here OpenFreeMap’s tiles fetched by an HttpSource. Waymark draws from a source called openmaptiles, after the OpenMapTiles schema those tiles follow, and comes in the colors of a Palette, here the dark one.

impl WaymarkMap {
    pub fn new(cc: &CreationContext<'_>) -> Self {
        let ctx = &cc.egui_ctx;
        let style = Waymark::new(Palette::dark()).build();
        let tiles = HttpSource::new(OpenFreeMap, HttpOptions::default(), ctx.clone());

        Self {
            map: StyledSources::new(style, ctx.clone()).with_tiled_source("openmaptiles", tiles),
            map_memory: MapMemory::default(),
        }
    }
}

StyledSources keeps the tiles it has fetched, so, as HttpTiles for raster tiles, it is created once and added to the map as a layer in every frame. A map can have more than one source, so there is a link to each one’s attribution.

impl App for WaymarkMap {
    fn ui(&mut self, ui: &mut Ui, _frame: &mut Frame) {
        let attributions = self.map.attributions();
        let wroclaw = lon_lat(17.03664, 51.09916);

        Map::new(None, &mut self.map_memory, wroclaw)
            .with_layer(&mut self.map, 1.0)
            .show(ui, |ui, _, _, _| {
                for attribution in attributions {
                    ui.hyperlink_to(attribution.text, attribution.url);
                }
            });
    }
}

Vector tiles are drawn with wgpu, so walkers::install_renderer has to be called once on startup, with eframe’s wgpu_render_state:

    eframe::run_native(
        &format!("Walkers: {name}"),
        Default::default(),
        Box::new(move |cc| {
            walkers::install_renderer(cc.wgpu_render_state.as_ref());
            Ok(app(&name, cc).unwrap_or_else(|| Box::new(Unknown(name))))
        }),
    )

Full source

Your own data

This map shows a walk from Wrocław’s market square, over the island of Wyspa Piasek, to the cathedral. A drone circles over it. They come from the app’s own data, and the map’s style draws them like the rest of the map. The streets and the island’s shore are from OpenStreetMap.

The data

Your app’s own points, routes and areas are a Source. A MemorySource keeps them in memory. It holds a list of FeatureLayers. Each one has a name and a list of Features. A feature is a shape in longitude and latitude, with properties the style can read.

/// A walk from Wrocław's market square, over the island of Wyspa Piasek, to the cathedral. The
/// streets and the island's shore are from OpenStreetMap.
fn walk() -> Vec<FeatureLayer> {
    vec![
        FeatureLayer::new(
            "areas",
            vec![Feature::new(Polygon::new(
                LineString::from(vec![
                    (17.04009, 51.11552),
                    (17.03960, 51.11546),
                    (17.03907, 51.11534),
                    (17.03826, 51.11532),
                    (17.03820, 51.11519),
                    (17.03865, 51.11472),
                    (17.03860, 51.11471),
                    (17.03900, 51.11428),
                    (17.03936, 51.11393),
                    (17.03958, 51.11376),
                    (17.04018, 51.11358),
                    (17.04073, 51.11349),
                    (17.04116, 51.11353),
                    (17.04174, 51.11380),
                    (17.04205, 51.11398),
                    (17.04220, 51.11417),
                    (17.04214, 51.11442),
                    (17.04172, 51.11498),
                    (17.04130, 51.11539),
                    (17.04119, 51.11545),
                    (17.04095, 51.11554),
                    (17.04082, 51.11552),
                    (17.04081, 51.11555),
                    (17.04062, 51.11557),
                    (17.04009, 51.11552),
                ]),
                vec![],
            ))],
        ),
        FeatureLayer::new(
            "routes",
            vec![Feature::new(LineString::from(vec![
                (17.03351, 51.11050),
                (17.03477, 51.11344),
                (17.03505, 51.11377),
                (17.03529, 51.11379),
                (17.03558, 51.11390),
                (17.03560, 51.11439),
                (17.03574, 51.11459),
                (17.03634, 51.11448),
                (17.03929, 51.11320),
                (17.03960, 51.11328),
                (17.04082, 51.11492),
                (17.04107, 51.11491),
                (17.04158, 51.11475),
                (17.04340, 51.11459),
                (17.04436, 51.11435),
                (17.04546, 51.11419),
                (17.04590, 51.11425),
                (17.04624, 51.11439),
            ]))],
        ),
        FeatureLayer::new(
            "places",
            vec![
                Feature::new(lon_lat(17.03351, 51.11050)).with_property("name", "Start"),
                Feature::new(lon_lat(17.04624, 51.11439)).with_property("name", "Finish"),
            ],
        ),
    ]
}

/// The drone, circling over the walk.
fn drone_at(time: f64) -> Vec<FeatureLayer> {
    let angle = time * 0.05;
    let position = lon_lat(17.04 + 0.006 * angle.cos(), 51.113 + 0.004 * angle.sin());
    vec![FeatureLayer::new(
        "drones",
        vec![Feature::new(position).with_property("name", "Drone")],
    )]
}

Drawing it

Style layers draw your data the same way they draw tiles. Each layer names the source, and one of its layers as its source-layer. Here, a fill and a dashed line draw the island, and another line draws the route. Symbol layers label the places and the drone. The drone also gets an icon from the style.

A symbol layer can also put an icon along a line, every symbol-spacing pixels, turned the way the line goes. Here, small arrows along the route show which way the walk goes.

/// Layers drawing the walk, from a source called `walk`, under the basemap's labels, with arrows
/// along the route the way it goes.
fn walk_layers() -> Vec<StyleLayer> {
    vec![
        StyleLayer::Fill {
            source: Some("walk".into()),
            source_layer: "areas".into(),
            filter: None,
            paint: Paint {
                fill_color: Some(Color::from("#2a9d8f")),
                fill_opacity: Some(Float(json!(0.4))),
                ..Default::default()
            },
        },
        StyleLayer::Line {
            source: Some("walk".into()),
            source_layer: "areas".into(),
            filter: None,
            paint: Paint {
                line_color: Some(Color::from("#2a9d8f")),
                line_width: Some(Float(json!(2.0))),
                line_dasharray: Some(Dasharray(json!([3, 2]))),
                ..Default::default()
            },
        },
        StyleLayer::Line {
            source: Some("walk".into()),
            source_layer: "routes".into(),
            filter: None,
            paint: Paint {
                line_color: Some(Color::from("#e9c46a")),
                line_width: Some(Float(json!(4.0))),
                ..Default::default()
            },
        },
        StyleLayer::Symbol {
            source: Some("walk".into()),
            source_layer: "routes".into(),
            minzoom: None,
            filter: None,
            layout: Layout {
                icon_image: Some(json!("onwards")),
                symbol_spacing: Some(Float(json!(60.0))),
                ..Default::default()
            },
            paint: None,
        },
    ]
}

/// Labels of the walk and the drone, over the basemap's, so that they win where they overlap.
fn label_layers() -> Vec<StyleLayer> {
    let label = |source: &str, source_layer: &str, icon: Option<&str>| StyleLayer::Symbol {
        source: Some(source.into()),
        source_layer: source_layer.into(),
        minzoom: None,
        filter: None,
        layout: Layout {
            icon_image: icon.map(|icon| json!(icon)),
            text_field: Some(json!(["get", "name"])),
            text_anchor: Some(json!("top")),
            text_offset: Some(json!([0.0, 0.8])),
            ..Default::default()
        },
        paint: Some(Paint {
            text_color: Some(Color::from("#ffffff")),
            text_halo_color: Some(Color::from("#000000")),
            text_halo_width: Some(Float(json!(1.5))),
            ..Default::default()
        }),
    };
    vec![
        label("walk", "places", None),
        label("drone", "drones", Some("drone")),
    ]
}

Adding it to the map

You add these layers to Waymark’s style, between its own layers:

  • the walk goes under the map’s labels, so it does not hide street names
  • its labels go on top, so they win where labels overlap

Then with_source adds each MemorySource to the StyledSources. Use the same name the layers use.

impl FeaturesMap {
    pub fn new(cc: &CreationContext<'_>) -> Self {
        let ctx = &cc.egui_ctx;
        let mut style = Waymark::new(Palette::dark()).build();

        let basemap_labels = style
            .layers
            .iter()
            .position(|layer| matches!(layer, StyleLayer::Symbol { .. }))
            .unwrap_or(style.layers.len());
        style
            .layers
            .splice(basemap_labels..basemap_labels, walk_layers());
        style.layers.extend(label_layers());
        let diamond = vec![
            [0.0, -7.0],
            [7.0, 0.0],
            [0.0, 7.0],
            [-7.0, 0.0],
            [0.0, -7.0],
        ];
        style.icons.insert(
            "onwards".into(),
            vec![IconShape::line(
                vec![[-2.5, -4.0], [2.5, 0.0], [-2.5, 4.0]],
                "#1d3557",
                2.0,
            )],
        );
        style.icons.insert(
            "drone".into(),
            vec![
                IconShape::fill(diamond.clone(), "#e76f51"),
                IconShape::line(diamond, "#ffffff", 1.5),
            ],
        );

        let tiles = HttpSource::new(OpenFreeMap, HttpOptions::default(), ctx.clone());
        let drone = MemorySource::new(drone_at(0.0));
        let map = StyledSources::new(style, ctx.clone())
            .with_tiled_source("openmaptiles", tiles)
            .with_source("walk", MemorySource::new(walk()))
            .with_source("drone", drone.clone());

        let mut map_memory = MapMemory::default();
        let _ = map_memory.set_zoom(15.0);

        Self {
            map,
            map_memory,
            drone,
            reported: 0.0,
        }
    }
}

Changing it

A MemorySource and its clones share the same features. Keep one clone in your app, and call set on it when your data changes. The map draws the new features from the next frame.

Walkers styles your features again in every frame. This works well for tens or hundreds of features, even if they change every second.

impl App for FeaturesMap {
    fn ui(&mut self, ui: &mut Ui, _frame: &mut Frame) {
        // Once a second, as a real drone would report where it is.
        let second = ui.input(|input| input.time).floor();
        if second > self.reported {
            self.reported = second;
            self.drone.set(drone_at(second));
        }
        ui.ctx().request_repaint_after_secs(1.0);

        let attributions = self.map.attributions();
        let old_town: Position = lon_lat(17.0395, 51.1128);

        Map::new(None, &mut self.map_memory, old_town)
            .with_layer(&mut self.map, 1.0)
            .show(ui, |ui, _, _, _| {
                for attribution in attributions {
                    ui.hyperlink_to(attribution.text, attribution.url);
                }
            });
    }
}

Full source

GeoJSON

This map shows the street gyms in Wrocław. They are mapped in OpenStreetMap, and the app has them in a GeoJSON file, built into it.

The data

include_str! builds the file into the app, so there is nothing to download or read when it starts. A GeoJsonSource, from walkers_extras, turns the parsed GeoJSON into features.

/// Street gyms in Wrocław, from OpenStreetMap, built into the app.
fn street_gyms() -> GeoJsonSource {
    let geojson = include_str!("../assets/wroclaw-street-gyms.geojson")
        .parse()
        .expect("the bundled GeoJSON is valid");
    GeoJsonSource::new(geojson)
}

Drawing it

A GeoJsonSource puts all of its features in one layer. Style layers draw from it by leaving source-layer empty. Here a symbol layer draws each gym as an icon of the style: a dumbbell in an orange circle, made of four filled shapes.

/// Every gym as a dumbbell in an orange circle.
fn gym_style() -> Style {
    Style {
        layers: vec![StyleLayer::Symbol {
            source: None,
            source_layer: "".into(),
            minzoom: None,
            filter: None,
            layout: Layout {
                icon_image: Some(json!("gym")),
                ..Default::default()
            },
            paint: None,
        }],
        icons: [(
            "gym".to_string(),
            vec![
                IconShape::fill(circle(8.0), "#f4a261"),
                IconShape::fill(
                    vec![[-4.0, -1.0], [4.0, -1.0], [4.0, 1.0], [-4.0, 1.0]],
                    "#264653",
                ),
                IconShape::fill(
                    vec![[-6.0, -4.0], [-3.5, -4.0], [-3.5, 4.0], [-6.0, 4.0]],
                    "#264653",
                ),
                IconShape::fill(
                    vec![[3.5, -4.0], [6.0, -4.0], [6.0, 4.0], [3.5, 4.0]],
                    "#264653",
                ),
            ],
        )]
        .into(),
    }
}

/// Corners of a circle of that `radius`, around where the icon stands.
fn circle(radius: f32) -> Vec<[f32; 2]> {
    (0..16)
        .map(|corner| {
            let angle = corner as f32 * std::f32::consts::TAU / 16.0;
            [radius * angle.cos(), radius * angle.sin()]
        })
        .collect()
}

Adding it to the map

The gyms have a StyledSources of their own, which the map draws over the basemap.

impl GeoJsonMap {
    pub fn new(cc: &CreationContext<'_>) -> Self {
        let ctx = &cc.egui_ctx;
        let tiles = HttpSource::new(OpenFreeMap, HttpOptions::default(), ctx.clone());
        let mut map_memory = MapMemory::default();
        let _ = map_memory.set_zoom(13.0);

        Self {
            basemap: StyledSources::new(Waymark::new(Palette::dark()).build(), ctx.clone())
                .with_tiled_source("openmaptiles", tiles),
            gyms: StyledSources::new(gym_style(), ctx.clone()).with_source("gyms", street_gyms()),
            map_memory,
        }
    }
}
impl App for GeoJsonMap {
    fn ui(&mut self, ui: &mut Ui, _frame: &mut Frame) {
        let attributions = self.basemap.attributions();
        let wroclaw = lon_lat(17.03664, 51.10916);

        Map::new(None, &mut self.map_memory, wroclaw)
            .with_layer(&mut self.basemap, 1.0)
            .with_layer(&mut self.gyms, 1.0)
            .show(ui, |ui, _, _, _| {
                for attribution in attributions {
                    ui.hyperlink_to(attribution.text, attribution.url);
                }
            });
    }
}

Full source