You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter+ipyleaflet绘制多边形,gdf2未定义报错求助

问题分析与解决方法

你的代码存在两个关键问题导致gdf2未定义的错误:

  1. 变量作用域问题
    gdf2仅在handle_draw函数内部被创建,属于局部变量,函数外部无法访问。同时你没有在全局作用域提前初始化gdf2,导致第一次执行判断时就会触发未定义错误。

  2. 语法错误
    代码中if gdf2: is None:是错误的语法,正确的判断空值写法应该是if gdf2 is None:。

修正后的代码

需要做以下几处修改:

  • 在全局作用域初始化gdf2为None
  • 在handle_draw函数中声明gdf2为全局变量
  • 修正判断空值的语法错误
# 全局初始化gdf2
gdf2 = None

def handle_draw(self, action, geo_json):
    global rects, polys, gdf2  # 添加gdf2到全局声明
    polygon=[]
    for coords in geo_json['geometry']['coordinates'][0][:-1][:]:
        handle_interaction(coords)
        polygon.append(tuple(coords))
    polygon = tuple(polygon)
    handle_interaction(polygon)
    if geo_json['properties']['style']['color'] == '#00F':  # poly
        if action == 'created':
            handle_interaction(" in here")
            polys.add(polygon)
            polygon_geom = geometry.Polygon(polygon)
    
            # 修正语法错误,同时使用全局的gdf2
            if gdf2 is None:
                gdf2 = gpd.GeoDataFrame(geometry=[polygon_geom])
            else:
                gdf2 = gdf2.append({'geometry': polygon_geom}, ignore_index=True)
            
        elif action == 'deleted':
            polys.discard(polygon)
    if geo_json['properties']['style']['color'] == '#a52a2a':  # rect
        if action == 'created':
            rects.add(polygon)
        elif action == 'deleted':
            rects.discard(polygon)

另外注意:你当前代码中m(地图对象)没有定义,需要补充地图初始化的代码,比如:

# 添加地图初始化
m = Map(center=(31.66, -88.43), zoom=zoom)

完成以上修改后,绘制多边形再执行print(gdf2)就能正常输出GeoDataFrame内容了。

内容的提问来源于stack exchange,提问作者user1592380

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:04:51