### Basic Streamlit Folium Map Example Source: https://github.com/randyzwitch/streamlit-folium/blob/master/tests/visual_baseline/test_basic/first_test/tags_level_3.txt This Python code snippet demonstrates how to create a basic Folium map centered on a specific location and add a marker to it. The map is then rendered within a Streamlit application using the `st_folium` function. Dependencies include `streamlit`, `streamlit-folium`, and `folium`. ```python import streamlit as st from streamlit_folium import st_folium import folium # center on Liberty Bell, add marker m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell" ).add_to(m) # call to render Folium map in Streamlit st_data = st_folium(m, width = 725) ``` -------------------------------- ### Add a Marker to a Folium Map in Python Source: https://github.com/randyzwitch/streamlit-folium/blob/master/tests/visual_baseline/test_basic/first_test/tags_level_1.txt This example demonstrates adding a marker to a Folium map at a specified latitude and longitude. It builds upon the basic map creation and requires the 'folium' library. The output is an HTML map with an added marker. ```python import folium # Create a map object m = folium.Map(location=[40.7128, -74.0060], zoom_start=12) # Add a marker to the map folium.Marker([40.7128, -74.0060], popup='New York City').add_to(m) # Save the map m.save("map_with_marker.html") ``` -------------------------------- ### Overlay Images on Folium Map with Pixelation in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt This example shows how to overlay images onto a Folium map within a Streamlit application. It demonstrates the use of the `ImageOverlay` class and provides options for both smooth rendering and pixelated rendering, allowing for crisp pixel display of the overlay. ```python import folium import streamlit as st from streamlit_folium import st_folium url_image = "https://example.com/overlay.png" image_bounds = [[-20.664910, -46.538223], [-20.660001, -46.532977]] m = folium.Map() # Add image overlay folium.raster_layers.ImageOverlay( image=url_image, name="Image Overlay", opacity=1, bounds=image_bounds, ).add_to(m) m.fit_bounds(image_bounds, padding=(0, 0)) col1, col2 = st.columns(2) with col1: st.markdown("## Smooth rendering") st_folium(m, use_container_width=True, pixelated=False, key="smooth") with col2: st.markdown("## Pixelated rendering") st_folium(m, use_container_width=True, pixelated=True, key="pixelated") ``` -------------------------------- ### Fit Folium Map to Bounds in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt This example demonstrates how to automatically zoom and center a Folium map to fit a specified bounding box within a Streamlit application. It includes an option to add padding around the bounds for better visualization. A rectangle is added to the map to visually represent the defined bounds. ```python import folium import streamlit as st from streamlit_folium import st_folium # Define bounds: [[south, west], [north, east]] bounds = [[40.0, -125.0], [50.0, -115.0]] # Create map and fit to bounds m = folium.Map(location=[0, 0], zoom_start=2, tiles="cartodbpositron") m.fit_bounds(bounds) # Add rectangle to visualize bounds folium.Rectangle( bounds=bounds, color="red", weight=2, fill=True, fill_opacity=0.1, ).add_to(m) st_folium(m, use_container_width=True, height=400) # With padding around bounds m2 = folium.Map(tiles="cartodbpositron") m2.fit_bounds(bounds, padding=(50, 50)) st_folium(m2, use_container_width=True, height=400) ``` -------------------------------- ### st_folium: GeoJSON Popups and Tooltips in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Illustrates creating interactive choropleth maps with styled GeoJSON features, including popups (on click) and tooltips (on hover). This example requires folium, geopandas, branca, and streamlit. It configures custom popups and tooltips for GeoJSON data. ```python import folium import geopandas as gpd import branca import streamlit as st from folium import GeoJsonPopup, GeoJsonTooltip from streamlit_folium import st_folium # Load GeoJSON data (example with US states) # df = gpd.read_file("states.geojson") # For this example, assume df has columns: name, population, change # Create colormap colormap = branca.colormap.LinearColormap( vmin=0, vmax=100, colors=["red", "orange", "lightblue", "green", "darkgreen"], caption="Population Change (%)", ) m = folium.Map(location=[35.3, -97.6], zoom_start=4) # Configure popup (shown on click) popup = GeoJsonPopup( fields=["name", "change"], aliases=["State", "% Change"], localize=True, labels=True, style="background-color: yellow;", ) # Configure tooltip (shown on hover) tooltip = GeoJsonTooltip( fields=["name", "population", "change"], aliases=["State:", "Population:", "% Change:"], localize=True, sticky=False, labels=True, style=""" background-color: #F0EFEF; border: 2px solid black; border-radius: 3px; """, max_width=800, ) # Add styled GeoJSON layer # folium.GeoJson( # df, # style_function=lambda x: { # "fillColor": colormap(x["properties"]["change"]) if x["properties"]["change"] else "transparent", # "color": "black", # "fillOpacity": 0.4, # }, # tooltip=tooltip, # popup=popup, # ).add_to(m) colormap.add_to(m) # Enable return on hover for tooltip data output = st_folium(m, width=700, height=500, return_on_hover=True) st.write("Tooltip content:", output["last_object_clicked_tooltip"]) st.write("Popup content:", output["last_object_clicked_popup"]) ``` -------------------------------- ### Create a Basic Folium Map in Python Source: https://github.com/randyzwitch/streamlit-folium/blob/master/tests/visual_baseline/test_basic/first_test/tags_level_1.txt This snippet shows how to create a simple Folium map centered on a specific location. It requires the 'folium' library. The output is an HTML representation of the map. ```python import folium # Create a map object centered on a specific location m = folium.Map(location=[45.5236, -122.6750]) # Save the map to an HTML file m.save("map.html") ``` -------------------------------- ### Create Responsive Folium Maps in Streamlit Columns Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt This code snippet illustrates how to create responsive Folium maps that automatically adjust to the width of their container within a Streamlit application. It showcases using maps in full-width layout and within columns to demonstrate responsive behavior. ```python import folium import streamlit as st from streamlit_folium import st_folium st.set_page_config(layout="wide") m = folium.Map(location=(45, -90), zoom_start=5) # Full-width responsive map st_folium(m, use_container_width=True, height=400, key="fullwidth") # Responsive maps in columns left, right = st.columns([2, 1]) with left: st_folium(m, use_container_width=True, height=300, key="left_map") with right: st_folium(m, use_container_width=True, height=300, key="right_map") ``` -------------------------------- ### st_folium: Layer Control with WMS/Tile Layers in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Shows how to add multiple WMS/tile layers to a Folium map and enable interactive layer control for toggling their visibility. This requires folium, streamlit, and streamlit-folium. The map includes Swiss WMS layers for imagery and solar potential. ```python import folium import streamlit as st from folium import WmsTileLayer from folium.plugins import Draw from streamlit_folium import st_folium # Create base map m = folium.Map(location=[47.377512, 8.540670], zoom_start=15, max_zoom=20) # Add WMS tile layers WmsTileLayer( url="https://wms.geo.admin.ch/", layers="ch.swisstopo.swissimage", name="Swiss Image", fmt="image/png", transparent=True, overlay=True, control=True, show=True, # Initially visible max_zoom=20, ).add_to(m) WmsTileLayer( url="https://wms.geo.admin.ch/", layers="ch.bfe.solarenergie-eignung-daecher", name="Solar Potential", fmt="image/png", transparent=True, overlay=True, control=True, show=False, # Initially hidden max_zoom=20, ).add_to(m) # Add layer control toggle folium.LayerControl(position="topright").add_to(m) # Add draw support Draw(export=True).add_to(m) data = st_folium(m, width=800, height=500) st.write("Selected layers:", data.get("selected_layers")) ``` -------------------------------- ### Streamlit-Folium Map with On-Change Callback Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Integrates a callback function that executes whenever the map's state changes in Streamlit. The callback can access the latest map data, such as zoom level and center coordinates, through `st.session_state` using a specified key. This enables dynamic updates or actions based on map interactions. ```python import folium import streamlit as st from streamlit_folium import st_folium m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell" ).add_to(m) def on_map_change(): """Callback triggered when map state changes""" map_state = st.session_state["my_map"] st.toast(f"Current zoom: {map_state['zoom']}") st.toast(f"Current center: {map_state['center']}") # Render map with callback and key for session state access st_data = st_folium( m, width=725, height=500, key="my_map", on_change=on_map_change ) ``` -------------------------------- ### Embed Folium Map in Streamlit using st_folium in Python Source: https://github.com/randyzwitch/streamlit-folium/blob/master/tests/visual_baseline/test_basic/first_test/tags_level_1.txt This snippet illustrates how to display a Folium map directly within a Streamlit application using the `st_folium` function. It requires the 'streamlit' and 'folium' libraries. The input is a Folium map object, and the output is an interactive map displayed in the Streamlit UI. ```python import streamlit as st import folium # Create a Folium map m = folium.Map(location=[37.7749, -122.4194], zoom_start=13) folium.Marker([37.7749, -122.4194], popup='San Francisco').add_to(m) # Display the map in Streamlit from streamlit_folium import st_folium st_folium(m, width=700, height=450) ``` -------------------------------- ### Display Folium Map in Streamlit Source: https://github.com/randyzwitch/streamlit-folium/blob/master/tests/visual_baseline/test_basic/first_test/tags_level_2.txt This snippet demonstrates how to render a Folium map object within a Streamlit application. It requires the `streamlit-folium` library and a Folium map object as input. The output is an interactive map displayed in the Streamlit UI. ```python import streamlit as st import folium # Create a Folium map m = folium.Map(location=[45.5236, -122.6750]) # Display the map in Streamlit streamlit_folium.folium_static(m) ``` -------------------------------- ### st_folium: Dynamic Feature Groups in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Demonstrates how to add or update map features dynamically without re-rendering the entire map using `feature_group_to_add`. This is useful for responding to user interactions efficiently. It requires folium, geopandas, shapely, and streamlit. ```python import folium import folium.features import geopandas as gpd import shapely import streamlit as st from streamlit_folium import st_folium # Create base map m = folium.Map(location=[37.7944, -122.3980], zoom_start=17, tiles="OpenStreetMap") # Define polygon geometry wkt = "POLYGON ((-122.399 37.793, -122.398 37.793, -122.398 37.794, -122.399 37.794, -122.399 37.793))" polygon = shapely.wkt.loads(wkt) gdf = gpd.GeoDataFrame(geometry=[polygon]).set_crs(epsg=4326) # Create styled GeoJSON style = {"fillColor": "#1100f8", "color": "#1100f8", "fillOpacity": 0.3, "weight": 2} polygon_folium = folium.GeoJson(data=gdf, style_function=lambda x: style) # Create feature group and add polygon fg = folium.FeatureGroup(name="Parcels") fg.add_child(polygon_folium) # Render with dynamic feature group st_folium( m, width=800, height=450, feature_group_to_add=fg, # Can also pass list: [fg1, fg2] ) # Dynamic center and zoom updates (won't reload the map) if st.button("Pan to New Location"): st_folium( m, center=[37.80, -122.40], # Dynamic center update zoom=15, # Dynamic zoom update feature_group_to_add=fg, ) ``` -------------------------------- ### Display Real-time Data with Folium Realtime Plugin in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt This snippet shows how to display real-time data on a Folium map within a Streamlit application using the Realtime plugin. It fetches data from an external API (ISS position) and updates the map periodically. Custom JavaScript is used for data fetching and handling feature interactions, including binding tooltips and setting Streamlit component values on click. ```python import folium import streamlit as st from folium.plugins import Realtime from streamlit_folium import st_folium m = folium.Map() # Define data source (fetches ISS position) source = folium.JsCode(""" function(responseHandler, errorHandler) { var url = 'https://api.wheretheiss.at/v1/satellites/25544'; fetch(url) .then((response) => { return response.json().then((data) => { var { id, timestamp, longitude, latitude } = data; return { 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [longitude, latitude] }, 'properties': { 'id': id, 'timestamp': timestamp } }] }; }) }) .then(responseHandler) .catch(errorHandler); } ") # Handle feature interactions with custom JS on_each_feature = folium.JsCode(""" (feature, layer) => { layer.bindTooltip(`${feature.properties.timestamp}`); layer.on("click", (event) => { Streamlit.setComponentValue({ id: feature.properties.id, location: event.sourceTarget.feature.geometry }); }); } ") # Add realtime layer (updates every 10 seconds) Realtime( source, on_each_feature=on_each_feature, interval=10000, ).add_to(m) data = st_folium(m, returned_objects=[], debug=False) st.write("Clicked feature:", data) ``` -------------------------------- ### Streamlit-Folium Map with Draw Plugin Support Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Enables users to draw shapes (e.g., polygons, circles) directly on the Folium map embedded in Streamlit using the Draw plugin. The drawn shapes are returned as GeoJSON features in the `all_drawings` and `last_active_drawing` fields of the output dictionary. This facilitates data collection and analysis based on user-drawn areas. ```python import folium import streamlit as st from folium.plugins import Draw from streamlit_folium import st_folium # Create map with Draw plugin m = folium.Map(location=[39.949610, -75.150282], zoom_start=5) Draw(export=True).add_to(m) col1, col2 = st.columns(2) with col1: output = st_folium(m, width=700, height=500) with col2: st.write("All drawings:", output["all_drawings"]) st.write("Last active drawing:", output["last_active_drawing"]) st.write("Last circle radius:", output["last_circle_radius"]) # Drawing data structure example: # { ``` -------------------------------- ### Render Interactive Folium Map in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Renders a Folium map object within a Streamlit application, enabling bi-directional interaction. It captures user events like clicks, zoom changes, and bounding box updates, returning this data in a dictionary. The Streamlit app automatically reruns when map interactions occur. ```python import folium import streamlit as st from streamlit_folium import st_folium # Create a map centered on a location m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) # Add a marker with popup and tooltip folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Click for info" ).add_to(m) # Render map and capture interaction data map_data = st_folium(m, width=725, height=500) # Access returned data st.write("Last clicked:", map_data["last_clicked"]) st.write("Current bounds:", map_data["bounds"]) st.write("Zoom level:", map_data["zoom"]) st.write("Clicked object tooltip:", map_data["last_object_clicked_tooltip"]) st.write("Clicked object popup:", map_data["last_object_clicked_popup"]) # Returned dictionary structure: # { # "last_clicked": {"lat": 39.949610, "lng": -75.150282}, # "last_object_clicked": {"lat": 39.949610, "lng": -75.150282}, # "last_object_clicked_tooltip": "Click for info", # "last_object_clicked_popup": "Liberty Bell", # "all_drawings": None, # "last_active_drawing": None, # "bounds": {"_southWest": {"lat": 39.94, "lng": -75.16}, "_northEast": {"lat": 39.96, "lng": -75.14}}, # "zoom": 16, # "center": {"lat": 39.949610, "lng": -75.150282} # } ``` -------------------------------- ### Render Non-Interactive Folium Map in Streamlit Source: https://context7.com/randyzwitch/streamlit-folium/llms.txt Renders a Folium map in Streamlit without returning interaction data, preventing Streamlit app reruns on user map interactions. This is suitable for static visualizations and offers improved performance. It also supports selectively returning specific data fields like zoom and bounds. ```python import folium import streamlit as st from streamlit_folium import st_folium # Create map with markers m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell" ).add_to(m) # Render as non-interactive display (no data returned, no reruns) st_folium(m, width=725, height=500, returned_objects=[]) # You can also selectively return only specific data fields: data = st_folium(m, width=725, height=500, returned_objects=["zoom", "bounds"]) # Only zoom and bounds will trigger reruns and be returned ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.