leaflet_documentation.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo(ui.leaflet)
  4. def main_demo() -> None:
  5. m = ui.leaflet(center=(51.505, -0.09))
  6. ui.label().bind_text_from(m, 'center', lambda center: f'Center: {center[0]:.3f}, {center[1]:.3f}')
  7. ui.label().bind_text_from(m, 'zoom', lambda zoom: f'Zoom: {zoom}')
  8. with ui.grid(columns=2):
  9. ui.button('London', on_click=lambda: m.set_center((51.505, -0.090)))
  10. ui.button('Berlin', on_click=lambda: m.set_center((52.520, 13.405)))
  11. ui.button(icon='zoom_in', on_click=lambda: m.set_zoom(m.zoom + 1))
  12. ui.button(icon='zoom_out', on_click=lambda: m.set_zoom(m.zoom - 1))
  13. @doc.demo('Changing the Map Style', '''
  14. The default map style is OpenStreetMap.
  15. You can find more map styles at <https://leaflet-extras.github.io/leaflet-providers/preview/>.
  16. Each call to `tile_layer` stacks upon the previous ones.
  17. So if you want to change the map style, you have to remove the default one first.
  18. *Updated in version 2.12.0: Both WMTS and WMS map services are supported.*
  19. ''')
  20. def map_style() -> None:
  21. ui.label('Web Map Tile Service')
  22. map1 = ui.leaflet(center=(51.505, -0.090), zoom=3)
  23. map1.clear_layers()
  24. map1.tile_layer(
  25. url_template=r'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
  26. options={
  27. 'maxZoom': 17,
  28. 'attribution':
  29. 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="https://viewfinderpanoramas.org/">SRTM</a> | '
  30. 'Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
  31. },
  32. )
  33. ui.label('Web Map Service')
  34. map2 = ui.leaflet(center=(51.505, -0.090), zoom=3)
  35. map2.clear_layers()
  36. map2.wms_layer(
  37. url_template='http://ows.mundialis.de/services/service?',
  38. options={
  39. 'layers': 'TOPO-WMS,OSM-Overlay-WMS'
  40. },
  41. )
  42. @doc.demo('Add Markers on Click', '''
  43. You can add markers to the map with `marker`.
  44. The `center` argument is a tuple of latitude and longitude.
  45. This demo adds markers by clicking on the map.
  46. Note that the "map-click" event refers to the click event of the map object,
  47. while the "click" event refers to the click event of the container div.
  48. ''')
  49. def markers() -> None:
  50. from nicegui import events
  51. m = ui.leaflet(center=(51.505, -0.09))
  52. def handle_click(e: events.GenericEventArguments):
  53. lat = e.args['latlng']['lat']
  54. lng = e.args['latlng']['lng']
  55. m.marker(latlng=(lat, lng))
  56. m.on('map-click', handle_click)
  57. @doc.demo('Move Markers', '''
  58. You can move markers with the `move` method.
  59. ''')
  60. def move_markers() -> None:
  61. m = ui.leaflet(center=(51.505, -0.09))
  62. marker = m.marker(latlng=m.center)
  63. ui.button('Move marker', on_click=lambda: marker.move(51.51, -0.09))
  64. @doc.demo('Vector Layers', '''
  65. Leaflet supports a set of [vector layers](https://leafletjs.com/reference.html#:~:text=VideoOverlay-,Vector%20Layers,-Path) like circle, polygon etc.
  66. These can be added with the `generic_layer` method.
  67. We are happy to review any pull requests to add more specific layers to simplify usage.
  68. ''')
  69. def vector_layers() -> None:
  70. m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
  71. m.generic_layer(name='circle', args=[m.center, {'color': 'red', 'radius': 300}])
  72. @doc.demo('Disable Pan and Zoom', '''
  73. There are [several options to configure the map in Leaflet](https://leafletjs.com/reference.html#map).
  74. This demo disables the pan and zoom controls.
  75. ''')
  76. def disable_pan_zoom() -> None:
  77. options = {
  78. 'zoomControl': False,
  79. 'scrollWheelZoom': False,
  80. 'doubleClickZoom': False,
  81. 'boxZoom': False,
  82. 'keyboard': False,
  83. 'dragging': False,
  84. }
  85. ui.leaflet(center=(51.505, -0.09), options=options)
  86. @doc.demo('Draw on Map', '''
  87. You can enable a toolbar to draw on the map.
  88. The `draw_control` can be used to configure the toolbar.
  89. This demo adds markers and polygons by clicking on the map.
  90. By setting "edit" and "remove" to `True` (the default), you can enable editing and deleting drawn shapes.
  91. ''')
  92. def draw_on_map() -> None:
  93. from nicegui import events
  94. def handle_draw(e: events.GenericEventArguments):
  95. layer_type = e.args['layerType']
  96. coords = e.args['layer'].get('_latlng') or e.args['layer'].get('_latlngs')
  97. ui.notify(f'Drawn a {layer_type} at {coords}')
  98. draw_control = {
  99. 'draw': {
  100. 'polygon': True,
  101. 'marker': True,
  102. 'circle': True,
  103. 'rectangle': True,
  104. 'polyline': True,
  105. 'circlemarker': True,
  106. },
  107. 'edit': {
  108. 'edit': True,
  109. 'remove': True,
  110. },
  111. }
  112. m = ui.leaflet(center=(51.505, -0.09), draw_control=draw_control)
  113. m.classes('h-96')
  114. m.on('draw:created', handle_draw)
  115. m.on('draw:edited', lambda: ui.notify('Edit completed'))
  116. m.on('draw:deleted', lambda: ui.notify('Delete completed'))
  117. @doc.demo('Draw with Custom Options', '''
  118. You can draw shapes with custom options like stroke color and weight.
  119. To hide the default rendering of drawn items, set `hide_drawn_items` to `True`.
  120. ''')
  121. def draw_custom_options():
  122. from nicegui import events
  123. def handle_draw(e: events.GenericEventArguments):
  124. options = {'color': 'red', 'weight': 1}
  125. m.generic_layer(name='polygon', args=[e.args['layer']['_latlngs'], options])
  126. draw_control = {
  127. 'draw': {
  128. 'polygon': True,
  129. 'marker': False,
  130. 'circle': False,
  131. 'rectangle': False,
  132. 'polyline': False,
  133. 'circlemarker': False,
  134. },
  135. 'edit': {
  136. 'edit': False,
  137. 'remove': False,
  138. },
  139. }
  140. m = ui.leaflet(center=(51.5, 0), draw_control=draw_control, hide_drawn_items=True)
  141. m.on('draw:created', handle_draw)
  142. @doc.demo('Run Map Methods', '''
  143. You can run methods of the Leaflet map object with `run_map_method`.
  144. This demo shows how to fit the map to the whole world.
  145. ''')
  146. def run_map_methods() -> None:
  147. m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
  148. ui.button('Fit world', on_click=lambda: m.run_map_method('fitWorld'))
  149. @doc.demo('Run Layer Methods', '''
  150. You can run methods of the Leaflet layer objects with `run_layer_method`.
  151. This demo shows how to change the opacity of a marker or change its icon.
  152. ''')
  153. def run_layer_methods() -> None:
  154. m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
  155. marker = m.marker(latlng=m.center)
  156. ui.button('Hide', on_click=lambda: marker.run_method('setOpacity', 0.3))
  157. ui.button('Show', on_click=lambda: marker.run_method('setOpacity', 1.0))
  158. icon = 'L.icon({iconUrl: "https://leafletjs.com/examples/custom-icons/leaf-green.png"})'
  159. ui.button('Change icon', on_click=lambda: marker.run_method(':setIcon', icon))
  160. @doc.demo('Wait for Initialization', '''
  161. You can wait for the map to be initialized with the `initialized` method.
  162. This is necessary when you want to run methods like fitting the bounds of the map right after the map is created.
  163. ''')
  164. async def wait_for_init() -> None:
  165. # @ui.page('/')
  166. async def page():
  167. m = ui.leaflet(zoom=5)
  168. central_park = m.generic_layer(name='polygon', args=[[
  169. (40.767809, -73.981249),
  170. (40.800273, -73.958291),
  171. (40.797011, -73.949683),
  172. (40.764704, -73.973741),
  173. ]])
  174. await m.initialized()
  175. bounds = await central_park.run_method('getBounds')
  176. m.run_map_method('fitBounds', [[bounds['_southWest'], bounds['_northEast']]])
  177. ui.timer(0, page, once=True) # HIDE
  178. @doc.demo('Leaflet Plugins', '''
  179. You can add plugins to the map by passing the URLs of JS and CSS files to the `additional_resources` parameter.
  180. This demo shows how to add the [Leaflet.RotatedMarker](https://github.com/bbecquet/Leaflet.RotatedMarker) plugin.
  181. It allows you to rotate markers by a given `rotationAngle`.
  182. *Added in version 2.11.0*
  183. ''')
  184. def leaflet_plugins() -> None:
  185. m = ui.leaflet((51.51, -0.09), additional_resources=[
  186. 'https://unpkg.com/leaflet-rotatedmarker@0.2.0/leaflet.rotatedMarker.js',
  187. ])
  188. m.marker(latlng=(51.51, -0.091), options={'rotationAngle': -30})
  189. m.marker(latlng=(51.51, -0.090), options={'rotationAngle': 30})
  190. doc.reference(ui.leaflet)