Folium: Display pandas dataframe info in geojson popup

1.8k Views Asked by At

I'm having trouble creating popups for polygons in Folium. I have a GeoJSON file of all the countries in the world, and for each country, I would like to display a popup. However, my issue is that the info I need in the popup is contained in a separate pandas dataframe.

I downloaded a GeoJSON with all the countries of the world here, and mapped that in Folium like so:

# Create a Map instance
m = folium.Map(location=[40.7, -74.0], tiles = 'cartodbpositron', zoom_start=11, control_scale=True)

## add chloropleth layer
m.choropleth(
    geo_data='path-to-geojson-file-i-downloaded',
    name='Countries',
)  

Next, I added markers to my map based on a pandas dataframe that has coordinates of countries along with an html page per country as the popup data:

# add markers with basic information
fg = folium.FeatureGroup(name='Articles by Country')

for loc,html in zip(countries,countries_htmls):
    fg.add_child(folium.Marker(location=loc, popup=html))

m.add_child(fg)

# enable layers to be turned in or out
folium.LayerControl().add_to(m)

Here is the output map: map output

Clicking on the little blue markers gives me the correct popup, but ideally I want the polygon of the chloropleth layer itself to give me the popup, since each country only needs one popup.

Does anyone know if there's a way that I can render my map so that a marker can be connected somehow to the chloropleth geojson layer so that each country polygon has a popup? Sample here:

country polygon popup

Would really appreciate any and all help! Thank you so much.

1

There are 1 best solutions below

0
On

As you are not using the Choropleth map to visualize data, you should better use the GeoJson object. In the last version of Folium (0.11.0), there is a new feature called GeoJsonPopup that you can use to do what you want (add popup for each country). You can use it like that :

import folium
m = folium.Map(location=[40.7, -74.0], tiles = 'cartodbpositron', zoom_start=11, control_scale=True)
folium.features.GeoJson('carto.json', name="Countries", popup=folium.features.GeoJsonPopup(fields=['name_long'])).add_to(m)
m