3

How do I define a js_sys::Function that must be used in get_current_position to get the users latitude and longitude coordinates?

I have the following

let navigator = web_sys::window().expect("Missing window").navigator();
let geolocation = navigator.geolocation().unwrap();

geolocation.get_current_position(|pos: JsValue| {
    // logic omitted for brevity
})

which gives the following compile error by wasm-pack build --target web:

    |       geolocation.get_current_position(|pos: JsValue| {
    |  ______________________________________^
    | |
    | |     });
    | |_____^ expected `&Function`, found closure

As I understand, the argument needs to be a js_sys::Function instead of an ordinary rust closure. The documentation is a bit vague, but I think I need to use new_with_args ?

Kevin
  • 3,096
  • 2
  • 8
  • 37
  • 2
    [Passing Rust Closures to Imported JavaScript Functions](https://rustwasm.github.io/wasm-bindgen/reference/passing-rust-closures-to-js.html) – Chayim Friedman Nov 24 '21 at 06:12
  • @ChayimFriedman Thanks for the link. However, I am still confused how I can practically apply it. Say I wanted to create a *Stack-lifetime closure*, how do I pass it as an argument to ```geolocation.get_current_position``` ? – Kevin Nov 26 '21 at 11:52
  • See also [this question](https://stackoverflow.com/questions/60054963/how-to-convert-closure-to-js-sysfunction). – Matthias Braun Feb 10 '23 at 14:05

0 Answers0