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

Dash Leaflet带下拉筛选功能的散点图失效问题求助

Dash Leaflet下拉筛选功能修复方案

你的代码中筛选功能失效存在几个关键问题,以下是修复后的完整代码:

import dash_leaflet as dl
import dash_leaflet.express as dlx
import pandas as pd
from dash_extensions.javascript import assign
from dash import Dash, html, dcc, Input, Output, State

colorscale = ["white", "yellow", "red"]
chroma = "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
color_prop = 'NumerodeTrans'
df = pd.read_csv("assets/ParadasAtributos.csv")

da = df[['Latitud', 'Longitud', 'ID', color_prop, "CODIGOCONTRATO"]]
da[color_prop] = da[color_prop].astype(int)
dicts = da.to_dict('rows')

# 修正下拉框选项格式,符合Dash组件要求
dd_options = [{"label": opt, "value": opt} for opt in df["CODIGOCONTRATO"].unique()]
dd_defaults = ["Atributo Nacional"]

for item in dicts:
    item["tooltip"] = "{} ({:.1f})".format(item[color_prop], item[color_prop])

geojson = dlx.dicts_to_geojson(dicts, lat="Latitud", lon="Longitud")
geobuf = dlx.geojson_to_geobuf(geojson)

# 修正筛选函数:引用正确的筛选字段名
geojson_filter = assign("function(feature, context){return context.props.hideout.selectedContracts.includes(feature.properties.CODIGOCONTRATO);}")

vmax = df[color_prop].max()
colorbar = dl.Colorbar(colorscale=colorscale, width=20, height=150, min=0, max=vmax, unit="Transacciones por parada")

point_to_layer = assign("""function(feature, latlng, context){
    const {min, max, colorscale, circleOptions, colorProp} = context.props.hideout;
    const csc = chroma.scale(colorscale).domain([min, max]);
    circleOptions.fillColor = csc(feature.properties[colorProp]);
    return L.circleMarker(latlng, circleOptions);
}""")

# 绑定筛选函数到GeoJSON组件,同时初始化筛选字段
geojson = dl.GeoJSON(data=geobuf, id="geojson", format="geobuf",
                     zoomToBounds=True,
                     options=dict(pointToLayer=point_to_layer),
                     superClusterOptions=dict(radius=50),
                     filter=geojson_filter,  # 启用筛选逻辑
                     hideout=dict(colorProp=color_prop, circleOptions=dict(fillOpacity=1, stroke=False, radius=5),
                                  min=0, max=vmax, colorscale=colorscale, selectedContracts=dd_defaults))

app = Dash(external_scripts=[chroma], prevent_initial_callbacks=True)

app.layout = html.Div([
    dl.Map([dl.TileLayer(), geojson, colorbar], style={'width': '100%', 'height': '50vh'}),
    dcc.Dropdown(id="dd", value=dd_defaults, options=dd_options, clearable=False, multi=True)
], style={'width': '100%', 'margin': "auto", "display": "block", "position": "relative"})

# 新增回调:同步下拉框选中值到GeoJSON的筛选条件
@app.callback(Output("geojson", "hideout"), Input("dd", "value"), State("geojson", "hideout"))
def update_hideout(selected, current_hideout):
    current_hideout["selectedContracts"] = selected
    return current_hideout

if __name__ == '__main__':
    app.run_server(debug=True)

关键修改点说明:

  1. 下拉框选项格式修正:将原数组格式的选项改为{"label": opt, "value": opt}的字典结构,符合Dash Dropdown组件的规范,确保选项正常显示和选中。
  2. 筛选函数字段修正:把筛选函数中错误的feature.properties.name改为feature.properties.CODIGOCONTRATO,匹配你实际要筛选的字段。
  3. 启用筛选逻辑:在dl.GeoJSON组件中添加filter=geojson_filter参数,让筛选函数生效。
  4. 新增同步回调:通过回调将下拉框的选中值同步到GeoJSON的hideout对象中,让筛选函数能实时获取最新的筛选条件。
  5. 初始化筛选字段:在初始hideout中添加selectedContracts=dd_defaults,确保默认筛选条件生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:30:42