I'm working with Jupiter and ipywidgets and Ipyleaflet , trying to draw polygons on a map and saving to a geodataframe. I have the following in a notebook cell:
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)
After drawing the shapes in the map, I can see
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)) in here [-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)) in here
listed in the next cell (the expected results). However when I try:
print(gdf2)
I get:
NameError: name 'gdf2' is not defined
What am I doing wrong
gdf2 is a local variable from handle_draw
function. It is thus not defined outside of this function.
If you want to keep its value, define it before, e.g.
zoom = 15
gdf2 = None
Then use global at the beginning of handle_draw
function:
def handle_draw(self, action, geo_json):
global gdf2
Note: edited to let only the answer