使用 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 文件

附言我是编程新手,所以任何类型的建议都会非常有帮助

对于那些会遇到类似问题的人 - 我发现创建一个复合 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

最新更新