如何解析美国县界JSON文件并在Folium热力图上叠加指定县界
解决Folium中指定县界提取与热力图叠加问题
一、提取并绘制指定县的边界
原代码直接加载了全部县界数据,我们需要先解析GeoJSON并筛选目标县的记录,再进行绘制:
import folium import json # 目标县列表(注:Raleigh对应Wake县,Charlotte对应Mecklenburg县,需根据GeoJSON实际名称调整) target_counties = ["Durham", "Wake", "Mecklenburg"] geo_path = r"C:\Users\RShuell\Downloads\gz_2010_us_050_00_500k.json" # 加载并解析GeoJSON数据 with open(geo_path, 'r') as f: geo_data = json.load(f) # 筛选目标县的地理特征 filtered_features = [ feature for feature in geo_data['features'] if feature['properties']['NAME'] in target_counties ] # 重组为标准GeoJSON结构 filtered_geo = { "type": "FeatureCollection", "features": filtered_features } # 初始化地图(定位到北卡核心区域) m = folium.Map(width="100%", height="100%", location=[35.7, -78.6], zoom_start=9) # 添加筛选后的县界,可自定义样式 folium.GeoJson( filtered_geo, style_function=lambda x: { 'color': '#0066cc', 'weight': 2, 'fillOpacity': 0.1 } ).add_to(m)
二、将热力图叠加在县界之上
原问题源于创建了两个独立地图实例,只需将县界和热力图添加到同一个地图对象,并控制图层顺序即可:
import folium from folium.plugins import HeatMap import json # 1. 加载并筛选县界数据 target_counties = ["Durham", "Wake", "Mecklenburg"] geo_path = r"C:\Users\RShuell\Downloads\gz_2010_us_050_00_500k.json" with open(geo_path, 'r') as f: geo_data = json.load(f) filtered_features = [ feature for feature in geo_data['features'] if feature['properties']['NAME'] in target_counties ] filtered_geo = { "type": "FeatureCollection", "features": filtered_features } # 初始化统一地图实例 m = folium.Map(location=[35.5, -82.5], zoom_start=7, width="100%", height="100%") # 先添加县界(底层图层) folium.GeoJson( filtered_geo, style_function=lambda x: {'color': '#0066cc', 'weight': 2, 'fillOpacity': 0.1} ).add_to(m) # 2. 添加热力图(上层图层,后添加的元素会覆盖在上方) max_amount = float(df_2std['Total_Cust_Minutes'].max()) hm_wide = HeatMap( list(zip(df_2std.Circuit_Latitude.values, df_2std.Circuit_Longitude.values, df_2std.Total_Cust_Minutes.values)), min_opacity=0.2, max_val=max_amount, radius=25, blur=20, max_zoom=1, opacity=0.6 # 调整透明度,让下方县界可见 ) hm_wide.add_to(m) # 显示最终地图 m
核心注意点:
- 所有图层必须绑定到同一个
folium.Map实例,不能分开创建 - 图层渲染顺序:先加底层元素(县界),再加覆盖层(热力图)
- 通过调整热力图的
opacity参数(0-1区间),保证县界能透过热力图显示
内容的提问来源于stack exchange,提问作者ASH
相关产品推荐
相关产品推荐

