瀏覽代碼

update map example

Falko Schindler 2 年之前
父節點
當前提交
7c4f83dea3
共有 2 個文件被更改,包括 25 次插入34 次删除
  1. 14 27
      examples/map/leaflet.py
  2. 11 7
      examples/map/main.py

+ 14 - 27
examples/map/leaflet.py

@@ -1,37 +1,26 @@
 import logging
-from typing import Dict, Optional, Tuple, Union
+from typing import Tuple
 
 from nicegui import ui
-from nicegui.events import ValueChangeEventArguments
 
 
 class map(ui.card):
 
-    def __init__(self):
+    def __init__(self) -> None:
         super().__init__()
-        self.classes('osm-map').style('width:100%;height:300px;transition:opacity 1s;opacity:0.1')
+        self.classes('osm-map').style('width:100%;height:300px')
         self.add_leaflet_js()
 
-    async def set_location(self, location: Union[Optional[Tuple[float, float]], Dict[str, Tuple[float, float]], ValueChangeEventArguments]):
+    async def set_location(self, location: Tuple[float, float]) -> None:
+        print(location, flush=True)
         try:
-            if isinstance(location, ValueChangeEventArguments):
-                location = location.value
-            if isinstance(location, dict):
-                location = location.get('location', location.get('value', None))
-            if not isinstance(location, tuple) or len(location) != 2 or not all(
-                    isinstance(x, float) or isinstance(x, int) for x in location):
-                self.style('opacity: 0.1;')
-                logging.warning(f'Invalid location: {location}')
-                return
-            self.style('opacity: 1;')
             await ui.run_javascript(f'''
-                target = L.latLng("{location[0]}", "{location[1]}")
-                map.setView(target, 9);
-                if (marker != undefined) map.removeLayer(marker);
-                marker = L.marker(target);
-                marker.addTo(map);
-                0 // return something so we do net get a js error
-            ''')
+                window.target = L.latLng("{location[0]}", "{location[1]}");
+                window.map.setView(target, 9);
+                if (window.marker != undefined) window.map.removeLayer(window.marker);
+                window.marker = L.marker(target);
+                window.marker.addTo(window.map);
+            ''', respond=False)
         except:
             logging.exception(f'could not update {location}')
 
@@ -56,18 +45,16 @@ class map(ui.card):
 
                     observer.observe(document.body, {
                         childList: true,
-                        subtree: true
+                        subtree: true,
                     });
                 });
             }
-            var marker;
-            var map;
             document.addEventListener("DOMContentLoaded", function() {
                 waitForElm('.osm-map').then((container) => {
-                    map = L.map(container);
+                    window.map = L.map(container);
                     L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                         attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
-                    }).addTo(map);                    
+                    }).addTo(window.map);
                 });
             });
         </script>

+ 11 - 7
examples/map/main.py

@@ -1,12 +1,12 @@
 #!/usr/bin/env python3
-from nicegui import ui
+import leaflet  # this module wraps the JavaScript lib leafletjs.com into an easy-to-use NiceGUI element
 
-# this module wraps the JavaScript lib leafletjs.com into an easy-to-use NiceGUI element
-import leaflet
+from nicegui import Client, ui
+from nicegui.events import ValueChangeEventArguments
 
 
 @ui.page('/')
-def main_page():
+async def main_page(client: Client):
     map = leaflet.map()
     locations = {
         (52.5200, 13.4049): 'Berlin',
@@ -14,10 +14,14 @@ def main_page():
         (39.9042, 116.4074): 'Beijing',
         (35.6895, 139.6917): 'Tokyo',
     }
-    selection = ui.select(locations, on_change=map.set_location).style('width: 10em')
-    yield  # all code below is executed after page is ready
+
+    async def handle_location_change(e: ValueChangeEventArguments) -> None:
+        with e.client:
+            await map.set_location(e.value)
+    selection = ui.select(locations, on_change=handle_location_change).style('width: 10em')
+    await client.handshake()  # all code below is executed after client is connected
     default_location = next(iter(locations))
-    # this will trigger the map.set_location event; which is js and must be run after page is ready
+    # this will trigger the map.set_location event; which is js and must be run after client has connected
     selection.set_value(default_location)