Adding a large .shp file to a folium map

I am trying to add a large .shp file to a folium map, and there is a significant lag each time I zoom or re-center the map. The shapefile is large, with about 10000 rows with polygon geometries. I’ve tried putting it inside a form, and that is helpful, but I still get a long wait time after pushing the submit button.

My question, is there a more efficient way to load a layer than what I have below? I’ve seen other Streamlit apps with very complex base maps that render almost instantly, and I’m hoping to get the same result. Ultimately, I’d like to add some dynamic drawing features to this, but I can’t get to that step until the base map is running well.

import streamlit as st
import geopandas as gpd
import folium
from streamlit_folium import st_folium

st.set_page_config(layout="wide")  

@st.cache_data
def load_shp():
    shp_df = gpd.read_file('testlayer.shp')
    return shp_df.to_json()

layer_to_add = load_shp()
with st.form(key='mymap'):
    m = folium.Map(location = [31.5943, -102.8927], zoom_start = 12)
    folium.GeoJson(layer_to_add, name="my layer",style_function=lambda feature:      {"fillColor": "yellow", "color": "black", "weight": 0.5, "fillOpacity": 0.4}).add_to(m)

    st_folium(m, height = 1000, use_container_width = True, key = 'map')

    submit_button = st.form_submit_button("Submit")

It depends somewhat on what the slow part is – one thing you might try is to also cache creating the initial map, putting both of these lines in an st.cache_data or st.cache_resource function

@st.cache_data
def get_map():
    m = folium.Map(location = [31.5943, -102.8927], zoom_start = 12)
    folium.GeoJson(layer_to_add, name="my layer",style_function=lambda feature:      {"fillColor": "yellow", "color": "black", "weight": 0.5, "fillOpacity": 0.4}).add_to(m)
return m

It’s hard to be sure, but it’s possible, for example, that actually creating the geojson object, and/or styling it, take a long time, and you only want to do that once.

Thanks, I tried that out and still had similar issues.

After a bit more digging, I think I found the appropriate solution. I used maptiler.com to create a custom basemap. I’ve integrated it into my streamlit app and it seems to be working perfectly.

1 Like

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