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 9 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
98 changes: 98 additions & 0 deletions python/grass/jupyter/interactivemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
reproject_region,
update_region,
get_location_proj_string,
save_vector,
)


Expand Down Expand Up @@ -353,6 +354,101 @@ 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(edit=False, remove=False)
drawn_geometries = []
geo_json_layers = {}
save_button_control = None

def handle_draw(_target, action, geo_json):
if action == "created":
drawn_geometries.append(geo_json)
print(f"Geometry created: {geo_json}")

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="New vector map name:",
style={"description_width": "initial"},
layout=widgets.Layout(
width="80%",
margin="1px 1px 1px 1px",
),
)
save_button = widgets.Button(
29riyasaxena marked this conversation as resolved.
Show resolved Hide resolved
description="Save",
layout=widgets.Layout(width="20%", margin="1px 1px 1px 1px"),
)

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
draw_control.clear()
drawn_geometries.clear()

save_button.on_click(save_geometries)

hbox_layout = widgets.Layout(
display="flex",
flex_flow="row",
align_items="stretch",
width="300px",
justify_content="space-between",
)

save_button_control = self._ipyleaflet.WidgetControl(
widget=widgets.HBox([name_input, save_button], layout=hbox_layout),
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)
self.map.add_control(toggle_control)

def draw_computational_region(self):
"""
Allow users to draw the computational region and modify it.
Expand Down Expand Up @@ -481,6 +577,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
20 changes: 20 additions & 0 deletions python/grass/jupyter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
# for details.

"""Utility functions warpping existing processes in a suitable way"""
import tempfile
import json

from pathlib import Path
import grass.script as gs

Expand Down Expand Up @@ -201,6 +204,23 @@ 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
"""
with tempfile.NamedTemporaryFile(
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
suffix=".geojson", delete=False, mode="w"
) as temp_file:
temp_filename = temp_file.name
for each in geo_json["features"]:
each["properties"].clear()
json.dump(geo_json, temp_file)
gs.run_command("v.import", input=temp_filename, output=name)


def get_region_bounds_latlon():
"""Gets the current computational region bounds in latlon."""
region = gs.parse_command("g.region", flags="gbp")
Expand Down
Loading