Skip to main content

Events

Struct Events 

Source
pub struct Events { /* private fields */ }
Expand description

Layer events for a set of layers. See the module docs.

Implementations§

Source§

impl Events

Source

pub fn new(layers: &[&str]) -> Self

Events for these layers (style or custom layer ids).

Examples found in repository?
examples/hello_map.rs (line 28)
14async fn main() -> anyhow::Result<()> {
15    let mut map = Map::new();
16    map.add_source("omt", MapSource::vector(Source::open(mapterm::source::OPENFREEMAP).await?))?;
17    map.add_source("pin", MapSource::geojson(&json!({"type": "Feature", "id": 1, "properties": {"name": "Washington Monument"},
18        "geometry": {"type": "Point", "coordinates": [-77.0353, 38.8895]}}))?)?;
19    map.add_layer(StyleLayer::background("bg").color("#101418"))?;
20    map.add_layer(StyleLayer::fill("park", "omt").source_layer("park").color("#1a3220"))?;
21    map.add_layer(StyleLayer::fill("water", "omt").source_layer("water").color("#16304a"))?;
22    map.add_layer(StyleLayer::line("roads", "omt").source_layer("transportation").color(json!(
23        ["match", ["get", "class"], "motorway", "#eb6e3c", "trunk", "#e1a046", "primary", "#d2c36e", "#5a5a5a"])))?;
24    map.add_layer(StyleLayer::symbol("places", "omt").source_layer("place").text(json!(["get", "name"]))
25        .sort_key(json!(["get", "rank"])).color("#e1e1e1"))?;
26    map.add_layer(StyleLayer::symbol("pin", "pin").glyph("◆").text("{name}")
27        .color(json!(["case", ["boolean", ["feature-state", "hover"], false], "yellow", "cyan"])))?;
28    let mut events = Events::new(&["pin", "places"]).hover_state("hover");
29
30    let mut ctl = Controller::new(Camera::new(-77.0353, 38.8895, 13.0), 0.0, 17.0);
31    let mut status = String::new();
32    let mut term = ratatui::init();
33    crossterm::execute!(std::io::stdout(), event::EnableMouseCapture)?;
34    loop {
35        ctl.tick(Instant::now());
36        let area = term.get_frame().area();
37        ctl.set_area(area);
38        let _ = map.load_tiles(&ctl.cam, area).await; // a real app loads in the background
39        term.draw(|f| {
40            f.render_widget(map.view(&ctl.cam), area);
41            f.render_widget(ratatui::text::Line::from(status.as_str()), area);
42        })?;
43        events.pointer(&mut map, &ctl.cam, area, ctl.pointer()); // hover: the pin turns yellow
44        if let Some(click) = ctl.take_click() {
45            for e in events.click(&map, &ctl.cam, area, &click) {
46                if let MapEvent::Click { layer, features, .. } = e {
47                    status = format!("{layer}: {}", features[0].title());
48                }
49            }
50        }
51        if event::poll(Duration::from_millis(if ctl.animating() { 16 } else { 250 }))? {
52            match event::read()? {
53                Event::Key(k) if k.code == KeyCode::Char('q') => break,
54                Event::Key(k) => _ = ctl.key(k),
55                Event::Mouse(m) => _ = ctl.mouse(m),
56                _ => {}
57            }
58        }
59    }
60    crossterm::execute!(std::io::stdout(), event::DisableMouseCapture)?;
61    ratatui::restore();
62    Ok(())
63}
Source

pub fn hover_state(self, key: &str) -> Self

Set feature state key to true on the feature under the pointer (and remove it when the pointer leaves), for ["feature-state", key] hover styling.

