leptos_leaflet/components/
tile_layer.rs

1use leptos::logging::warn;
2use leptos::prelude::*;
3
4use crate::core::JsStoredValue;
5
6use super::LeafletMapContext;
7
8/// A tile layer component.
9#[component(transparent)]
10pub fn TileLayer(
11    #[prop(into)] url: String,
12    #[prop(into, optional)] attribution: String,
13    #[prop(optional)] bring_to_front: bool,
14    #[prop(optional)] bring_to_back: bool,
15    #[prop(default = 0.0)] min_zoom: f64,
16    #[prop(default = 18.0)] max_zoom: f64,
17) -> impl IntoView {
18    let map_context = use_context::<LeafletMapContext>().expect("map context not found");
19
20    Effect::new(move |_| {
21        if let Some(map) = map_context.map() {
22            let options = leaflet::TileLayerOptions::default();
23            if !attribution.is_empty() {
24                options.set_attribution(attribution.to_string());
25            }
26            options.set_min_zoom(min_zoom);
27            options.set_max_zoom(max_zoom);
28            let map_layer = leaflet::TileLayer::new_options(&url, &options);
29            map_layer.add_to(&map);
30
31            match (bring_to_front, bring_to_back) {
32                (true, true) => warn!("The parameters are set to bring the layer to front and back at the same time. Ignoring these parameters..."),
33                (true, false) => {map_layer.bring_to_front();}
34                (false, true) => {map_layer.bring_to_back();}
35                (false, false) => (),
36            }
37
38            let map_layer = JsStoredValue::new_local(map_layer);
39
40            on_cleanup(move || {
41                map_layer.with_value(|v| v.remove());
42            });
43        }
44    });
45}