[Python] How can I update a Plotly Map in NiceGUI with new coordinates?

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I assume this is a simple fix that I cannot seem to wrap my head around. I've defined the default values in four NiceGUI ui.inputs and bound them to a dict. I know these values update on_change, but the Plotly plot doesn't. I can't seem to understand what function to create that takes these updated values from the input to the dict to the new plot. Ultimately I want the user to be able to draw and redraw a bounding box on the map by changing the float values in the input.

    As is, code simply brings up a map and bounding box that can't be changed. Uncomment the fig.data = [] line and it will start as an empty graph. What is up with that behavior? Why would that function run before the button is clicked?

    from nicegui import ui
    import plotly.graph_objects as go

    bbox_dict = {
    'lat_n': '',
    'lat_s': '',
    'lon_w': '',
    'lon_e': '',
    }

    ui.input(label='North Latitude', value=45, placeholder='eg 45.0').bind_value_to(bbox_dict, 'lat_n')
    ui.input(label='South Latitude', value=40, placeholder='eg 40.0').bind_value_to(bbox_dict, 'lat_s')
    ui.input(label='West Longitude', value=-90, placeholder='eg -90.0').bind_value_to(bbox_dict, 'lon_w')
    ui.input(label='East Longitude', value=-88, placeholder='eg -88.0').bind_value_to(bbox_dict, 'lon_e')

    lon = [bbox_dict['lon_w'], bbox_dict['lon_e'], bbox_dict['lon_e'], bbox_dict['lon_w']]
    lat = [bbox_dict['lat_n'], bbox_dict['lat_n'],bbox_dict['lat_s'], bbox_dict['lat_s']]

    lon_mid = (bbox_dict['lon_w']+bbox_dict['lon_e'])/2
    lat_mid = (bbox_dict['lat_n']+bbox_dict['lat_s'])/2

    fig = go.Figure(go.Scattermap(
    fill = "toself",
    lon = lon, lat = lat,
    marker = { 'size': 10, 'color': "orange" },
    name='BBox'))
    fig.update_layout(margin=dict(l=0,r=0,t=0,b=0), width=400, showlegend=False,
    map = {
    'style': 'carto-darkmatter',
    'center': {'lon': lon_mid, 'lat': lat_mid },
    'zoom':5})
    plot = ui.plotly(fig)

    def update_plt():
    # fig.data = []
    plot.update()

    ui.button('Update', on_click=update_plt())

    ui.run()

    Continue reading...

Compartilhe esta Página