我正在使用ipyleaflet
中的draw_control
函数在地图上绘制多边形。我正在收集我使用feature_collection
变量绘制的内容,它运行良好。但是,当我在映射的bin
按钮上按下clear all
时,feature_collection
变量不会被清空——我如何将映射上按下的clear all
按钮转换为清除我的feature_collection
变量?目前它复制了我以前画的,所以我有这样的工作流程:
- 绘制两个多边形
feature_collection
包含关于两个ploygon的信息- 按地图上
bin
按钮上的clear all
- 在地图上绘制两个新多边形
feature_collection
现在包含6(!(个条目,与1重复。动作两次
这里有一个要复制的代码!基本上,我不知道如何从bin
按钮收集clear_all
操作来清除我的feature_control
变量。
from ipyleaflet import Map, basemaps, basemap_to_tiles, DrawControl, LayersControl, GeoJSON, SearchControl, Marker, FullScreenControl
#Creating empty geojson to collect features drawn on map:
feature_collection = {
'type': 'FeatureCollection',
'features': []}
#Handling items drawn on map:
def handle_draw(self, action, geo_json):
"""Do something with the GeoJSON when it's drawn on the map"""
feature_collection['features'].append(geo_json)
#Generate Basemap:
satellite = basemap_to_tiles(basemaps.Esri.WorldImagery)
osmap = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik)
mymap = Map(layers=(osmap, satellite), center=(55,0), zoom=5,scroll_wheel_zoom=True)
#Generate controls on map:
center=[55,0] #where to start on map: middle of UK
marker = Marker(location=center, draggable=False)
#Draw shapes on map:
dc = DrawControl(
marker={'shapeOptions': {'color': '#0000FF'}},
rectangle={'shapeOptions': {'color': '#0000FF'}},
circlemarker={}
)
dc.on_draw(handle_draw) #call function what to do with objects drawn on maps
#Add all controls to the actual map:
mymap.add_control(dc) #add
#Generate GEOJSON which could contain data to be displayed on map:
geo_json = GeoJSON(data={},style={},hover_style={})
mymap.add_layer(geo_json) #add to map object
mymap
在handle_draw
方法中,您不仅有geo_json
功能,还有一个action
参数,可以帮助您处理DrawingControl
中发生的事情。
清除时,action
将为deleted
。
因此,要调整您的代码,您可以执行以下操作:
#Handling items drawn on map:
def handle_draw(self, action, geo_json):
"""Do something with the GeoJSON when it's drawn on the map"""
if action in ['created', 'edited']:
feature_collection['features'].append(geo_json)
elif action == 'deleted':
feature_collection['features'].remove(geo_json)
return
注意,由于"编辑"没有提供任何关于原始形状的信息,您不知道修改的是哪一个