Avoid Page Reload When Interacting With Folium Map

Read through a number of streamlit-folium posts and the documentation…is there a method to scroll around on the map, but not have to reload the page every time?

For example, lets look at the Dynamic Updates documentation page. Each time a user zooms or scrolls on the map, the entire page reloads.

A colleague suggested that if there was a key parameter that could help avoid having to reload the entire page. I’ve found examples using the key parameter, but have not been able to find any documentation on how it works or how/when to use it.

Suggestions?

1 Like

Hello @Binx,

One effective approach is to leverage st.session_state to preserve the state of the map and other parts of your application between reruns. By doing this, you can avoid unnecessary recalculations or reloads of data that haven’t changed.

import streamlit as st
import folium
from streamlit_folium import folium_static
from folium.plugins import MarkerCluster

def create_map():
    if 'map' not in st.session_state or st.session_state.map is None:
        m = folium.Map(location=[45.372, -121.6972], zoom_start=12, tiles="Stamen Terrain")
        
        marker_cluster = MarkerCluster().add_to(m)
        folium.Marker(location=[45.372, -121.6972], popup="Mt. Hood Meadows").add_to(marker_cluster)
        
        st.session_state.map = m  # Save the map in the session state
    return st.session_state.map

def show_map():
    m = create_map()  # Get or create the map
    folium_static(m)

show_map()

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➤ Want me to build your solution? Lets chat about how I can assist!
➤ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➤ Website: https://sahirmaharaj.com
➤ Email: sahir@sahirmaharaj.com
➤ 100+ FREE Power BI Themes: Download Now

3 Likes

Yup that works. Just wanted to see an example with how that works. Thanks again!

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.