基于Folium实现点击区域弹窗按钮显示对应数据标记
Got it, let's walk through how to add those button-enabled popups to your Folium map so users can toggle data points per UK region. You already have the GeoJSON hover and highlighting set up, so we'll build on that:
Step 1: Prep Your Data & Dependencies
First, make sure your DataFrame (df) has a region column that exactly matches the region names in your UK GeoJSON file (double-check for typos like "Northwest" vs "North West"—this is crucial for the filtering to work).
Here's the setup code you'll need:
import folium import pandas as pd from folium import GeoJson from folium.plugins import MarkerCluster
Step 2: Build the Base Map & Hidden Data Markers
We'll first add all your DataFrame markers to the map, but hide them initially. Using MarkerCluster is a good call if you have lots of points, as it keeps the map performant:
# Initialize base map centered on the UK m = folium.Map(location=[54.0, -2.0], zoom_start=6) # Create a marker cluster (hidden by default) marker_cluster = MarkerCluster(overlay=True, control=False, options={"opacity": 0}) marker_cluster.add_to(m) # Add all data points from df to the cluster, with a custom `data-region` attribute for idx, row in df.iterrows(): folium.Marker( location=[row["latitude"], row["longitude"]], popup=f"<strong>{row['name']}</strong><br>Lat: {row['latitude']}<br>Lon: {row['longitude']}", icon=folium.Icon(color="blue"), # Add region attribute to link marker to its UK region options={"data-region": row["region"]} ).add_to(marker_cluster)
Step 3: Add GeoJSON with Button-Enabled Popups
Next, we'll update your existing GeoJSON layer to include popups with buttons. The buttons will trigger JavaScript functions to show/hide markers for the selected region:
# Define style and highlight functions (keep your existing ones if you prefer) def style_function(feature): return { "fillColor": "#ffffff", "color": "#000000", "weight": 2, "fillOpacity": 0.1 } def highlight_function(feature): return { "fillOpacity": 0.5, "fillColor": "#ffff00" } # Create popup content with buttons for each region def popup_content(feature): region_name = feature["properties"]["name"] # Replace with your GeoJSON's region field name return f""" <div style="padding: 10px;"> <h4>{region_name}</h4> <button onclick="showRegionMarkers('{region_name}')" style="margin-right: 10px;">Show Data Points</button> <button onclick="hideAllMarkers()">Hide All Points</button> </div> """ # Add GeoJSON layer to the map GeoJson( "uk-regions.geojson", # Replace with your GeoJSON file path style_function=style_function, highlight_function=highlight_function, tooltip=folium.GeoJsonTooltip(fields=["name"], aliases=["Region:"]), # Keep your hover tooltip popup=folium.GeoJsonPopup(popup_content=popup_content) ).add_to(m)
Step 4: Add Custom JavaScript for Toggle Logic
Finally, we'll add JavaScript to handle the button clicks. This code will find all markers, filter them by region, and toggle their visibility:
# Custom JS to control marker visibility custom_js = """ function showRegionMarkers(regionName) { // Get all marker elements on the map const markers = document.querySelectorAll('.leaflet-marker-icon'); markers.forEach(marker => { // Match marker's region to the clicked region const markerRegion = marker.getAttribute('data-region'); if (markerRegion === regionName) { marker.style.opacity = 1; } else { marker.style.opacity = 0; } }); // Refresh marker cluster to update visible points document.querySelectorAll('.leaflet-markercluster').forEach(cluster => { cluster.__markerCluster.refresh(); }); } function hideAllMarkers() { const markers = document.querySelectorAll('.leaflet-marker-icon'); markers.forEach(marker => { marker.style.opacity = 0; }); // Refresh marker cluster document.querySelectorAll('.leaflet-markercluster').forEach(cluster => { cluster.__markerCluster.refresh(); }); } """ # Add the JS to the map's root folium.Element(custom_js).add_to(m.get_root()) # Save your map m.save("uk_region_map.html")
Key Notes to Keep in Mind
- Match Region Names: Double-check that the region names in your
df['region']column are identical to the names in your GeoJSON's properties (case-sensitive!). - MarkerCluster Refresh: The JS includes code to refresh the marker cluster, so when you show/hide points, the cluster will update to reflect visible markers.
- Customization: You can tweak the button styles (add CSS to the popup HTML) or marker colors to match your map's design.
- Performance: If you have thousands of data points,
MarkerClusteris essential to keep the map responsive.
内容的提问来源于stack exchange,提问作者simon90

