如何在Dash-Leaflet美国地图中实现点击切换州高亮状态?
实现美国州地图点击高亮/取消高亮功能
要实现点击州切换高亮状态的功能,你需要修改dl.GeoJSON的**style属性**,通过回调动态控制每个地理要素的样式,同时跟踪已选中的州来实现切换逻辑。以下是修改后的完整代码:
import dash_leaflet as dl from dash import Dash, html, Output, Input, State from dash_extensions.javascript import arrow_function, assign app = Dash() # 定义动态样式函数:根据是否选中返回对应样式 style_func = assign("""function(feature, context) { const selected = context.props.selectedFeatures.includes(feature.properties.name); return { fillColor: selected ? '#FF9933' : '#3388FF', weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: selected ? 0.7 : 0.3 }; }""") app.layout = html.Div([ dl.Map(center=[39, -98], zoom=4, children=[ dl.TileLayer(), dl.GeoJSON( url="/assets/us-states.pbf", format="geobuf", id="states", hoverStyle=arrow_function(dict(weight=5, color='#666', dashArray='')), style=style_func, # 绑定动态样式函数 options=dict(hidden=False) # 显示地理要素 ), ], style={'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block"}, id="map"), html.Div(id="state"), html.Div(id="capital"), # 隐藏div用来存储已选中的州列表 html.Div(id="selected-states", style={'display': 'none'}) ]) @app.callback( [Output("state", "children"), Output("selected-states", "children")], Input("states", "click_feature"), State("selected-states", "children") ) def update_selection(feature, selected_states): # 初始化选中列表 selected = selected_states.split(",") if selected_states else [] if feature is not None: state_name = feature['properties']['name'] # 切换选中状态:已选中则移除,未选中则添加 if state_name in selected: selected.remove(state_name) else: selected.append(state_name) # 更新显示文本 selected_text = f"已选中:{', '.join(selected)}" if selected else "未选中任何州" return selected_text, ",".join(selected) return "", "" # 触发样式更新的回调:当选中列表变化时,重新渲染GeoJSON样式 @app.callback( Output("states", "style"), Input("selected-states", "children") ) def update_style(selected_states): return style_func if __name__ == '__main__': app.run_server(port=8052, debug=True)
关键说明:
- 动态样式函数:通过
assign定义JavaScript函数,根据当前州是否在选中列表中返回不同的填充色、透明度等样式,实现高亮效果。 - 状态跟踪:用隐藏的
selected-statesdiv存储已选中的州名称,作为回调的State来维护选中状态。 - 切换逻辑:点击州时,判断该州是否已选中,执行添加/移除操作,更新选中列表和显示文本。
- 样式更新触发:当选中列表变化时,重新绑定样式函数,让GeoJSON组件重新渲染每个要素的样式。
内容的提问来源于stack exchange,提问作者Mohammed Eltaweel
相关产品推荐
相关产品推荐