Examples found in repository?
examples/hello_map.rs (line 28)
14async fn main() -> anyhow::Result<()> {
15    let mut map = Map::new();
16    map.add_source("omt", MapSource::vector(Source::open(mapterm::source::OPENFREEMAP).await?))?;
17    map.add_source("pin", MapSource::geojson(&json!({"type": "Feature", "id": 1, "properties": {"name": "Washington Monument"},
18        "geometry": {"type": "Point", "coordinates": [-77.0353, 38.8895]}}))?)?;
19    map.add_layer(StyleLayer::background("bg").color("#101418"))?;
20    map.add_layer(StyleLayer::fill("park", "omt").source_layer("park").color("#1a3220"))?;
21    map.add_layer(StyleLayer::fill("water", "omt").source_layer("water").color("#16304a"))?;
22    map.add_layer(StyleLayer::line("roads", "omt").source_layer("transportation").color(json!(
23        ["match", ["get", "class"], "motorway", "#eb6e3c", "trunk", "#e1a046", "primary", "#d2c36e", "#5a5a5a"])))?;
24    map.add_layer(StyleLayer::symbol("places", "omt").source_layer("place").text(json!(["get", "name"]))
25        .sort_key(json!(["get", "rank"])).color("#e1e1e1"))?;
26    map.add_layer(StyleLayer::symbol("pin", "pin").glyph("◆").text("{name}")
27        .color(json!(["case", ["boolean", ["feature-state", "hover"], false], "yellow", "cyan"])))?;
28    let mut events = Events::new(&["pin", "places"]).hover_state("hover");
29
30    let mut ctl = Controller::new(Camera::new(-77.0353, 38.8895, 13.0), 0.0, 17.0);
31    let mut status = String::new();
32    let mut term = ratatui::init();
33    crossterm::execute!(std::io::stdout(), event::EnableMouseCapture)?;
34    loop {
35        ctl.tick(Instant::now());
36        let area = term.get_frame().area();
37        ctl.set_area(area);
38        let _ = map.load_tiles(&ctl.cam, area).await; // a real app loads in the background
39        term.draw(|f| {
40            f.render_widget(map.view(&ctl.cam), area);
41            f.render_widget(ratatui::text::Line::from(status.as_str()), area);
42        })?;
43        events.pointer(&mut map, &ctl.cam, area, ctl.pointer()); // hover: the pin turns yellow
44        if let Some(click) = ctl.take_click() {
45            for e in events.click(&map, &ctl.cam, area, &click) {
46                if let MapEvent::Click { layer, features, .. } = e {
47                    status = format!("{layer}: {}", features[0].title());
48                }
49            }
50        }
51        if event::poll(Duration::from_millis(if ctl.animating() { 16 } else { 250 }))? {
52            match event::read()? {
53                Event::Key(k) if k.code == KeyCode::Char('q') => break,
54                Event::Key(k) => _ = ctl.key(k),
55                Event::Mouse(m) => _ = ctl.mouse(m),
56                _ => {}
57            }
58        }
59    }
60    crossterm::execute!(std::io::stdout(), event::DisableMouseCapture)?;
61    ratatui::restore();
62    Ok(())
63}
Source

pub fn hovered(&self) -> impl Iterator<Item = (&str, &Pick)>

The features under the pointer now, by layer.

Source

pub fn pointer( &mut self, map: &mut Map, cam: &Camera, area: Rect, at: Option<(f64, f64)>, ) -> Vec<MapEvent>

Where the pointer is (dots relative to area, e.g. crate::Controller::pointer), or None when it’s off the map. Returns Leave and Enter events as the feature under it changes on each layer; call it every frame (repeats with nothing new are skipped).

Examples found in repository?
examples/hello_map.rs (line 43)
14async fn main() -> anyhow::Result<()> {
15    let mut map = Map::new();
16    map.add_source("omt", MapSource::vector(Source::open(mapterm::source::OPENFREEMAP).await?))?;
17    map.add_source("pin", MapSource::geojson(&json!({"type": "Feature", "id": 1, "properties": {"name": "Washington Monument"},
18        "geometry": {"type": "Point", "coordinates": [-77.0353, 38.8895]}}))?)?;
19    map.add_layer(StyleLayer::background("bg").color("#101418"))?;
20    map.add_layer(StyleLayer::fill("park", "omt").source_layer("park").color("#1a3220"))?;
21    map.add_layer(StyleLayer::fill("water", "omt").source_layer("water").color("#16304a"))?;
22    map.add_layer(StyleLayer::line("roads", "omt").source_layer("transportation").color(json!(
23        ["match", ["get", "class"], "motorway", "#eb6e3c", "trunk", "#e1a046", "primary", "#d2c36e", "#5a5a5a"])))?;
24    map.add_layer(StyleLayer::symbol("places", "omt").source_layer("place").text(json!(["get", "name"]))
25        .sort_key(json!(["get", "rank"])).color("#e1e1e1"))?;
26    map.add_layer(StyleLayer::symbol("pin", "pin").glyph("◆").text("{name}")
27        .color(json!(["case", ["boolean", ["feature-state", "hover"], false], "yellow", "cyan"])))?;
28    let mut events = Events::new(&["pin", "places"]).hover_state("hover");
29
30    let mut ctl = Controller::new(Camera::new(-77.0353, 38.8895, 13.0), 0.0, 17.0);
31    let mut status = String::new();
32    let mut term = ratatui::init();
33    crossterm::execute!(std::io::stdout(), event::EnableMouseCapture)?;
34    loop {
35        ctl.tick(Instant::now());
36        let area = term.get_frame().area();
37        ctl.set_area(area);
38        let _ = map.load_tiles(&ctl.cam, area).await; // a real app loads in the background
39        term.draw(|f| {
40            f.render_widget(map.view(&ctl.cam), area);
41            f.render_widget(ratatui::text::Line::from(status.as_str()), area);
42        })?;
43        events.pointer(&mut map, &ctl.cam, area, ctl.pointer()); // hover: the pin turns yellow
44        if let Some(click) = ctl.take_click() {
45            for e in events.click(&map, &ctl.cam, area, &click) {
46                if let MapEvent::Click { layer, features, .. } = e {
47                    status = format!("{layer}: {}", features[0].title());
48                }
49            }
50        }
51        if event::poll(Duration::from_millis(if ctl.animating() { 16 } else { 250 }))? {
52            match event::read()? {
53                Event::Key(k) if k.code == KeyCode::Char('q') => break,
54                Event::Key(k) => _ = ctl.key(k),
55                Event::Mouse(m) => _ = ctl.mouse(m),
56                _ => {}
57            }
58        }
59    }
60    crossterm::execute!(std::io::stdout(), event::DisableMouseCapture)?;
61    ratatui::restore();
62    Ok(())
63}
Source

