# ui.leaflet | NiceGUI

[Button: icon:menu]

[](/)

[Installation](/#installation)

[Features](/#features)

[Demos](/#demos)

[Documentation](/documentation)

[Examples](/examples)

[Why?](/#why)

[Button]

[Button]

[](https://github.com/zauberzeug/nicegui/)

[Button: icon:more_vert]

# ui.*leaflet*

## Leaflet map

This element is a wrapper around the `Leaflet <https://leafletjs.com/>`_ JavaScript library.

:center: initial center location of the map (latitude/longitude, default: (0.0, 0.0))
:zoom: initial zoom level of the map (default: 13)
:draw_control: whether to show the draw toolbar (default: False)
:options: additional options passed to the Leaflet map (default: {})
:hide_drawn_items: whether to hide drawn items on the map (default: False, *added in version 2.0.0*)
:additional_resources: additional resources like CSS or JS files to load (default: None, *added in version 2.11.0*)

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(51.505, -0.09))
ui.label().bind_text_from(m, 'center', lambda center: f'Center: {center[0]:.3f}, {center[1]:.3f}')
ui.label().bind_text_from(m, 'zoom', lambda zoom: f'Zoom: {zoom}')

with ui.grid(columns=2):
    ui.button('London', on_click=lambda: m.set_center((51.505, -0.090)))
    ui.button('Berlin', on_click=lambda: m.set_center((52.520, 13.405)))
    ui.button(icon='zoom_in', on_click=lambda: m.set_zoom(m.zoom + 1))
    ui.button(icon='zoom_out', on_click=lambda: m.set_zoom(m.zoom - 1))

ui.run()
````

## Changing the Map Style

The default map style is OpenStreetMap.
You can find more map styles at <https://leaflet-extras.github.io/leaflet-providers/preview/>.
Each call to `tile_layer` stacks upon the previous ones.
So if you want to change the map style, you have to remove the default one first.

*Updated in version 2.12.0: Both WMTS and WMS map services are supported.*

main.py

[Button]

````python
from nicegui import ui

ui.label('Web Map Tile Service')
map1 = ui.leaflet(center=(51.505, -0.090), zoom=3)
map1.clear_layers()
map1.tile_layer(
    url_template=r'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
    options={
        'maxZoom': 17,
        'attribution':
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="https://viewfinderpanoramas.org/">SRTM</a> | '
            'Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
    },
)

ui.label('Web Map Service')
map2 = ui.leaflet(center=(51.505, -0.090), zoom=3)
map2.clear_layers()
map2.wms_layer(
    url_template='http://ows.mundialis.de/services/service?',
    options={
        'layers': 'TOPO-WMS,OSM-Overlay-WMS'
    },
)

ui.run()
````

## Add Markers on Click

You can add markers to the map with `marker`.
The `center` argument is a tuple of latitude and longitude.
This demo adds markers by clicking on the map.
Note that the "map-click" event refers to the click event of the map object,
while the "click" event refers to the click event of the container div.

main.py

[Button]

````python
from nicegui import events, ui

m = ui.leaflet(center=(51.505, -0.09))

def handle_click(e: events.GenericEventArguments):
    lat = e.args['latlng']['lat']
    lng = e.args['latlng']['lng']
    m.marker(latlng=(lat, lng))
m.on('map-click', handle_click)

ui.run()
````

## Move Markers

You can move markers with the `move` method.

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(51.505, -0.09))
marker = m.marker(latlng=m.center)
ui.button('Move marker', on_click=lambda: marker.move(51.51, -0.09))

ui.run()
````

## Image Overlays

Leaflet supports [image overlays](https://leafletjs.com/reference.html#imageoverlay).
You can add an image overlay with the `image_overlay` method.

*Added in version 2.17.0*

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(52.5165, 13.4047), zoom=13)
m.image_overlay(
    url='https://images.squarespace-cdn.com/content/v1/5b3e152e620b8559f2edcf7d/1613743643304-Y7SLCT43BQ2N8C2QA3JN/1660+berlin+%28Custom%29.jpg',
    bounds=[[52.5088, 13.3877], [52.5242, 13.4218]],
    options={'opacity': 0.8},
)

ui.run()
````

## Video Overlays

Leaflet supports [video overlays](https://leafletjs.com/reference.html#videooverlay).
You can add a video overlay with the `video_overlay` method.

*Added in version 2.17.0*

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(23.0, -115.0), zoom=3)
m.video_overlay(
    url='https://www.mapbox.com/bites/00188/patricia_nasa.webm',
    bounds=[[32, -130], [13, -100]],
    options={'opacity': 0.8, 'autoplay': True, 'playsInline': True},
)

ui.run()
````

## Vector Layers

Leaflet supports a set of [vector layers](https://leafletjs.com/reference.html#:~:text=VideoOverlay-,Vector%20Layers,-Path) like circle, polygon etc.
These can be added with the `generic_layer` method.
We are happy to review any pull requests to add more specific layers to simplify usage.

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
m.generic_layer(name='circle', args=[m.center, {'color': 'red', 'radius': 300}])

ui.run()
````

## Disable Pan and Zoom

There are [several options to configure the map in Leaflet](https://leafletjs.com/reference.html#map).
This demo disables the pan and zoom controls.

main.py

[Button]

````python
from nicegui import ui

options = {
    'zoomControl': False,
    'scrollWheelZoom': False,
    'doubleClickZoom': False,
    'boxZoom': False,
    'keyboard': False,
    'dragging': False,
}
ui.leaflet(center=(51.505, -0.09), options=options)

ui.run()
````

## 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.
By setting "edit" and "remove" to `True` (the default), you can enable editing and deleting drawn shapes.

main.py

[Button]

````python
from nicegui import events, ui

def handle_draw(e: events.GenericEventArguments):
    layer_type = e.args['layerType']
    coords = e.args['layer'].get('_latlng') or e.args['layer'].get('_latlngs')
    ui.notify(f'Drawn a {layer_type} at {coords}')

draw_control = {
    'draw': {
        'polygon': True,
        'marker': True,
        'circle': True,
        'rectangle': True,
        'polyline': True,
        'circlemarker': True,
    },
    'edit': {
        'edit': True,
        'remove': True,
    },
}
m = ui.leaflet(center=(51.505, -0.09), draw_control=draw_control)
m.classes('h-96')
m.on('draw:created', handle_draw)
m.on('draw:edited', lambda: ui.notify('Edit completed'))
m.on('draw:deleted', lambda: ui.notify('Delete completed'))

ui.run()
````

## Draw with Custom Options

You can draw shapes with custom options like stroke color and weight.
To hide the default rendering of drawn items, set `hide_drawn_items` to `True`.

main.py

[Button]

````python
from nicegui import events, ui

def handle_draw(e: events.GenericEventArguments):
    options = {'color': 'red', 'weight': 1}
    m.generic_layer(name='polygon', args=[e.args['layer']['_latlngs'], options])

draw_control = {
    'draw': {
        'polygon': True,
        'marker': False,
        'circle': False,
        'rectangle': False,
        'polyline': False,
        'circlemarker': False,
    },
    'edit': {
        'edit': False,
        'remove': False,
    },
}
m = ui.leaflet(center=(51.5, 0), draw_control=draw_control, hide_drawn_items=True)
m.on('draw:created', handle_draw)

ui.run()
````

## Run Map Methods

You can run methods of the Leaflet map object with `run_map_method`.
This demo shows how to fit the map to the whole world.

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
ui.button('Fit world', on_click=lambda: m.run_map_method('fitWorld'))

ui.run()
````

## Run Layer Methods

You can run methods of the Leaflet layer objects with `run_layer_method`.
This demo shows how to change the opacity of a marker or change its icon.

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet(center=(51.505, -0.09)).classes('h-32')
marker = m.marker(latlng=m.center)
ui.button('Hide', on_click=lambda: marker.run_method('setOpacity', 0.3))
ui.button('Show', on_click=lambda: marker.run_method('setOpacity', 1.0))

icon = 'L.icon({iconUrl: "https://leafletjs.com/examples/custom-icons/leaf-green.png"})'
ui.button('Change icon', on_click=lambda: marker.run_method(':setIcon', icon))

ui.run()
````

## Wait for Initialization

You can wait for the map to be initialized with the `initialized` method.
This is necessary when you want to run methods like fitting the bounds of the map right after the map is created.

main.py

[Button]

````python
from nicegui import ui

@ui.page('/')
async def page():
    m = ui.leaflet(zoom=5)
    central_park = m.generic_layer(name='polygon', args=[[
        (40.767809, -73.981249),
        (40.800273, -73.958291),
        (40.797011, -73.949683),
        (40.764704, -73.973741),
    ]])
    await m.initialized()
    bounds = await central_park.run_method('getBounds')
    m.run_map_method('fitBounds', [[bounds['_southWest'], bounds['_northEast']]])

ui.run()
````

## Leaflet Plugins

You can add plugins to the map by passing the URLs of JS and CSS files to the `additional_resources` parameter.
This demo shows how to add the [Leaflet.RotatedMarker](https://github.com/bbecquet/Leaflet.RotatedMarker) plugin.
It allows you to rotate markers by a given `rotationAngle`.

*Added in version 2.11.0*

main.py

[Button]

````python
from nicegui import ui

m = ui.leaflet((51.51, -0.09), additional_resources=[
    'https://unpkg.com/leaflet-rotatedmarker@0.2.0/leaflet.rotatedMarker.js',
])
m.marker(latlng=(51.51, -0.091), options={'rotationAngle': -30})
m.marker(latlng=(51.51, -0.090), options={'rotationAngle': 30})

ui.run()
````

## Reference

## Initializer

:center: initial center location of the map (latitude/longitude, default: (0.0, 0.0))
:zoom: initial zoom level of the map (default: 13)
:draw_control: whether to show the draw toolbar (default: False)
:options: additional options passed to the Leaflet map (default: {})
:hide_drawn_items: whether to hide drawn items on the map (default: False, *added in version 2.0.0*)
:additional_resources: additional resources like CSS or JS files to load (default: None, *added in version 2.11.0*)

## Properties

**`center`**`: BindableProperty`

**`zoom`**`: BindableProperty`

**Inherited properties**

**`classes`**`: 'Classes[Self]'`

The classes of the element.

**`client`**`: 'Client'`

The client this element belongs to.

**`html_id`**`: 'str'`

The ID of the element in the HTML DOM.

*Added in version 2.16.0*

**`is_deleted`**`: 'bool'`

Whether the element has been deleted.

**`is_ignoring_events`**`: bool`

Return whether the element is currently ignoring events.

**`parent_slot`**`: 'Slot | None' (settable)`

The parent slot of the element.

**`props`**`: 'Props[Self]'`

The props of the element.

**`style`**`: 'Style[Self]'`

The style of the element.

**`visible`**`: BindableProperty`

## Methods

**`clear_layers`**`() -> None`

Remove all layers from the map.

**`initialized`**`() -> None`

Wait until the map is initialized.

**`remove_layer`**`(layer: nicegui.elements.leaflet.leaflet_layer.Layer) -> None`

Remove a layer from the map.

**`run_layer_method`**`(layer_id: str, name: str, *args, timeout: float = 1) -> nicegui.awaitable_response.AwaitableResponse`

Run a method of a Leaflet layer.

If the function is awaited, the result of the method call is returned.
Otherwise, the method is executed without waiting for a response.

:param layer_id: ID of the layer
:param name: name of the method (a prefix ":" indicates that the arguments are JavaScript expressions)
:param args: arguments to pass to the method
:param timeout: timeout in seconds (default: 1 second)

:return: AwaitableResponse that can be awaited to get the result of the method call

**`run_map_method`**`(name: str, *args, timeout: float = 1) -> nicegui.awaitable_response.AwaitableResponse`

Run a method of the Leaflet map instance.

Refer to the `Leaflet documentation <https://leafletjs.com/reference.html#map-methods-for-modifying-map-state>`_ for a list of methods.

If the function is awaited, the result of the method call is returned.
Otherwise, the method is executed without waiting for a response.

:param name: name of the method (a prefix ":" indicates that the arguments are JavaScript expressions)
:param args: arguments to pass to the method
:param timeout: timeout in seconds (default: 1 second)

:return: AwaitableResponse that can be awaited to get the result of the method call

**`run_method`**`(name: str, *args: Any, timeout: float = 1) -> nicegui.awaitable_response.AwaitableResponse`

Run a method on the client side.

If the function is awaited, the result of the method call is returned.
Otherwise, the method is executed without waiting for a response.

:param name: name of the method
:param args: arguments to pass to the method
:param timeout: maximum time to wait for a response (default: 1 second)

**`set_center`**`(center: tuple[float, float]) -> Self`

Set the center location of the map.

**`set_zoom`**`(zoom: int) -> Self`

Set the zoom level of the map.

**Inherited methods**

**`add_dynamic_resource`**`(name: str, function: Callable) -> None`

Add a dynamic resource to the element which returns the result of a function.

:param name: name of the resource
:param function: function that returns the resource response

**`add_resource`**`(path: str | Path) -> None`

Add a resource to the element.

:param path: path to the resource (e.g. folder with CSS and JavaScript files)

**`add_slot`**`(name: str, template: str | None = None) -> Slot`

Add a slot to the element.

NiceGUI is using the slot concept from Vue:
Elements can have multiple slots, each possibly with a number of children.
Most elements only have one slot, e.g. a `ui.card` (QCard) only has a default slot.
But more complex elements like `ui.table` (QTable) can have more slots like "header", "body" and so on.
If you nest NiceGUI elements via with `ui.row(): ...` you place new elements inside of the row's default slot.
But if you use with `table.add_slot(...): ...`, you enter a different slot.

The slot stack helps NiceGUI to keep track of which slot is currently used for new elements.
The `parent` field holds a reference to its element.
Whenever an element is entered via a `with` expression, its default slot is automatically entered as well.

:param name: name of the slot
:param template: Vue template of the slot
:return: the slot

**`ancestors`**`(include_self: bool = False) -> Iterator[Element]`

Iterate over the ancestors of the element.

:param include_self: whether to include the element itself in the iteration

**`bind_visibility`**`(target_object: Any, target_name: str | tuple[str, ...] = 'visible', forward: collections.abc.Callable[[Any], Any] | None = None, backward: collections.abc.Callable[[Any], Any] | None = None, value: Any = None, strict: bool | None = None) -> Self`

Bind the visibility of this element to the target object's target_name property.

The binding works both ways, from this element to the target and from the target to this element.
The update happens immediately and whenever a value changes.
The backward binding takes precedence for the initial synchronization.
The ``target_name`` parameter also accepts a tuple of strings for nested keys (*since version 3.10.0*).

:param target_object: The object to bind to.
:param target_name: The name of the property to bind to.
:param forward: A function to apply to the value before applying it to the target (default: identity).
:param backward: A function to apply to the value before applying it to this element (default: identity).
:param value: If specified, the element will be visible only when the target value is equal to this value.
:param strict: Whether to check (and raise) if the target object has the specified property (default: None,
    performs a check if the object is not a dictionary, *added in version 3.0.0*).

**`bind_visibility_from`**`(target_object: Any, target_name: str | tuple[str, ...] = 'visible', backward: collections.abc.Callable[[Any], Any] | None = None, value: Any = None, strict: bool | None = None) -> Self`

Bind the visibility of this element from the target object's target_name property.

The binding works one way only, from the target to this element.
The update happens immediately and whenever a value changes.
The ``target_name`` parameter also accepts a tuple of strings for nested keys (*since version 3.10.0*).

:param target_object: The object to bind from.
:param target_name: The name of the property to bind from.
:param backward: A function to apply to the value before applying it to this element (default: identity).
:param value: If specified, the element will be visible only when the target value is equal to this value.
:param strict: Whether to check (and raise) if the target object has the specified property (default: None,
    performs a check if the object is not a dictionary, *added in version 3.0.0*).

**`bind_visibility_to`**`(target_object: Any, target_name: str | tuple[str, ...] = 'visible', forward: collections.abc.Callable[[Any], Any] | None = None, strict: bool | None = None) -> Self`

Bind the visibility of this element to the target object's target_name property.

The binding works one way only, from this element to the target.
The update happens immediately and whenever a value changes.
The ``target_name`` parameter also accepts a tuple of strings for nested keys (*since version 3.10.0*).

:param target_object: The object to bind to.
:param target_name: The name of the property to bind to.
:param forward: A function to apply to the value before applying it to the target (default: identity).
:param strict: Whether to check (and raise) if the target object has the specified property (default: None,
    performs a check if the object is not a dictionary, *added in version 3.0.0*).

**`clear`**`() -> Self`

Remove all child elements.

`@classmethod`<br />**`default_classes`**`(add: str | None = None, remove: str | None = None, toggle: str | None = None, replace: str | None = None) -> type[Self]`

Apply, remove, toggle, or replace default HTML classes.

This allows modifying the look of the element or its layout using `Tailwind <https://tailwindcss.com/>`_ or `Quasar <https://quasar.dev/>`_ classes.

Removing or replacing classes can be helpful if predefined classes are not desired.
All elements of this class will share these HTML classes.
These must be defined before element instantiation.

:param add: whitespace-delimited string of classes
:param remove: whitespace-delimited string of classes to remove from the element
:param toggle: whitespace-delimited string of classes to toggle (*added in version 2.7.0*)
:param replace: whitespace-delimited string of classes to use instead of existing ones

`@classmethod`<br />**`default_props`**`(add: str | None = None, remove: str | None = None) -> type[Self]`

Add or remove default props.

This allows modifying the look of the element or its layout using `Quasar <https://quasar.dev/>`_ props.
Since props are simply applied as HTML attributes, they can be used with any HTML element.
All elements of this class will share these props.
These must be defined before element instantiation.

Boolean properties are assumed ``True`` if no value is specified.

:param add: whitespace-delimited list of either boolean values or key=value pair to add
:param remove: whitespace-delimited list of property keys to remove

`@classmethod`<br />**`default_style`**`(add: str | None = None, remove: str | None = None, replace: str | None = None) -> type[Self]`

Apply, remove, or replace default CSS definitions.

Removing or replacing styles can be helpful if the predefined style is not desired.
All elements of this class will share these CSS definitions.
These must be defined before element instantiation.

:param add: semicolon-separated list of styles to add to the element
:param remove: semicolon-separated list of styles to remove from the element
:param replace: semicolon-separated list of styles to use instead of existing ones

**`delete`**`() -> None`

Delete the element and all its children.

**`descendants`**`(include_self: bool = False) -> Iterator[Element]`

Iterate over the descendants of the element.

:param include_self: whether to include the element itself in the iteration

**`get_computed_prop`**`(prop_name: str, timeout: float = 1) -> AwaitableResponse`

Return a computed property.

This function should be awaited so that the computed property is properly returned.

:param prop_name: name of the computed prop
:param timeout: maximum time to wait for a response (default: 1 second)

**`mark`**`(*markers: str) -> Self`

Replace markers of the element.

Markers are used to identify elements for querying with `ElementFilter </documentation/element_filter>`_
which is heavily used in testing
but can also be used to reduce the number of global variables or passing around dependencies.

:param markers: list of strings or single string with whitespace-delimited markers; replaces existing markers

**`move`**`(target_container: Element | None = None, target_index: int = -1, target_slot: str | None = None) -> Self`

Move the element to another container.

:param target_container: container to move the element to (default: the parent container)
:param target_index: index within the target slot (default: append to the end)
:param target_slot: slot within the target container (default: default slot)

**`on`**`(type: str, handler: events.Handler[events.GenericEventArguments] | None = None, args: None | Sequence[str] | Sequence[Sequence[str] | None] = None, throttle: float = 0.0, leading_events: bool = True, trailing_events: bool = True, js_handler: str = '(...args) => emit(...args)') -> Self`

Subscribe to an event.

The event handler can be a Python function, a JavaScript function or a combination of both:

- If you want to handle the event on the server with all (serializable) event arguments,
  use a Python ``handler``.
- If you want to handle the event on the client side without emitting anything to the server,
  use ``js_handler`` with a JavaScript function handling the event.
- If you want to handle the event on the server with a subset or transformed version of the event arguments,
  use ``js_handler`` with a JavaScript function emitting the transformed arguments using ``emit()``, and
  use a Python ``handler`` to handle these arguments on the server side.
  The ``js_handler`` can also decide to selectively emit arguments to the server,
  in which case the Python ``handler`` will not always be called.

Note that the arguments ``throttle``, ``leading_events``, and ``trailing_events`` are only relevant
when emitting events to the server.

*Updated in version 2.18.0: Both handlers can be specified at the same time.*

:param type: name of the event (e.g. "click", "mousedown", or "update:model-value")
:param handler: callback that is called upon occurrence of the event
:param args: arguments included in the event message sent to the event handler (default: ``None`` meaning all)
:param throttle: minimum time (in seconds) between event occurrences (default: 0.0)
:param leading_events: whether to trigger the event handler immediately upon the first event occurrence (default: ``True``)
:param trailing_events: whether to trigger the event handler after the last event occurrence (default: ``True``)
:param js_handler: JavaScript function that is handling the event on the client (default: "(...args) => emit(...args)")

**`remove`**`(element: Element | int) -> None`

Remove a child element.

:param element: either the element instance or its ID

**`set_visibility`**`(visible: bool) -> Self`

Set the visibility of this element.

:param visible: Whether the element should be visible.

**`tooltip`**`(text: str) -> Self`

Add a tooltip to the element.

:param text: text of the tooltip

**`update`**`() -> None`

Update the element on the client side.

## Inheritance

- `Element`
- `Visibility`

**Nice**GUI

The Python UI framework that shows up in your browser.

[](https://github.com/zauberzeug/nicegui/)

[](https://discord.gg/TEpFeAaF4f)

[](https://www.reddit.com/r/nicegui/)

Resources

[Documentation](/documentation)

[Examples](/examples)

[LLM reference](/llms.txt)

[GitHub](https://github.com/zauberzeug/nicegui/)

[PyPI](https://pypi.org/project/nicegui/)

Community

[Discussions](https://github.com/zauberzeug/nicegui/discussions)

[Discord](https://discord.gg/TEpFeAaF4f)

[Reddit](https://www.reddit.com/r/nicegui/)

[Contributing](https://github.com/zauberzeug/nicegui/blob/main/CONTRIBUTING.md)

[Sponsors](https://github.com/sponsors/zauberzeug)

Legal

[Imprint](/imprint_privacy#imprint)

[Privacy](/imprint_privacy#privacy)

Made with NiceGUI by [Zauberzeug](https://zauberzeug.com)

© 2026 [Zauberzeug GmbH](https://zauberzeug.com)