geopandas读取的shapefile无法添加到ipyleaflet图层报错如何解决
错误原因
ipyleaflet的add_layer方法仅支持传入ipyleaflet内置的图层类实例,直接传入GeoPandas的GeoDataFrame对象不属于合法的图层类型,model_id是ipyleaflet图层对象的特有属性,GeoDataFrame没有该属性因此触发报错。
解决方案
方法1:使用ipyleaflet内置的GeoData类直接加载GeoDataFrame(推荐,操作最简)
- 首先导入
GeoData类,将GeoDataFrame封装为合法的图层对象后再添加到地图,完整可运行代码如下:
import geopandas as gpd from ipyleaflet import Map, basemaps, GeoData # 读取shapefile fire_was = gpd.read_file('fire_wa.shp') # 若shp坐标系不是WGS84(EPSG:4326),需先转坐标系避免位置偏移 fire_was = fire_was.to_crs(epsg=4326) # 初始化地图 center = [47.409824923593575,-120.43401014843751] zoom = 7 m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=center, zoom=zoom) # 封装为GeoData图层,可自定义样式 fire_layer = GeoData( geo_dataframe=fire_was, style={ "color": "red", # 边框颜色 "weight": 1, # 边框粗细 "fillColor": "orange", # 填充颜色 "fillOpacity": 0.5 # 填充透明度 } ) # 添加图层并渲染地图 m.add_layer(fire_layer) m
方法2:转换为GeoJSON格式后加载(适合需要自定义复杂交互的场景)
- 先将GeoDataFrame转为GeoJSON格式,再用
GeoJSON类封装为图层:
import geopandas as gpd from ipyleaflet import Map, basemaps, GeoJSON fire_was = gpd.read_file('fire_wa.shp').to_crs(epsg=4326) center = [47.409824923593575,-120.43401014843751] zoom = 7 m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=center, zoom=zoom) # 转GeoJSON后封装为图层 fire_layer = GeoJSON( data=fire_was.to_json(), style={"color": "red", "fillOpacity": 0.5} ) m.add_layer(fire_layer) m
内容的提问来源于stack exchange,提问作者coues
相关产品推荐
相关产品推荐