pub fn click( &self, map: &Map, cam: &Camera, area: Rect, click: &Click, ) -> Vec<MapEvent>

A click (from crate::Controller::take_click): one Click per layer with features under it.

Examples found in repository?
examples/hello_map.rs (line 45)
14async fn main() -> anyhow::Result<()> {
15    let mut map = Map::new();
16    map.add_source("omt", MapSource::vector(Source::open(mapterm::source::OPENFREEMAP).await?))?;
17    map.add_source("pin", MapSource::geojson(&json!({"type": "Feature", "id": 1, "properties": {"name": "Washington Monument"},
18        "geometry": {"type": "Point", "coordinates": [-77.0353, 38.8895]}}))?)?;
19    map.add_layer(StyleLayer::background("bg").color("#101418"))?;
20    map.add_layer(StyleLayer::fill("park", "omt").source_layer("park").color("#1a3220"))?;
21    map.add_layer(StyleLayer::fill("water", "omt").source_layer("water").color("#16304a"))?;
22    map.add_layer(StyleLayer::line("roads", "omt").source_layer("transportation").color(json!(
23        ["match", ["get", "class"], "motorway", "#eb6e3c", "trunk", "#e1a046", "primary", "#d2c36e", "#5a5a5a"])))?;
24    map.add_layer(StyleLayer::symbol("places", "omt").source_layer("place").text(json!(["get", "name"]))
25        .sort_key(json!(["get", "rank"])).color("#e1e1e1"))?;
26    map.add_layer(StyleLayer::symbol("pin", "pin").glyph("◆").text("{name}")
27        .color(json!(["case", ["boolean", ["feature-state", "hover"], false], "yellow", "cyan"])))?;
28    let mut events = Events::new(&["pin", "places"]).hover_state("hover");
29
30    let mut ctl = Controller::new(Camera::new(-77.0353, 38.8895, 13.0), 0.0, 17.0);
31    let mut status = String::new();
32    let mut term = ratatui::init();
33    crossterm::execute!(std::io::stdout(), event::EnableMouseCapture)?;
34    loop {
35        ctl.tick(Instant::now());
36        let area = term.get_frame().area();
37        ctl.set_area(area);
38        let _ = map.load_tiles(&ctl.cam, area).await; // a real app loads in the background
39        term.draw(|f| {
40            f.render_widget(map.view(&ctl.cam), area);
41            f.render_widget(ratatui::text::Line::from(status.as_str()), area);
42        })?;
43        events.pointer(&mut map, &ctl.cam, area, ctl.pointer()); // hover: the pin turns yellow
44        if let Some(click) = ctl.take_click() {
45            for e in events.click(&map, &ctl.cam, area, &click) {
46                if let MapEvent::Click { layer, features, .. } = e {
47                    status = format!("{layer}: {}", features[0].title());
48                }
49            }
50        }
51        if event::poll(Duration::from_millis(if ctl.animating() { 16 } else { 250 }))? {
52            match event::read()? {
53                Event::Key(k) if k.code == KeyCode::Char('q') => break,
54                Event::Key(k) => _ = ctl.key(k),
55                Event::Mouse(m) => _ = ctl.mouse(m),
56                _ => {}
57            }
58        }
59    }
60    crossterm::execute!(std::io::stdout(), event::DisableMouseCapture)?;
61    ratatui::restore();
62    Ok(())
63}

Trait Implementations§

Source§

impl Default for Events

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

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<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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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, !>

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