I am using plotly scattermapbox and am in process of making code improvements. To the customdata
property of scattermapbox, I’d like to assign multiple pandas series. In the callback, I read this data and populate a modal pop-up based on click event. Here’s the code:
layout = html.Div([
# Plot properties map
dcc.Graph(id="map-graph"),
)]
Callback to append data and define layout for map-graph
, only posting relevant code snippet:
result_df = pd.DataFrame({'id': [1,2,3,4'],
'name':['a','b','c','d'],
'val': [5,6,7,8],
'lat':[.....], 'long':[....]})
data = []
lat = result_df["lat"]
lng = result_df["long"]
data.append({
"type": "scattermapbox",
"lat": lat,
"lon": lng,
"mode": "markers",
"clickmode": "event+select",
"customdata": { "Name": result_df["name"],
"id": result_df["id"]},
"marker": {
"symbol": "circle",
"size": 12,
"opacity": 0.7,
"color": "black"
}
}
)
Callback that reads customdata
, parses as json
data and then populate the modal
based on selection.
@application.callback(
[
Output("modal-1","is_open"),
Output("name","children"),
Output("val","children"),
],
[
# Button clicks
Input("map-graph1","clickData"),
Input("c-button", "n_clicks"),
Input("close","n_clicks1")
],
[
State("modal-1", "is_open")
],
)
def display_popup(clickData, n_clicks, close, is_open):
if clickData:
res = json.dumps(clickData, indent=2)
Name = clickData["points"][0]["customdata"]["Name"]
id = clickData["points"][0]["customdata"]["id"]
return(not is_open, Name, id,)
elif close:
return is_open
else:
return (no_update)
Here’s what the response from clickData looks like when I print:
{
"points": [
{
"curveNumber": 0,
"pointNumber": 15,
"pointIndex": 15,
"lon": -118.27600459999998,
"lat": 34.0456796,
}
]
}
customdata
is missing from the response. How do I tie tie the data back to (lat, long)
clicked on the map-graph
and populate the modal with Name
, id
etc information from custom data.