You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中folium.LayerControl互斥地理空间标记显示异常问题

folium单选按钮切换图层异常问题

目标

我希望使用Python3.6和folium 0.9.0版本,通过单选按钮切换folium地图中地理空间标记的颜色和弹窗内容。我尝试创建两个带有不同颜色值的独立DataFrame,并将它们分别添加到各自的folium.FeatureGroup()中。

问题

生成地图后,所有单选按钮选项均仅显示最后一个folium.FeatureGroup()的数值。

可复现示例

步骤1:创建两个DataFrame

创建两个具有相同位置名称和地理坐标,但不同类别及对应颜色值的DataFrame:

import pandas as pd
from branca.colormap import LinearColormap


# Create base data frame
df = pd.DataFrame({'loc_name': ['Palmdale', 'Pacoima', 'West L.A.', 'Metro L.A.', 'Lincoln Heights', 'El Monte',
                                'Pomona', 'Inglewood', 'South L.A.', 'East L.A.', 'Lynwood', 'Norwalk', 'Wilmington',
                                'Long Beach'],
                   'loc_lat': [34.5800111, 34.2662363, 34.0364075, 34.0487368, 34.0735519, 34.0733908,
                               34.0620289, 33.930828, 33.990596, 34.021968, 33.930476, 33.902052, 33.7814812,
                               33.857974],
                   'loc_lon': [-118.0915039, -118.4224082, -118.4364343, -118.3091383, -118.2161354, -118.0418393,
                               -117.7610335, -118.325139, -118.3311216, -118.164376, -118.175329, -118.083686, -118.2626444,
                               -118.185061]})


# Create df1 and its variable coloring, based on its values
# ------------------------------------------------
df1 = df.copy()
df1['category'] = 'volume'
df1['value'] = [23148, 78629, 38670, 176483, 136961, 64221, 29217, 
                131525, 172852, 113231, 144485, 63213, 51900, 88446]

df1_colormap = LinearColormap(colors=['blue', 'red'], 
                              vmin=df1['value'].min(), 
                              vmax=df1['value'].max())

def df1_color_tag(row):
    return df1_colormap(row['value'])

df1['color'] = df1.apply(df1_color_tag, axis=1)


# Create df2 and its variable coloring, based on its values
# ------------------------------------------------
df2 = df.copy()
df2['category'] = 'index'
df2['value'] = range(1, 15)

df2_colormap = LinearColormap(colors=['green', 'yellow'], 
                              vmin=df2['value'].min(), 
                              vmax=df2['value'].max())

def df2_color_tag(row):
    return df2_colormap(row['value'])

df2['color'] = df2.apply(df2_color_tag, axis=1)

步骤2:创建folium地图

将df1和df2的数据分别放入folium.FeatureGroups():

import folium
from folium import plugins


# Create a map
la_map = folium.Map(location=[34.24, -118.091233], zoom_start=9) 

category_feature_groups = {}


# Create category feature group markers for df1 dataframe
# ----------------------------------------------------------------------
feature_group_df1 = folium.FeatureGroup(name='volume', overlay=False)
folium.TileLayer(tiles='OpenStreetMap').add_to(feature_group_df1)
feature_group_df1.add_to(la_map)
    
#Loop through each row of crc data to plot CRC location markers
for i,row in df1.iterrows():
    
    custom_icon = folium.DivIcon(
        icon_size=(40, 40),
        icon_anchor=(20, 20),  # Position of the icon center
        html=f"""
        <div style="width: 40px; 
                    height: 40px; 
                    background-color: {row['color']}; 
                    border-radius: 50%; 
                    display: flex; 
                    justify-content: center; 
                    align-items: center; 
                    color: white; 
                    font-weight: bold;">
        </div>
        """
    )
    
    #Setup the content of the popup
    iframe = folium.IFrame(row['loc_name'] + '<br/><br/>' + \
                           row['category'] + ': ' + str(row['value']))
    
    #Initialise the popup using the iframe
    popup = folium.Popup(iframe, min_width=200, max_width=200)
    
    #Add each row to the map
    folium.Marker(location=[row['loc_lat'],row['loc_lon']],
                  popup = popup,
                  icon = custom_icon).add_to(la_map)
    
feature_group_df1.add_to(la_map)
category_feature_groups['volume'] = feature_group_df1


# Create category feature group markers for df2 dataframe
# ----------------------------------------------------------------------
feature_group_df2 = folium.FeatureGroup(name='index', overlay=False)
folium.TileLayer(tiles='OpenStreetMap').add_to(feature_group_df2)
feature_group_df2.add_to(la_map)
    
#Loop through each row of crc data to plot CRC location markers
for i,row in df2.iterrows():
    
    custom_icon = folium.DivIcon(
        icon_size=(40, 40),
        icon_anchor=(20, 20),  # Position of the icon center
        html=f"""
        <div style="width: 40px; 
                    height: 40px; 
                    background-color: {row['color']}; 
                    border-radius: 50%; 
                    display: flex; 
                    justify-content: center; 
                    align-items: center; 
                    color: white; 
                    font-weight: bold;">
        </div>
        """
    )
    
    #Setup the content of the popup
    iframe = folium.IFrame(row['loc_name'] + '<br/><br/>' + \
                           row['category'] + ': ' + str(row['value']))
    
    #Initialise the popup using the iframe
    popup = folium.Popup(iframe, min_width=200, max_width=200)
    
    #Add each row to the map
    folium.Marker(location=[row['loc_lat'],row['loc_lon']],
                  popup = popup,
                  icon = custom_icon).add_to(la_map)
    
feature_group_df2.add_to(la_map)
category_feature_groups['index'] = feature_group_df2


# Add Layer Control
folium.LayerControl(collapsed=False, overlay=True).add_to(la_map)

</think_never_used_51bce0c785ca2f68081bfa7d91973934>
</think_never_used_51bce0c785ca2f68081bfa7d91973934>

问题表现

生成的地图中,所有单选按钮选项均显示df2(即最后定义的folium.FeatureGroup())的数值。

volume选项显示df2数据
index选项显示df2数据


内容的提问来源于stack exchange,提问作者bshelt141

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:56:00