pythondictionaryfolium

Folium heatmap with tooltips


I'm trying to create a heatmap with tool tips displaying additional information when the user rolls their mouse over that area. Example of the data I have is:

heat_df = pd.DataFrame({'Latitude':[45.3288, 45.3311],
                        'Longitude':[-121.6625, -121.6625,],
                        'Count':[4, 2],
                        'Note':[10, 20]})

Where count determines the density colour of the heatmap, and Note contains information which I would like to include in a tooltip (in reality I have a lot more data than this). Creating the heatmap is simple:

m = folium.Map([45.35, -121.6972], zoom_start=12)
#Repeat by count number
heat_data = heat_df.loc[heat_df.index.repeat(heat_df['Count']), ['Latitude','Longitude']].dropna()
heat_data = [[row['Latitude'], row['Longitude']] for index, row in heat_df.iterrows()]
HeatMap(heat_data).add_to(m)
m.save(r"test.html")

enter image description here

But I can't find an obvious way to add labels to the data. I tried adding markers with the tool tips, which does show what I want, but then my heatmap is covered in markers and can't be seen very well:

m = folium.Map([45.35, -121.6972], zoom_start=12)
heat_data = heat_df.loc[heat_df.index.repeat(heat_df['Count']), ['Latitude','Longitude']].dropna()
heat_data = [[row['Latitude'], row['Longitude']] for index, row in heat_df.iterrows()]
HeatMap(heat_data).add_to(m)
for i, row in heat_df.iterrows():
    folium.Marker([row['Latitude'], row['Longitude']], tooltip=f'Tooltip value: {row['Note']}', icon=None).add_to(m)
m.save(r"test.html")

enter image description here

Is there a way to add tooltips to a heatmap (perhaps they change depending on zoom level? as heatmaps change depending on the zoom). Or is there a way to have an invisible marker, so the tooltip would still appear when the mouse rolls over it but there isn't a big marker in the way?


Solution

  • I found a solution, if you use a circle marker, then you can set color=None to get rid of the outer circle, and set the fill=True and opacity=0 to make the fill be see through, then the tooltips show up without a visible marker. Like this:

    m = folium.Map([45.35, -121.6972], zoom_start=12)
    heat_data = heat_df.loc[heat_df.index.repeat(heat_df['Count']), ['Latitude','Longitude']].dropna()
    heat_data = [[row['Latitude'], row['Longitude']] for index, row in heat_df.iterrows()]
    HeatMap(heat_data).add_to(m)
    for i, row in heat_df.iterrows():
        folium.CircleMarker([row['Latitude'], row['Longitude']], radius=20,
                            fill_opacity=0, fill=True, color=None,
                            tooltip=f'Tooltip value: {row['Note']}', icon=None).add_to(m)
    m.save(r"test.html")
    

    enter image description here

    (The box is because I clicked on the circle to be able to use the snipping tool to get an image. The tooltip shows up without the box usually)