首页 > 解决方案 > 使用 Folium 将多个 Geojson 传单添加到一张地图时如何正确使用样式功能?

问题描述

我正在尝试在城市 Folium 地图上添加多个行政区的 Geojson 传单,根据人口密度绘制它们,并且无法在此处正确使用 style_function

我的一段代码:

colorscale=branca.colormap.linear.YlGnBu_09.scale(vmin=df_BoroughsSP.Density.min(),vmax=df_BoroughsSP.Density.max())

def style_function(feature):
    density = df_BoroughsSP.Density[i]
    return {
        'fillOpacity': 0.5,
        'weight': 0.5,
        'fillColor': colorscale(density)
    }

map_SP = folium.Map(location=[latitudeSP, longitudeSP], zoom_start=10)

for i in range(len(df_BoroughsSP.Density)):
 jsonurl='http://polygons.openstreetmap.fr/get_geojson.py?id='+str(df_BoroughsSP.RelationID[i])+'&params=0'
 with urllib.request.urlopen(jsonurl) as url:
    data = json.loads(url.read().decode())
 folium.GeoJson(
    data,
    name='geojson',
    style_function=style_function
 ).add_to(map_SP)

map_SP

我得到了 dict' object is not callable输出。我尝试使用预先计算的值列表而不是 style_function,但得到了相同的结果。

有人知道如何解决这个问题吗?

我知道使用 Cloropleth 会更容易,但我没有将整个城市划分为行政区的 Geojson 文件

ps 我是编程新手,所以任何建议都会很有帮助

标签: pythonpandasgeojsonfolium

解决方案


对于那些会遇到类似问题的人 - 我发现创建复合 Geojson 然后使用 Chloropleth 方法来显示它比尝试使用循环在地图上应用单独的补丁要容易得多

我的最终代码:

# df_BoroughsSP is a Pandas dataframe with density and OpenStreetMap RelationID of each city borough


# Preparing a composite Geojson file from files of individual boroughs
features = []

for index in range(len(df_BoroughsSP.index)):
 jsonurl='http://polygons.openstreetmap.fr/get_geojson.py?id='+str(df_BoroughsSP.RelationID[index])+'&params=0'
 with urllib.request.urlopen(jsonurl) as url:
    Geometry=json.loads(url.read().decode())
    features.append(Feature(geometry=Geometry, properties={"name": df_BoroughsSP.Borough[index],"density":df_BoroughsSP.Density[index]}))

feature_collection = FeatureCollection(features)
with open('myfile.geojson', 'w') as f:
   dump(feature_collection, f)
with open('myfile.geojson', 'r') as f:    
   GeodataSP=json.load(f) #Geojson file with city boundaries, broken down to individual boroughs

推荐阅读