Python Dash Mapboxgl Polygon click event data,

Viewed 2773

How to get the data (geojson properties - name, id etc) from the mapboxgl polygon click event in python dash/plotly?

Below is Dash Graph element

layer = dict(
        type="fill",
        below='traces',
        color="#18607e",
        opacity=0.7,
        hovermode="closest",
        interactive=True,
        text=[x['properties']['id'] for x in geojson['features']],
        source=geojson,
        sourcetype="geojson"

    )

    element = dcc.Graph(
                id='TxWCD-choropleth',
                figure=dict(
                    data=[dict(
                        type='scattermapbox'
                    )],
                    layout=dict(
                            plot_bgcolor="#18607e",
                            paper_bgcolor="#18607e",
                            clickmode="event+select",
                            mapbox=dict(
                                layers=[layer],
                                accesstoken=_token,
                                center=dict(
                                    lat=53.350140,
                                    lon=-6.266155
                                ),
                                zoom=1,
                                style='light'
                            ),
                            height=600,
                            autosize=True,
                            margin=dict(
                                l=0,
                                r=0,
                                b=0,
                                t=0,
                                pad=4
                            )
                    )
                )
            )

Call Back event:


app.callback(
    Output(component_id='graphs', component_property='children'),
    [Input('map-flex', "n_clicks")]
)
def update_graph(data):

    # Do some updates
    # Expected result: mapbox click event data geojson properties

    return ''

Expected Result:

On click of Mapbox polygon return Mapbox event data. i.e. geojson properties.

Any help or workaround is appreciated. Thanks

1 Answers

Check out the documentation of the scattermapbox. There is an attribute called customdata which you can use to determine what is passed to your callback.

To define the callback you can use this reference. Essentially you are doing the following steps:

  1. Add clickmode attribute to your graph layout:

    'layout': {
        'clickmode': 'event+select'
    }
    
  2. Define your callback:

    @app.callback(
        Output(component_id='graphs', component_property='children'),
        [Input('map-flex', 'clickData')]) 
    def display_click_data(custom_data):
        print(custom_data)
    
Related