Normal 'def' function instead of lambda

728 views Asked by At

The following code produces a web map with countries colored by population which values come from world.json.

import folium

map=folium.Map(location=[30,30],tiles='Stamen Terrain')

map.add_child(folium.GeoJson(data=open('world.json', encoding='utf-8-sig'),
name="Unemployment",
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

map.save('file.html')

Link of world.json.

I was wondering if it's possible to use a normal function created with def instead of a lambda function as the value of the style_function argument. I tried creating a function for that:

def feature(x):
    file = open("world.json", encoding='utf-8-sig')
    data = json.load(file)
    population = data['features'][x]['properties']['POP2005']
    d ={'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}
    return d

However, I can't think of how to use it in style_function. Is this possible or is the lambda function irreplaceable here?

2

There are 2 answers

2
thaavik On BEST ANSWER

the style_function lambda can be replaced with a function like this:

def style_function(x):
    return {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

Then you can just pass the function name to the kwarg:

folium.GeoJson(
    data=...,
    name=...,
    style_function=style_function
)
0
matusf On

If I understand it right, you need to make function like this one (x is the geojson):

def my_style_function(x):
    color = ''
    if x['properties']['POP2005'] <= 10e6:
        color = 'green'
    elif x['properties']['POP2005'] < 2*10e6:
        color = 'orange'
    return {'fillColor': color if color else 'red'}

and simply assign it to the style_function parameter (without the parenthesis):

map.add_child(folium.GeoJson(data=open('world.json', encoding='utf-8-sig'),
                             name="Unemployment",
                             style_function=my_style_function))