[Python] Getting clicked folium map coordinates as a reactive variable in shiny for python

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I have a shiny for python app that I would like to make interactive to allow user to see various statistics depending on where they click on the map. I am using folium to display the map. I can't find a way to return the coordinates of the clicked spot back to shiny for further processing. I found this process relatively easy to implement using ipyleaflet but its dependency on ipywidgets conflicts with plotly which my app heavily depends on to display interactive charts relevant to the place clicked on.

    Here is a toy example that I would like to use for practice:

    from shiny import App, render, ui, reactive
    import folium

    def server(input, output, session):
    # Initialize reactive value for coordinates
    coords = reactive.Value({'lat': None, 'lng': None})

    @output
    @render.ui
    def map():
    m = folium.Map(location=[-1.9403, 29.8739], zoom_start=8)
    # Define a click event handler here that returns the coordinate to shiny
    return ui.HTML(m._repr_html_())

    @reactive.Effect
    @reactive.event(input.map_click)
    def _():
    # capture the coordinates returned by the click event handler on the map
    coords.set()
    return coords

    app_ui = ui.page_fluid(
    ui.h1("Folium Map that returns Coordinates of clicked spot"),
    ui.div(
    ui.output_ui("map"),
    style="height: 600px; width: 100%;"
    )
    )

    app = App(app_ui, server)

    Continue reading...

Compartilhe esta Página