Skip to main content

Map

Struct Map 

Source
pub struct Map {
    pub settings: MapSettings,
    /* private fields */
}
Expand description

An interactive 2D map widget.

Map renders a set of nodes (objects::MapPoint), connection lines (objects::MapSegment) and text labels (objects::MapLabel). The user can pan the view by dragging and zoom with the mouse wheel (hold Ctrl — or Cmd on macOS — to zoom faster), or use the built-in zoom slider drawn at the top-right corner of the widget.

The map is fed through Map::add_hashmap_points, which also builds the internal kd-tree used for viewport culling and nearest-node hover queries. Behavior and appearance are configured through the public settings field (see objects::MapSettings).

Rendering of nodes and their visual effects (selection highlight, notifications and markers) can be fully customized by installing a objects::NodeTemplate implementation with Map::set_node_template, and segments likewise with objects::SegmentTemplate and Map::set_segment_template; a right-click context menu can be provided with Map::set_context_manager.

§Examples

use egui_map::map::Map;
use egui_map::map::objects::MapPoint;
use std::collections::HashMap;

let mut points = HashMap::new();
points.insert(1, MapPoint::new(1, [0.0, 0.0]));

let mut map = Map::new();
map.add_hashmap_points(points);

// Every frame, inside your egui update logic:
ui.add(&mut map);

Fields§

§settings: MapSettings

Behavior and appearance configuration (zoom limits, visibility thresholds and per-theme styles). See objects::MapSettings.

Implementations§

Source§

impl Map

Source

pub fn new() -> Self

Creates an empty map widget with default MapSettings.

The widget displays nothing until nodes are loaded with Map::add_hashmap_points.

Source

pub fn add_points(&mut self, points: Vec<MapPoint>)

Loads the node set and (re)builds the spatial index.

This replaces any previously loaded points, computes the bounding box of the whole set, centers the view on its midpoint and refreshes the list of visible nodes. It must be called at least once before the widget can display anything.

The kd-tree built here is what enables viewport culling and nearest-neighbor hover lookups, so calling this method on every frame is discouraged; call it only when the node set changes.

§Examples
use egui_map::map::Map;
use egui_map::map::objects::MapPoint;

let mut points = Vec::new();
points.push(MapPoint::new(1, [0.0, 0.0]));
points.push(MapPoint::new(2, [10.0, 10.0]));

let mut map = Map::new();
map.add_points(points);

// The view is centered on the midpoint of the loaded nodes.
assert_eq!(map.get_pos(), [5.0, 5.0]);
Source

pub fn add_hashmap_points(&mut self, hash_map: HashMap<usize, MapPoint>)

Loads the node set and (re)builds the spatial index.

This replaces any previously loaded points, computes the bounding box of the whole set, centers the view on its midpoint and refreshes the list of visible nodes. It must be called at least once before the widget can display anything.

The kd-tree built here is what enables viewport culling and nearest-neighbor hover lookups, so calling this method on every frame is discouraged; call it only when the node set changes.

§Examples
use egui_map::map::Map;
use egui_map::map::objects::MapPoint;
use std::collections::HashMap;

let mut points = HashMap::new();
points.insert(1, MapPoint::new(1, [0.0, 0.0]));
points.insert(2, MapPoint::new(2, [10.0, 10.0]));

let mut map = Map::new();
map.add_hashmap_points(points);

// The view is centered on the midpoint of the loaded nodes.
assert_eq!(map.get_pos(), [5.0, 5.0]);
Source

pub fn set_pos_from_nodeid(&mut self, node_id: usize) -> bool

Centers the view on the node with the given id.

Returns true if the view moved. Returns false — leaving the view untouched — when no points have been loaded yet or when node_id is not among them; that case also emits a tracing warning, since a silently ignored id is otherwise indistinguishable from a node that was centered but drawn in the wrong place.

A false here usually means the id belongs to a different set than the one loaded through Map::add_hashmap_points — for example a map showing only part of the universe, or ids coming from a different query than the one that produced the nodes.

use egui_map::map::Map;
use egui_map::map::objects::MapPoint;

let mut map = Map::new();
map.add_points(vec![MapPoint::new(1, [10.0, 20.0])]);

assert!(map.set_pos_from_nodeid(1));
assert_eq!(map.get_pos(), [10.0, 20.0]);

// Unknown id: the view stays where it was.
assert!(!map.set_pos_from_nodeid(999));
assert_eq!(map.get_pos(), [10.0, 20.0]);
Source

pub fn set_pos(&mut self, position: [f32; 2])

Centers the view on the given map coordinates.

Source

pub fn get_pos(&self) -> [f32; 2]

Returns the map coordinates the view is currently centered on.

Source

pub fn add_labels(&mut self, labels: Vec<MapLabel>)

Replaces the set of free-floating text labels drawn on the map.

Labels are only rendered while the zoom level is below MapSettings::line_visible_zoom.

Source

pub fn add_lines(&mut self, segments: Vec<MapSegment>)

Replaces the set of connection lines between nodes.

Lines are keyed by a connection id that the endpoint nodes must reference through MapPoint::connections — push each line’s key into the connections of the nodes it joins. The segments are stored in an R-tree keyed by bounding box: a line is drawn while its bounding box intersects the viewport and the zoom level is above MapSettings::line_visible_zoom.

See the module-level example for the complete wiring.

Source

pub fn add_hashmap_lines( &mut self, segments: HashMap<(usize, usize), MapSegment>, )

Replaces the set of connection lines between nodes, from a map keyed by the same (usize, usize) id used in MapSegment::id and referenced by MapPoint::connections.

Equivalent to add_lines but avoids callers having to collect their segments into a Vec first when they already have them keyed in a HashMap (e.g. straight from an adapter that mirrors them 1:1 by id, with no intermediate ordering to preserve).

