Selaa lähdekoodia

fix draw_control and add demo

Falko Schindler 1 vuosi sitten
vanhempi
säilyke
bf0f7ca93b

+ 9 - 5
nicegui/elements/leaflet.js

@@ -4,6 +4,7 @@ export default {
   template: "<div></div>",
   props: {
     map_options: Object,
+    draw_control: Object,
     resource_path: String,
   },
   async mounted() {
@@ -12,7 +13,7 @@ export default {
       loadResource(window.path_prefix + `${this.resource_path}/leaflet/leaflet.css`),
       loadResource(window.path_prefix + `${this.resource_path}/leaflet/leaflet.js`),
     ]);
-    if (this.map_options.drawControl) {
+    if (this.draw_control) {
       await Promise.all([
         loadResource(window.path_prefix + `${this.resource_path}/leaflet-draw/leaflet.draw.css`),
         loadResource(window.path_prefix + `${this.resource_path}/leaflet-draw/leaflet.draw.js`),
@@ -68,7 +69,7 @@ export default {
         });
       });
     }
-    if (this.map_options.drawControl) {
+    if (this.draw_control) {
       for (const key in L.Draw.Event) {
         const type = L.Draw.Event[key];
         this.map.on(type, (e) => {
@@ -80,10 +81,13 @@ export default {
           });
         });
       }
-    }
-    if (this.map_options.drawControl) {
-      var drawnItems = new L.FeatureGroup();
+      const drawnItems = new L.FeatureGroup();
       this.map.addLayer(drawnItems);
+      const drawControl = new L.Control.Draw({
+        edit: { featureGroup: drawnItems },
+        ...this.draw_control,
+      });
+      this.map.addControl(drawControl);
     }
     const connectInterval = setInterval(async () => {
       if (window.socket.id === undefined) return;

+ 5 - 5
nicegui/elements/leaflet.py

@@ -1,5 +1,5 @@
 from pathlib import Path
-from typing import Any, List, Tuple, cast
+from typing import Any, List, Tuple, Union, cast
 
 from typing_extensions import Self
 
@@ -23,7 +23,7 @@ class Leaflet(Element, component='leaflet.js'):
                  location: Tuple[float, float] = (0, 0),
                  zoom: int = 13,
                  *,
-                 show_draw_toolbar: bool = False,
+                 draw_control: Union[bool, dict] = False,
                  ) -> None:
         """Leaflet map
 
@@ -31,7 +31,7 @@ class Leaflet(Element, component='leaflet.js'):
 
         :param location: initial location of the map
         :param zoom: initial zoom level of the map
-        :param show_draw_toolbar: whether to show the draw control toolbar
+        :param draw_control: whether to show the draw toolbar (default: False)
         """
         super().__init__()
         self.add_resource(Path(__file__).parent / 'lib' / 'leaflet')
@@ -41,7 +41,7 @@ class Leaflet(Element, component='leaflet.js'):
 
         self.set_location(location)
         self.set_zoom(zoom)
-        self.show_draw_toolbar = show_draw_toolbar
+        self.draw_control = draw_control
 
         self.is_initialized = False
         self.on('init', self._handle_init)
@@ -89,8 +89,8 @@ class Leaflet(Element, component='leaflet.js'):
                 'lng': self.location[1],
             },
             'zoom': self.zoom,
-            'drawControl': self.show_draw_toolbar,
         }
+        self._props['draw_control'] = self.draw_control
         super().update()
 
     def _handle_delete(self) -> None:

+ 30 - 0
website/documentation/content/leaflet_documentation.py

@@ -66,4 +66,34 @@ def vector_layers() -> None:
                     args=[[51.505, -0.09], {'color': 'red', 'radius': 300}])
 
 
+@doc.demo('Draw on Map', '''
+    You can enable a toolbar to draw on the map.
+    The `draw_control` can be used to configure the toolbar.
+    This demo adds markers and polygons by clicking on the map.
+''')
+def draw_on_map() -> None:
+    from nicegui import events
+
+    def handle_draw(e: events.GenericEventArguments):
+        if e.args['layerType'] == 'marker':
+            m.marker(location=(e.args['layer']['_latlng']['lat'],
+                               e.args['layer']['_latlng']['lng']))
+        if e.args['layerType'] == 'polygon':
+            m.generic_layer(name='polygon', args=[e.args['layer']['_latlngs']])
+
+    draw_control = {
+        'draw': {
+            'polygon': True,
+            'marker': True,
+            'circle': False,
+            'rectangle': False,
+            'polyline': False,
+            'circlemarker': False,
+        },
+        'edit': False,
+    }
+    m = ui.leaflet(location=(51.505, -0.09), zoom=13, draw_control=draw_control)
+    m.on('draw:created', handle_draw)
+
+
 doc.reference(ui.leaflet)