Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

grass.jupyter: Allow users to draw simple geometries and save it as vector #4003

Merged
merged 18 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions python/grass/jupyter/interactivemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import base64
import json
from .reprojection_renderer import ReprojectionRenderer
from .utils import save_vector


def get_backend(interactive_map):
Expand Down Expand Up @@ -346,6 +347,89 @@ def add_layer_control(self, **kwargs):
else:
self.layer_control_object = self._ipyleaflet.LayersControl(**kwargs)

def setup_drawing_interface(self):
"""
Allow Users to draw Geometry and Save/Delete them.
"""
import ipywidgets as widgets # pylint: disable=import-outside-toplevel

draw_control = self._ipyleaflet.DrawControl()
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved
drawn_geometries = []
geo_json_layers = {}
save_button_control = None

def handle_draw(_, action, geo_json):
print(drawn_geometries, "dgb")
if action == "created":
drawn_geometries.append(geo_json)
print(f"Geometry created: {geo_json}")
elif action == "deleted":
drawn_geometries.clear()
for layers in geo_json_layers:
print("layers", layers)
self.map.remove_layer(layers)

draw_control.on_draw(handle_draw)

draw_button = widgets.ToggleButton(
icon="pencil",
value=False,
tooltip="Click to draw geometries",
layout=widgets.Layout(width="33px", margin="0px 0px 0px 0px"),
)

def toggle_geometry(change):
if change["new"]:
self.map.add_control(draw_control)
show_interface()
else:
drawn_geometries.clear()
self.map.remove_control(draw_control)
hide_interface()

draw_button.observe(toggle_geometry, names="value")

def show_interface():
nonlocal save_button_control

name_input = widgets.Text(description="Name:")
save_button = widgets.Button(
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved
description="Save Geometries", button_style="success"
)

def save_geometries(b):
name = name_input.value
if name and drawn_geometries:
for geometry in drawn_geometries:
geometry["properties"]["name"] = name
geo_json = {
"type": "FeatureCollection",
"features": drawn_geometries,
}
save_vector(name, geo_json)
geo_json_layer = self._ipyleaflet.GeoJSON(data=geo_json, name=name)
geo_json_layers[name] = geo_json_layer
self.map.add_layer(geo_json_layer)
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved

save_button.on_click(save_geometries)

save_button_control = self._ipyleaflet.WidgetControl(
widget=widgets.VBox([name_input, save_button]), position="topright"
)
self.map.add_control(save_button_control)

def hide_interface():
nonlocal save_button_control
drawn_geometries.clear()
if save_button_control:
self.map.remove_control(save_button_control)
save_button_control = None

toggle_control = self._ipyleaflet.WidgetControl(
widget=draw_button, position="topright"
)
self.map.add_control(toggle_control)

def show(self):
"""This function returns a folium figure or ipyleaflet map object
with a GRASS raster and/or vector overlaid on a basemap.
Expand All @@ -367,6 +451,8 @@ def show(self):
return fig

# ipyleaflet
if self._ipyleaflet:
self.setup_drawing_interface()
self.map.add(self.layer_control_object)
return self.map

Expand Down
22 changes: 22 additions & 0 deletions python/grass/jupyter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,28 @@ def get_rendering_size(region, width, height, default_width=600, default_height=
return (default_width, round(default_width * region_height / region_width))


def save_vector(name, geo_json):
"""
Saves the user drawn vector.

param geojson_filename: name of the geojson file to be saved
param name: name with which vector should be saved
"""
import tempfile
import json

try:
with tempfile.NamedTemporaryFile(
suffix=".geojson", delete=False, mode="w"
) as temp_file:
temp_filename = temp_file.name
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved
json.dump(geo_json, temp_file)
gs.run_command("v.import", input=temp_filename, output=name)
print(f"Imported geometry with name '{name}' into GRASS GIS.")
except Exception as e:
print(f"Failed to import geometries into GRASS GIS: {e}")


def save_gif(
input_files,
output_filename,
Expand Down
Loading