Source

pub fn set_zoom(&mut self, value: f32)

Sets the zoom factor.

Values outside the MapSettings::min_zoom..=MapSettings::max_zoom range are ignored.

Source

pub fn get_zoom(&mut self) -> f32

Returns the current zoom factor.

Source

pub fn notify(&mut self, id_node: usize, time: Instant)

👎Deprecated since 0.4.0:

use map.node(id) and pick an effect, e.g. if let Some(n) = map.node(id) { n.pulse(time) }

Triggers a pulsing notification on the node id_node.

§Deprecated

This only ever played one of the available effects. Use Map::node and pick the effect you want:

if let Some(node) = map.node(1) {
    node.pulse(time);
}

Note the one behavioural difference: notify accepts an id that was never loaded (the notification simply never draws), while Map::node returns None for it.

Source

pub fn node(&mut self, id: usize) -> Option<NodeHandle<'_>>

Borrows the node id so an animation can be attached to it.

Returns None when id was never loaded through Map::add_points / Map::add_hashmap_points, so a stale or mistyped id is a compile-time-visible case rather than a silent no-op.

The handle carries optional configuration that must be set before the effect, which is the terminal call:

// a one-off event
if let Some(node) = map.node(1) {
    node.color(egui::Color32::RED).ripple(time);
}

// lasting state, until cleared
if let Some(node) = map.node(1) {
    node.halo();
}

assert!(map.node(999).is_none());
Source

pub fn segment(&mut self, id: (usize, usize)) -> Option<SegmentHandle<'_>>

Borrows the segment id so an animation can be attached to it.

Returns None when id was never loaded through Map::add_lines / Map::add_hashmap_lines, mirroring Map::node. Use Map::line_at to find the id of the segment under a point first, e.g. to flash the route the mouse is hovering.

// a one-off event
if let Some(segment) = map.segment((1, 2)) {
    segment.color(egui::Color32::RED).flash(time);
}

// lasting state, until cleared
if let Some(segment) = map.segment((1, 2)) {
    segment.comet();
}

assert!(map.segment((404, 404)).is_none());
Source

pub fn line_at(&self, point: [f32; 2], tolerance: f32) -> Option<(usize, usize)>

Returns the id of the line closest to point, in map coordinates, when it lies within tolerance map units of the segment.

Broad-phase candidates are taken from the segment R-tree built by Map::add_lines; the exact point-to-segment distance is then computed against the line geometry and the closest match wins. Returns None when no lines are loaded or every segment is farther than tolerance. A negative tolerance behaves like 0.0.

To hit-test a mouse click, convert the screen position to map coordinates first (map = (screen + origin) / zoom, see the coordinate model) and pick a tolerance scaled by 1.0 / zoom so it stays constant in screen pixels.

Source

pub fn set_context_manager(&mut self, manager: Rc<dyn ContextMenuManager>)

Installs a right-click context menu whose contents are built by the given ContextMenuManager implementation.

Source

pub fn set_node_template(&mut self, template: Rc<dyn NodeTemplate>)

Replaces the built-in node rendering with a custom NodeTemplate implementation.

The template takes over the drawing of nodes, selection highlights, notification animations and markers — including the node name labels, which the widget no longer draws once a template is installed. See the NodeTemplate examples for custom shapes and animations.

Source

pub fn set_segment_template(&mut self, template: Rc<dyn SegmentTemplate>)

Replaces the built-in segment rendering with a custom SegmentTemplate implementation.

The template takes over the drawing of segments and their effects. See the SegmentTemplate examples for a custom line style and animation.

Source

pub fn set_theme(&mut self, new_theme: Rc<dyn MapTheme>)

Installs the color palette used to paint the map, replacing the default Theme::default.

Accepts any MapTheme implementation, including a built-in Theme variant – e.g. map.set_theme(Rc::new(Theme::ArticCyan)) – or a custom palette. The new colors are resolved live from new_theme on the very next frame, in whichever light/dark mode is active then – there is nothing to eagerly refresh, since Style never caches theme colors.

Source

pub fn update_marker(&mut self, id: usize, node_id: usize)

Adds the marker id, or moves it, so it points to the node node_id.

Markers are drawn as a blinking ring around the target node unless a custom objects::NodeTemplate::marker_ui is installed.

Source

pub fn allocate_at_least(&mut self, width: Option<f32>, height: Option<f32>)

Sets the minimum width and/or height the widget should occupy, in egui points. None leaves the corresponding dimension unconstrained.

Source

pub fn allocate_at_most(&mut self, width: Option<f32>, height: Option<f32>)

Sets the maximum width and/or height the widget should occupy, in egui points. None leaves the corresponding dimension unconstrained.

Trait Implementations§

Source§

impl Clone for Map

Source§

fn clone(&self) -> Map

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for Map

Source§

fn default() -> Self

Creates an empty map; equivalent to Map::new.

Source§

impl Widget for &mut Map

Source§

fn ui(self, ui: &mut Ui) -> Response

Renders the map, handling panning (drag), zooming (mouse wheel) and the right-click context menu if one was installed.

Source§

fn boxed<'a>(self) -> Box<dyn FnOnce(&mut Ui) -> Response + 'a>
where Self: Sized + 'a,

Box this widget for dynamic dispatch.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Map

§

impl !Send for Map

§

impl !Sync for Map

§

impl !UnwindSafe for Map

§

impl Freeze for Map

§

impl Unpin for Map

§

impl UnsafeUnpin for Map

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

Source§

fn simd_from(_simd: S, value: T) -> T

Source§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

Source§

fn simd_into(self, simd: S) -> T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more