未定义 geodataframe
我正在使用Jupiter、ipywidgets和Ipyleaflet,试图在地图上绘制多边形并保存到一个地理数据框中。在我的笔记本单元格里有以下内容:
zoom = 15
from ipywidgets import Output, interact
import ipywidgets
from __future__ import print_function
import ipyleaflet
import geopandas as gpd
import pandas as pd
# from shapely.geometry import Point, LineString, Polygon
from shapely import geometry
from ipyleaflet import (
Map,
Marker,
TileLayer, ImageOverlay,
Polyline, Polygon, Rectangle, Circle, CircleMarker,
GeoJSON,
DrawControl)
# Create an Output widget
out = Output()
# Define a function to handle interactions
def handle_interaction(change):
with out:
print(change)
c = ipywidgets.Box()
c.children = [m]
# keep track of rectangles and polygons drawn on map:
def clear_m():
global rects,polys
rects = set()
polys = set()
clear_m()
rect_color = '#a52a2a'
poly_color = '#00F'
myDrawControl = DrawControl(
rectangle={'shapeOptions':{'color':rect_color}},
polygon={'shapeOptions':{'color':poly_color}}) #,polyline=None)
def handle_draw(self, action, geo_json):
global rects,polys
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)
# Create GeoDataFrame if it doesn't exist
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)
myDrawControl.on_draw(handle_draw)
m.add_control(myDrawControl)
在地图上绘制形状后,我可以看到
display(out)
[-88.434269, 31.660818] [-88.431051, 31.661439] [-88.431265, 31.660087] [-88.433582, 31.659941] ((-88.434269, 31.660818), (-88.431051, 31.661439), (-88.431265, 31.660087), (-88.433582, 31.659941)) 在这里 [-88.432166, 31.658474] [-88.429678, 31.65767] [-88.431609, 31.656684] [-88.434054, 31.65778] ((-88.432166, 31.658474), (-88.429678, 31.65767), (-88.431609, 31.656684), (-88.434054, 31.65778)) 在这里
这些是在下一个单元格中列出的(预期的结果)。但是当我尝试:
print(gdf2)
我得到了:
NameError: name 'gdf2' is not defined
我哪里做错了?
2 个回答
1
我不太确定你是不是没有粘贴完整的代码,不过除了你函数内部的局部环境之外,确实没有地方定义过 gdf2
。gdf2
需要是一个全局变量。
2
gdf2是handle_draw
函数里的一个局部变量。这意味着它在这个函数外面是无法使用的。
如果你想保留它的值,可以在函数外面先定义它,比如:
zoom = 15
gdf2 = None
然后在handle_draw
函数的开头使用global关键字:
def handle_draw(self, action, geo_json):
global gdf2
注意:已经编辑过,只保留了答案部分