How to avoid page reload on interaction

Hi there,

I’m displaying a map conditioned to the value of a selectbox.
Here is a simple example of what I’m doing:

selection = st.selectbox('Select something', option_list)

m = folium.Map(location=[0, 0], zoom_start=16, max_zoom = 19)

for idx, node in nodes_df.iterrows():
    folium.Marker([selection['lat'], selection['lon']]).add_to(m)

st_data = st_folium(m, width=640, height=320)

st.write(st_data)

Suppose that selection contains the info required to generate a marker.

The map is displayed correctly.
The problem is that once I click on the marker, the whole page reloads and nothing is shown related to the st.write(st_data) command

This is another (simpler) example that shows my problem:

import streamlit as st
import folium
from streamlit_folium import st_folium

form = st.form("location_form")
set_latitude = form.number_input("Latitude")
set_longitude = form.number_input("Longitude")
submit_button = form.form_submit_button("Submit")

if submit_button:
    location = [ set_latitude , set_longitude ]

    st.write(location)

    m = folium.Map(location=location, zoom_start=16)
    fg = folium.FeatureGroup(name="Markers")
    
    fg.add_child(folium.Marker(location=location))

    st_data = st_folium(m, feature_group_to_add=fg, width=640, height=320)

    st.write(st_data)

If I run this app, once the button is pressed, the map is displayed for a brief amount of time and then disappears. If I remove the button, everything works fine.

You can use st.session_state to store the markers over app reloads.

From here, you can append each marker to the st.session_state["markers"] from inside of the button click condition, and then create the FeatureGroup by looping over st.session_state["markers"]

Here is a working example of your code:

import folium
import streamlit as st
from streamlit_folium import st_folium

form = st.form("location_form")
set_latitude = form.number_input("Latitude")
set_longitude = form.number_input("Longitude")
submit_button = form.form_submit_button("Submit")

# Initialize markers inside of session state
if "markers" not in st.session_state:
    st.session_state["markers"] = []

location = [set_latitude, set_longitude]
m = folium.Map(location=location, zoom_start=16)

if submit_button:
    st.session_state["markers"].append(folium.Marker(location=location))
    st.write(location)

fg = folium.FeatureGroup(name="Markers")
for marker in st.session_state["markers"]:
    fg.add_child(marker)
st_data = st_folium(m, feature_group_to_add=fg, width=640, height=320)
st.write(st_data)
1 Like

Now you can use returned_objects to disable reruns:

st_folium(..., returned_objects=[])

Check out the docs: https://folium.streamlit.app/static_map

1 Like