leptos_use/
use_geolocation.rs

1use crate::core::{OptionLocalRwSignal, OptionLocalSignal};
2use default_struct_builder::DefaultBuilder;
3use leptos::prelude::*;
4use leptos::reactive::wrappers::read::Signal;
5
6/// Reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API).
7///
8/// It allows the user to provide their location to web applications if they so desire. For privacy reasons,
9/// the user is asked for permission to report location information.
10///
11/// ## Demo
12///
13/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_geolocation)
14///
15/// ## Usage
16///
17/// ```
18/// # use leptos::prelude::*;
19/// # use leptos_use::{use_geolocation, UseGeolocationReturn};
20/// #
21/// # #[component]
22/// # fn Demo() -> impl IntoView {
23/// let UseGeolocationReturn {
24///     coords,
25///     located_at,
26///     error,
27///     resume,
28///     pause,
29/// } = use_geolocation();
30/// #
31/// # view! { }
32/// # }
33/// ```
34///
35///
36/// ## SendWrapped Return
37///
38/// The returned closures `pause` and `resume` are sendwrapped functions. They can
39/// only be called from the same thread that called `use_geolocation`.
40///
41/// ## Server-Side Rendering
42///
43/// > Make sure you follow the [instructions in Server-Side Rendering](https://leptos-use.rs/server_side_rendering.html).
44///
45/// On the server all signals returns will always contain `None` and the functions do nothing.
46pub fn use_geolocation()
47-> UseGeolocationReturn<impl Fn() + Clone + Send + Sync, impl Fn() + Clone + Send + Sync> {
48    use_geolocation_with_options(UseGeolocationOptions::default())
49}
50
51/// Version of [`use_geolocation`] that takes a `UseGeolocationOptions`. See [`use_geolocation`] for how to use.
52pub fn use_geolocation_with_options(
53    options: UseGeolocationOptions,
54) -> UseGeolocationReturn<impl Fn() + Clone + Send + Sync, impl Fn() + Clone + Send + Sync> {
55    let (located_at, set_located_at) = signal(None::<f64>);
56    let error = OptionLocalRwSignal::<web_sys::PositionError>::new();
57    let coords = OptionLocalRwSignal::<web_sys::Coordinates>::new();
58
59    let resume;
60    let pause;
61
62    #[cfg(feature = "ssr")]
63    {
64        resume = || ();
65        pause = || ();
66
67        let _ = options;
68        let _ = set_located_at;
69        let _ = error;
70        let _ = coords;
71    }
72
73    #[cfg(not(feature = "ssr"))]
74    {
75        use crate::{sendwrap_fn, use_window};
76        use std::sync::{Arc, Mutex};
77        use wasm_bindgen::prelude::*;
78
79        let update_position = move |position: web_sys::Position| {
80            set_located_at.set(Some(position.timestamp()));
81            coords.set(Some(position.coords()));
82            error.set(None);
83        };
84
85        let on_error = move |err: web_sys::PositionError| {
86            error.set(Some(err));
87        };
88
89        let watch_handle = Arc::new(Mutex::new(None::<i32>));
90
91        resume = {
92            let watch_handle = Arc::clone(&watch_handle);
93            let position_options = options.as_position_options();
94
95            sendwrap_fn!(move || {
96                let navigator = use_window().navigator();
97                if let Some(navigator) = navigator
98                    && let Ok(geolocation) = navigator.geolocation()
99                {
100                    let update_position =
101                        Closure::wrap(Box::new(update_position) as Box<dyn Fn(web_sys::Position)>);
102                    let on_error =
103                        Closure::wrap(Box::new(on_error) as Box<dyn Fn(web_sys::PositionError)>);
104
105                    *watch_handle.lock().unwrap() = geolocation
106                        .watch_position_with_error_callback_and_options(
107                            update_position.as_ref().unchecked_ref(),
108                            Some(on_error.as_ref().unchecked_ref()),
109                            &position_options,
110                        )
111                        .ok();
112
113                    update_position.forget();
114                    on_error.forget();
115                }
116            })
117        };
118
119        if options.immediate {
120            resume();
121        }
122
123        pause = {
124            let watch_handle = Arc::clone(&watch_handle);
125
126            sendwrap_fn!(move || {
127                let navigator = use_window().navigator();
128                if let Some(navigator) = navigator
129                    && let Some(handle) = *watch_handle.lock().unwrap()
130                    && let Ok(geolocation) = navigator.geolocation()
131                {
132                    geolocation.clear_watch(handle);
133                }
134            })
135        };
136
137        on_cleanup({
138            let pause = pause.clone();
139
140            move || {
141                pause();
142            }
143        });
144    }
145
146    UseGeolocationReturn {
147        coords: coords.read_only(),
148        located_at: located_at.into(),
149        error: error.read_only(),
150        resume,
151        pause,
152    }
153}
154
155/// Options for [`use_geolocation_with_options`].
156#[derive(DefaultBuilder, Clone)]
157#[allow(dead_code)]
158pub struct UseGeolocationOptions {
159    /// If `true` the geolocation watch is started when this function is called.
160    /// If `false` you have to call `resume` manually to start it. Defaults to `true`.
161    immediate: bool,
162
163    /// A boolean value that indicates the application would like to receive the best
164    /// possible results. If `true` and if the device is able to provide a more accurate
165    /// position, it will do so. Note that this can result in slower response times or
166    /// increased power consumption (with a GPS chip on a mobile device for example).
167    /// On the other hand, if `false`, the device can take the liberty to save
168    /// resources by responding more quickly and/or using less power. Default: `false`.
169    enable_high_accuracy: bool,
170
171    /// A positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return.
172    /// If set to `0`, it means that the device cannot use a cached position and must attempt to retrieve the real current position.
173    /// Default: 30000.
174    maximum_age: u32,
175
176    /// A positive value representing the maximum length of time (in milliseconds)
177    /// the device is allowed to take in order to return a position.
178    /// The default value is 27000.
179    timeout: u32,
180}
181
182impl Default for UseGeolocationOptions {
183    fn default() -> Self {
184        Self {
185            enable_high_accuracy: false,
186            maximum_age: 30000,
187            timeout: 27000,
188            immediate: true,
189        }
190    }
191}
192
193#[cfg(not(feature = "ssr"))]
194impl UseGeolocationOptions {
195    fn as_position_options(&self) -> web_sys::PositionOptions {
196        let UseGeolocationOptions {
197            enable_high_accuracy,
198            maximum_age,
199            timeout,
200            ..
201        } = self;
202
203        let options = web_sys::PositionOptions::new();
204        options.set_enable_high_accuracy(*enable_high_accuracy);
205        options.set_maximum_age(*maximum_age);
206        options.set_timeout(*timeout);
207
208        options
209    }
210}
211
212/// Return type of [`use_geolocation`].
213pub struct UseGeolocationReturn<ResumeFn, PauseFn>
214where
215    ResumeFn: Fn() + Clone + Send + Sync,
216    PauseFn: Fn() + Clone + Send + Sync,
217{
218    /// The coordinates of the current device like latitude and longitude.
219    /// See [`GeolocationCoordinates`](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates)..
220    pub coords: OptionLocalSignal<web_sys::Coordinates>,
221
222    /// The timestamp of the current coordinates.
223    pub located_at: Signal<Option<f64>>,
224
225    /// The last error received from `navigator.geolocation`.
226    pub error: OptionLocalSignal<web_sys::PositionError>,
227
228    /// Resume the geolocation watch.
229    pub resume: ResumeFn,
230
231    /// Pause the geolocation watch.
232    pub pause: PauseFn,
233}