Get map of each country with Mapbox

app = dash.Dash(__name__)


app.layout = html.Div([
    html.Div([
        html.Label(['Demo Dash !']),
        dcc.Dropdown(
            id = 'demo-dropdown',
            options = [{'label':str(item) , 'value':str(item) } for item in sorted(df_copy['country_txt'].unique())],
            placeholder='Select a country...',
            style={"width": "50%"}
            )]),
    html.Div([dcc.Graph(id = 'id-graph', config = {'scrollZoom' : True})]),
])


@app.callback(
     Output('id-graph', 'figure'),
    [Input('demo-dropdown', 'value')])
def update_output(value):
    df_sub = df_copy.loc[df_copy['country_txt'] == value]
    
    #create graph
    location = [go.Scattermapbox(lon = df_sub['longitude'], lat = df_sub['latitude'] , mode = 'markers',hoverinfo= 'text' )]
    
    # return graph
    return {'data': location , 'layout':go.layout(uirevision = 'foo' , hovermode = 'closest' , hoverdistance = 2 , mapbox =dict(accesstoken = mapbox_access_token))}
    

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

Screenshot of Dashboard:

As you can see no graph of country.
I don’t know how to use mapbox for each country in dropdown menu

Hi @matsujju
I recommend assigning a country value to the dropdown inside the layout section like this:

        dcc.Dropdown(
            id = 'demo-dropdown',
            options = [{'label':str(item) , 'value':str(item) } for item in sorted(df_copy['country_txt'].unique())],
            placeholder='Select a country...',
            style={"width": "50%"},
            value=name_of_one_country_from_list
            )]),

And then, try to print out the object inside the callback function:

def update_output(value):
    df_sub = df_copy.loc[df_copy['country_txt'] == value]
    print(df_sub.head())

What does it print out? does it print out a dataframe with a country?

Yes, it does print out the dataframe with 5 rows of the value i put as country name

do you have your access token?
what is the error that you get? Just an empty graph?

No error just empty graph. and Yes I have both public and secret keys of Mapbox

Here is the traceback after refreshing the browser page:

Exception on /_dash-update-component [POST]
Traceback (most recent call last):
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\dash\dash.py", line 1059, in dispatch
    response.set_data(func(*args, outputs_list=outputs_list))
  File "C:\Users\Sujju\Anaconda3\envs\machine_learning\lib\site-packages\dash\dash.py", line 994, in add_context
    output_value = func(*args, **kwargs)  # %% callback invoked %%
  File "<ipython-input-87-8c8b180b01b9>", line 31, in update_output
    return {'data': location , 'layout':go.layout(uirevision = 'foo' , hovermode = 'closest' , hoverdistance = 2 , mapbox =dict(accesstoken = mapbox_access_token))}
TypeError: 'module' object is not callable
Exception on /_dash-update-component [POST

Not sure what’s going on. Try with Plotly Express:

import plotly.express as px
...
...
def update_output(value):
    df_sub = df_copy.loc[df_copy['country_txt'] == value]
    fig = px.scatter_mapbox(df_sub , lat="latitude", lon="longitude", zoom=10)

fig.update_layout(
    hovermode='closest',
    mapbox=dict(
        accesstoken=mapbox_access_token)
)
return fig
    

What do you get?

Did you see the above traceback?

Is this related to Mapbox module? Do I have to download the Mapbox module externally?

I’m not sure you can do go.layout. I can’t recall. Either try with plotly express or follow the Basic Example section on Plotly’s documentation more carefully:

yes that’s a typo in your code. it should be go.Layout

1 Like

Looks like yes it was typo from my side and I regret that. How could I miss this?
Should I delete this post?

Thanks for catching that, @chriddyp

I don’t think you should delete this. It’s a good learning opportunity in case others make the same mistake.

1 Like

Thanks a lot for helping here both of you @chriddyp @adamschroeder