How do I display country name and population when I hover over world map using Python folium library?

Viewed 2570

I made a Webmap with python using folium. The map reads in population.json file that contains country names, and population number and displays a map on browser.

Here's the code:

import pandas
import folium

map = folium.Map(location=[32, 0], zoom_start=4.3, tiles = "CartoDB positron", max_zoom = 100)


fgp = folium.FeatureGroup(name="Population" )

def colorPicker(population):
    if population < 10000000:
        return 'green'
    elif population >= 10000000 and population < 500000000:
        return 'orange'
    else:
        return 'red'


fgp.add_child(folium.GeoJson(data=open('population.json', 'r', encoding='utf-8-sig').read(), 
style_function=lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])},
tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005'])

))


map.add_child(fgp)

map.save("index.html")

I created feature group and add_child to add colors to each country on the map based on their population size using this code:

style_function=lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])}

What I wanted to then is whenever user hovers over a country, I want to display the name of the country and the population size of the country. For that, I wrote:

tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005'])

Instead of giving me the name of the country, it gives me this... Picture of map

It suppose to say "China: 'population size'", but instead is shows "at 0x24...."

I'm not sure why. I've tried several variations of tooltip such as:

tooltip=lambda x: '{0}\n{1}'.format(x['properties']['Name'], x['properties']['POP2005']) 
tooltip=lambda x: '%s\n%s' % (x['properties']['Name'], x['properties']['POP2005']) 
tooltip= lambda x: {'text': x['properties']['Name']}))
tooltip= lambda x: {'%s': x['properties']['Name']}))

But still, shows me same output

Here's link to population.json file: file

1 Answers

Use GeoJson and GeoJsonTooltip classes:

import folium

m = folium.Map(location=[32, 0],
               zoom_start=4.3,
               tiles = "CartoDB positron",
               max_zoom = 100)

def colorPicker(population):
    if population < 10000000:
        return 'green'
    elif population >= 10000000 and population < 500000000:
        return 'orange'
    else:
        return 'red'

folium.GeoJson(open('population.json', 'r', encoding='utf-8-sig').read(),
               name = 'Population',
               style_function = lambda x: {'fillColor': colorPicker(x['properties']['POP2005'])},
               tooltip = folium.GeoJsonTooltip(fields=('NAME', 'POP2005',),
                                               aliases=('Country','Population')),
               show = True).add_to(m)


#folium.LayerControl().add_to(m)
m

and you get:

enter image description here

Related