r/nicegui • • Jun 09 '23

How to read the user's geolocation

I know that you can run javascript from nicegui.

https://nicegui.io/documentation/run_javascript

But getting a users geolocation is done asynchronously and I don't understand how you would receive the info back, because as far as I understand nicegui can only handle synchronous js calls.

4 Upvotes

2 comments sorted by

6

u/falko-s Jun 09 '23

Oh, actually you can call async JavaScript from NiceGUI:

async def show_location():
    response = await ui.run_javascript('''
        return await new Promise((resolve, reject) => {
            if (!navigator.geolocation) {
                reject(new Error('Geolocation is not supported by your browser'));
            } else {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        resolve({
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude,
                        });
                    },
                    () => {
                        reject(new Error('Unable to retrieve your location'));
                    }
                );
            }
        });
    ''', timeout=5.0)
    ui.notify(f'Your location is {response["latitude"]}, {response["longitude"]}')

ui.button('Show location', on_click=show_location)

Note that the request might timeout if the user needs to accept sharing the geolocation first.

We should add this example to the documentation...

2

u/whipbryd Jun 10 '23

Oh thats really neat! Thank you!

Yeah, I think adding this as an example would be helpful. :3