2017-08-30 112 views
0

以下代碼會生成一個帶有由population填充的國家/地區的Web地圖,其值來自world.json。正常'def'函數而不是lambda

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') 

鏈接world.json

我想知道是否可以使用由def創建的普通函數而不是lambda函數作爲參數style_function的值。我嘗試了,創造一個功能:

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 

但是,我想不出如何style_function使用它。這是可能的還是lambda函數在這裏是不可替代的?

+0

你的意思是'style_function = feature'? – khelwood

+0

或者只是'def style_function'而不是'def feature'? 'style_function'甚至可以在哪裏使用? –

+1

另外 - 你真的想每次調用該函數時打開和加載json文件嗎?當然 - 你想要做那一部分,然後使用該函數來獲得'x'的風格,無論這是... –

回答

2

style_function拉姆達可以用這樣的功能所取代:

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

然後,你可以通過函數名到kwarg:

folium.GeoJson(
    data=..., 
    name=..., 
    style_function=style_function 
) 
+0

'style_function'被用作'GeoJson'的'kwarg' – Wondercricket

+0

Ohhhh,you're對。格式化沒有說清楚,謝謝指出。 – thaavik

0

如果我的理解是正確的,你需要(x是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'} 

,簡單地將其分配給style_function參數(不帶括號):

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