Hello everyone,
I was wondering if it is possible to add a click event on a graph (specifically a map) that would capture any click the user makes, even if it is not on a known point.
I’ve searched numerous docs and forums but I couldn’t find anything that answers my question, even the plotly docs ( Event handlers in JavaScript) on event handlers in JS do not seem to have a suitable solution.
With the exemple below, you can see a callback linked to the clickData property of my scatter-geo graph. But if the user clicks somewhere on the map that is not associated with a point, I would need the app to display the coordinates anyway.
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
# Load the gapminder data for the year 2007
df = px.data.gapminder().query("year == 2007")
# Create the ScatterGeo plot with Plotly Express
fig = px.scatter_geo(
df,
locations="iso_alpha",
size="pop",
hover_name="country", # display country name on hover
title="Countries in 2007",
template="plotly",
color="continent",
)
app = dash.Dash(__name__)
app.layout = html.Div(
[dcc.Graph(id="scatter-geo", figure=fig), html.Div(id="click-output")]
)
# Callback to display the clicked country
@app.callback(Output("click-output", "children"), Input("scatter-geo", "clickData"))
def display_click_data(click_data):
if click_data is None:
return "Click on a country to get more information."
country = click_data["points"][0]
return f"You clicked on: {country['hovertext']} with coordinates ({country['lat']}°, {country['lon']}°)"
if __name__ == "__main__":
app.run(debug=True)