Ask user for geolocation

I use scattermapbox extensively and I would like to implement a button which the user has to press explicitly in order to ask for geolocation.

My idea to build this was:

  • I implemented a button with a clientside calback which call the navigator.geolocation.getCurrentPosition
  • I would like to store the result into a dcc.Store or html.Div which in turn can trigger another (server side callback) where I can use the location

Now my problem is that that the navigator.geolocation.getCurrentPosition is async and thus I would not know how to get its output into my div or store (also Promises are not supported yet).

I tried something like this:

app.clientside_callback(  
    """
    function (value) {
        if (!value) {
            throw window.dash_clientside.PreventUpdate;
        }


        function updateCoordinate(callback) {
            navigator.geolocation.getCurrentPosition(
              function (position) {
                var returnValue = {
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude
                }
                callback(position.coords);
              }
            )
        }

        let x = updateCoordinate(function (coords) {
          return coords
        });
    }

    """,
    Output('my-location', 'children'),
    [Input('locate-me-button', 'n_clicks')]
)

But this does not work

Have you found a solution @codefour? Iā€™m trying to do the exact same thing and any help would be much appreciated!

If you are not bound to using Plotly scattermapbox, Dash Leaflet has a LocateControl that asks for user location.

1 Like