Skip to content

Map

maplibre.Map

Bases: object

Map

Parameters:

Name Type Description Default
map_options MapOptions

Map options.

MapOptions()
**kwargs

Keyword arguments that are appended to the MapOptions object.

{}

Examples:

>>> from maplibre.map import Map, MapOptions
>>> map_options = MapOptions(center=(9.5, 51.31667), zoom=8)
>>> map = Map(map_options)
>>> dict(map)
{'mapOptions': {'center': (9.5, 51.31667), 'style': 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json', 'zoom': 8}, 'calls': []}
Source code in maplibre/map.py
class Map(object):
    """Map

    Args:
        map_options (MapOptions): Map options.
        **kwargs: Keyword arguments that are appended to the `MapOptions` object.

    Examples:
        >>> from maplibre.map import Map, MapOptions

        >>> map_options = MapOptions(center=(9.5, 51.31667), zoom=8)
        >>> map = Map(map_options)
        >>> dict(map)
        {'mapOptions': {'center': (9.5, 51.31667), 'style': 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json', 'zoom': 8}, 'calls': []}
    """

    MESSAGE = "not implemented yet"

    def __init__(self, map_options: MapOptions = MapOptions(), **kwargs):
        self.map_options = map_options.to_dict() | kwargs
        self._message_queue = []

    def __iter__(self):
        for k, v in self.to_dict().items():
            yield k, v

    def to_dict(self) -> dict:
        return {"mapOptions": self.map_options, "calls": self._message_queue}

    """
    @property
    def sources(self) -> list:
        return [item["data"] for item in self._calls if item["name"] == "addSource"]

    @property
    def layers(self) -> list:
        return [item["data"] for item in self._calls if item["name"] == "addLayer"]
    """

    # TODO: Rename to add_map_call
    def add_call_(self, func_name: str, params: list) -> None:
        self._message_queue.append(
            {"name": "applyFunc", "data": {"funcName": func_name, "params": params}}
        )

    def add_call(self, method_name: str, *args) -> None:
        """Add a method call that is executed on the map instance

        Args:
            method_name (str): The name of the map method to be executed.
            *args (any): The arguments to be passed to the map method.
        """
        # TODO: Pass as dict? {"name": method_name, "args": args}
        call = [method_name, args]
        self._message_queue.append(call)

    def add_control(
        self,
        control: Control,
        position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,
    ) -> None:
        """Add a control to the map

        Args:
            control (Control): The control to be added to the map.
            position (str | ControlPosition): The position of the control.
        """
        self.add_call(
            "addControl",
            control.type,
            control.to_dict(),
            ControlPosition(position).value,
        )

    def add_source(self, id: str, source: [Source | dict]) -> None:
        """Add a source to the map"""
        if isinstance(source, Source):
            source = source.to_dict()

        self.add_call("addSource", id, source)

    def add_layer(self, layer: [Layer | dict]) -> None:
        """Add a layer to the map

        Args:
            layer (Layer | dict): The Layer to be added to the map.
        """
        if isinstance(layer, Layer):
            layer = layer.to_dict()

        self.add_call("addLayer", layer)

    def add_marker(self, marker: Marker) -> None:
        """Add a marker to the map

        Args:
            marker (Marker): The marker to be added to the map.
        """
        self.add_call("addMarker", marker.to_dict())

    def add_popup(self, layer_id: str, prop: str = None, template: str = None) -> None:
        """Add a popup to the map

        Args:
            layer_id (str): The layer to which the popup is added.
            prop (str): The property of the source to be displayed. If `None`, all properties are displayed.
            template (str): A mustache template. If supplied, `prop` is ignored.
        """
        self.add_call("addPopup", layer_id, prop, template)

    def add_tooltip(
        self, layer_id: str, prop: str = None, template: str = None
    ) -> None:
        """Add a tooltip to the map

        Args:
            layer_id (str): The layer to which the tooltip is added.
            prop (str): The property of the source to be displayed. If `None`, all properties are displayed.
            template (str): A mustache template. If supplied, `prop` is ignored.

        Examples:
            >>> map = Map()
            >>> # ...
            >>> map.add_tooltip("test-layer", template="Name: {{ name }}")
        """
        self.add_call("addTooltip", layer_id, prop, template)

    def set_filter(self, layer_id: str, filter_: list):
        """Update the filter of a layer

        Args:
            layer_id (str): The name of the layer to be updated.
            filter_ (list): The filter expression that is applied to the source of the layer.
        """
        self.add_call("setFilter", layer_id, filter_)

    def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:
        """Update the paint property of a layer

        Args:
            layer_id (str): The name of the layer to be updated.
            prop (str): The name of the paint property to be updated.
            value (any): The new value of the paint property.
        """
        self.add_call("setPaintProperty", layer_id, prop, value)

    def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:
        """Update a layout property of a layer

        Args:
            layer_id (str): The name of the layer to be updated.
            prop (str): The name of the layout property to be updated.
            value (any): The new value of the layout property.
        """
        self.add_call("setLayoutProperty", layer_id, prop, value)

    def set_data(self, source_id: str, data: dict) -> None:
        """Update the data of a GeoJSON source

        Args:
            source_id (str): The name of the source to be updated.
            data (dict): The data of the source.
        """
        self.add_call("setSourceData", source_id, data)

    def set_visibility(self, layer_id: str, visible: bool = True) -> None:
        """Update the visibility of a layer

        Args:
            layer_id (str): The name of the layer to be updated.
            visible (bool): Whether the layer is visible or not.
        """
        value = "visible" if visible else "none"
        self.add_call("setLayoutProperty", layer_id, "visibility", value)

    def to_html(self, **kwargs) -> str:
        """Render to html

        Args:
            **kwargs (Any): Additional keyword arguments that are passed to the template.
                Currently, `style` is the only supported keyword argument.

        Examples:
            >>> from maplibre import Map

            >>> map = Map()
            >>> with open("/tmp/map.html", "w") as f:
            ...     f.write(map.to_html(style="height: 800px;") # doctest: +SKIP
        """
        js_lib = read_internal_file("srcjs", "index.js")
        js_snippet = Template(js_template).render(data=json.dumps(self.to_dict()))
        output = Template(html_template).render(
            js="\n".join([js_lib, js_snippet]), **kwargs
        )
        return output

add_call(method_name, *args)

Add a method call that is executed on the map instance

Parameters:

Name Type Description Default
method_name str

The name of the map method to be executed.

required
*args any

The arguments to be passed to the map method.

()
Source code in maplibre/map.py
def add_call(self, method_name: str, *args) -> None:
    """Add a method call that is executed on the map instance

    Args:
        method_name (str): The name of the map method to be executed.
        *args (any): The arguments to be passed to the map method.
    """
    # TODO: Pass as dict? {"name": method_name, "args": args}
    call = [method_name, args]
    self._message_queue.append(call)

add_control(control, position=ControlPosition.TOP_RIGHT)

Add a control to the map

Parameters:

Name Type Description Default
control Control

The control to be added to the map.

required
position str | ControlPosition

The position of the control.

TOP_RIGHT
Source code in maplibre/map.py
def add_control(
    self,
    control: Control,
    position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,
) -> None:
    """Add a control to the map

    Args:
        control (Control): The control to be added to the map.
        position (str | ControlPosition): The position of the control.
    """
    self.add_call(
        "addControl",
        control.type,
        control.to_dict(),
        ControlPosition(position).value,
    )

add_layer(layer)

Add a layer to the map

Parameters:

Name Type Description Default
layer Layer | dict

The Layer to be added to the map.

required
Source code in maplibre/map.py
def add_layer(self, layer: [Layer | dict]) -> None:
    """Add a layer to the map

    Args:
        layer (Layer | dict): The Layer to be added to the map.
    """
    if isinstance(layer, Layer):
        layer = layer.to_dict()

    self.add_call("addLayer", layer)

add_marker(marker)

Add a marker to the map

Parameters:

Name Type Description Default
marker Marker

The marker to be added to the map.

required
Source code in maplibre/map.py
def add_marker(self, marker: Marker) -> None:
    """Add a marker to the map

    Args:
        marker (Marker): The marker to be added to the map.
    """
    self.add_call("addMarker", marker.to_dict())

add_popup(layer_id, prop=None, template=None)

Add a popup to the map

Parameters:

Name Type Description Default
layer_id str

The layer to which the popup is added.

required
prop str

The property of the source to be displayed. If None, all properties are displayed.

None
template str

A mustache template. If supplied, prop is ignored.

None
Source code in maplibre/map.py
def add_popup(self, layer_id: str, prop: str = None, template: str = None) -> None:
    """Add a popup to the map

    Args:
        layer_id (str): The layer to which the popup is added.
        prop (str): The property of the source to be displayed. If `None`, all properties are displayed.
        template (str): A mustache template. If supplied, `prop` is ignored.
    """
    self.add_call("addPopup", layer_id, prop, template)

add_source(id, source)

Add a source to the map

Source code in maplibre/map.py
def add_source(self, id: str, source: [Source | dict]) -> None:
    """Add a source to the map"""
    if isinstance(source, Source):
        source = source.to_dict()

    self.add_call("addSource", id, source)

add_tooltip(layer_id, prop=None, template=None)

Add a tooltip to the map

Parameters:

Name Type Description Default
layer_id str

The layer to which the tooltip is added.

required
prop str

The property of the source to be displayed. If None, all properties are displayed.

None
template str

A mustache template. If supplied, prop is ignored.

None

Examples:

>>> map = Map()
>>> # ...
>>> map.add_tooltip("test-layer", template="Name: {{ name }}")
Source code in maplibre/map.py
def add_tooltip(
    self, layer_id: str, prop: str = None, template: str = None
) -> None:
    """Add a tooltip to the map

    Args:
        layer_id (str): The layer to which the tooltip is added.
        prop (str): The property of the source to be displayed. If `None`, all properties are displayed.
        template (str): A mustache template. If supplied, `prop` is ignored.

    Examples:
        >>> map = Map()
        >>> # ...
        >>> map.add_tooltip("test-layer", template="Name: {{ name }}")
    """
    self.add_call("addTooltip", layer_id, prop, template)

set_data(source_id, data)

Update the data of a GeoJSON source

Parameters:

Name Type Description Default
source_id str

The name of the source to be updated.

required
data dict

The data of the source.

required
Source code in maplibre/map.py
def set_data(self, source_id: str, data: dict) -> None:
    """Update the data of a GeoJSON source

    Args:
        source_id (str): The name of the source to be updated.
        data (dict): The data of the source.
    """
    self.add_call("setSourceData", source_id, data)

set_filter(layer_id, filter_)

Update the filter of a layer

Parameters:

Name Type Description Default
layer_id str

The name of the layer to be updated.

required
filter_ list

The filter expression that is applied to the source of the layer.

required
Source code in maplibre/map.py
def set_filter(self, layer_id: str, filter_: list):
    """Update the filter of a layer

    Args:
        layer_id (str): The name of the layer to be updated.
        filter_ (list): The filter expression that is applied to the source of the layer.
    """
    self.add_call("setFilter", layer_id, filter_)

set_layout_property(layer_id, prop, value)

Update a layout property of a layer

Parameters:

Name Type Description Default
layer_id str

The name of the layer to be updated.

required
prop str

The name of the layout property to be updated.

required
value any

The new value of the layout property.

required
Source code in maplibre/map.py
def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:
    """Update a layout property of a layer

    Args:
        layer_id (str): The name of the layer to be updated.
        prop (str): The name of the layout property to be updated.
        value (any): The new value of the layout property.
    """
    self.add_call("setLayoutProperty", layer_id, prop, value)

set_paint_property(layer_id, prop, value)

Update the paint property of a layer

Parameters:

Name Type Description Default
layer_id str

The name of the layer to be updated.

required
prop str

The name of the paint property to be updated.

required
value any

The new value of the paint property.

required
Source code in maplibre/map.py
def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:
    """Update the paint property of a layer

    Args:
        layer_id (str): The name of the layer to be updated.
        prop (str): The name of the paint property to be updated.
        value (any): The new value of the paint property.
    """
    self.add_call("setPaintProperty", layer_id, prop, value)

set_visibility(layer_id, visible=True)

Update the visibility of a layer

Parameters:

Name Type Description Default
layer_id str

The name of the layer to be updated.

required
visible bool

Whether the layer is visible or not.

True
Source code in maplibre/map.py
def set_visibility(self, layer_id: str, visible: bool = True) -> None:
    """Update the visibility of a layer

    Args:
        layer_id (str): The name of the layer to be updated.
        visible (bool): Whether the layer is visible or not.
    """
    value = "visible" if visible else "none"
    self.add_call("setLayoutProperty", layer_id, "visibility", value)

to_html(**kwargs)

Render to html

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments that are passed to the template. Currently, style is the only supported keyword argument.

{}

Examples:

>>> from maplibre import Map
>>> map = Map()
>>> with open("/tmp/map.html", "w") as f:
...     f.write(map.to_html(style="height: 800px;")
Source code in maplibre/map.py
def to_html(self, **kwargs) -> str:
    """Render to html

    Args:
        **kwargs (Any): Additional keyword arguments that are passed to the template.
            Currently, `style` is the only supported keyword argument.

    Examples:
        >>> from maplibre import Map

        >>> map = Map()
        >>> with open("/tmp/map.html", "w") as f:
        ...     f.write(map.to_html(style="height: 800px;") # doctest: +SKIP
    """
    js_lib = read_internal_file("srcjs", "index.js")
    js_snippet = Template(js_template).render(data=json.dumps(self.to_dict()))
    output = Template(html_template).render(
        js="\n".join([js_lib, js_snippet]), **kwargs
    )
    return output

maplibre.MapOptions

Bases: BaseModel

Map options

Note

See MapOptions for more details.

Source code in maplibre/map.py
class MapOptions(BaseModel):
    """Map options

    Note:
        See [MapOptions](https://maplibre.org/maplibre-gl-js/docs/API/types/MapOptions/) for more details.
    """

    model_config = ConfigDict(
        validate_assignment=True, extra="forbid", use_enum_values=False
    )
    antialias: bool = None
    attribution_control: bool = Field(None, serialization_alias="attributionControl")
    bearing: int = None
    bearing_snap: int = Field(None, serialization_alias="bearingSnap")
    bounds: tuple = None
    box_zoom: bool = Field(None, serialization_alias="boxZoom")
    center: tuple = None
    click_tolerance: int = Field(None, serialization_alias="clickTolerance")
    custom_attribution: bool = Field(None, serialization_alias="customAttribution")
    double_click_zoom: bool = Field(None, serialization_alias="doubleClickZoom")
    fade_duration: int = Field(None, serialization_alias="fadeDuration")
    fit_bounds_options: dict = Field(None, serialization_alias="fitBoundsOptions")
    hash: Union[bool, str] = None
    interactive: bool = None
    keyword: bool = None
    max_bounds: tuple = Field(None, serialization_alias="maxBounds")
    max_pitch: int = Field(None, serialization_alias="maxPitch")
    max_zoom: int = Field(None, serialization_alias="maxZoom")
    min_pitch: int = Field(None, serialization_alias="minPitch")
    min_zoom: int = Field(None, serialization_alias="minZoom")
    pitch: int = None
    scroll_zoom: bool = Field(None, serialization_alias="scrollZoom")
    style: Union[str, Carto, dict] = construct_carto_basemap_url(Carto.DARK_MATTER)
    zoom: int = None

    @field_validator("style")
    def validate_style(cls, v):
        if isinstance(v, Carto):
            return construct_carto_basemap_url(v)

        return v

maplibre.MapContext

Bases: Map

MapContext

Use this class to update a Map instance in a Shiny app. Must be used inside an async function.

See maplibre.Map for available methods.

Parameters:

Name Type Description Default
id string

The id of the map to be updated.

required
session Session

A Shiny session. If None, the active session is used.

None
Source code in maplibre/mapcontext.py
class MapContext(Map):
    """MapContext

    Use this class to update a `Map` instance in a Shiny app.
    Must be used inside an async function.

    See `maplibre.Map` for available methods.

    Args:
        id (string): The id of the map to be updated.
        session (Session): A Shiny session.
            If `None`, the active session is used.
    """

    def __init__(self, id: str, session: Session = None) -> None:
        self.id = id
        self._session = require_active_session(session)
        self.map_options = {}
        self._message_queue = []

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.render()

    async def render(self):
        await self._session.send_custom_message(
            f"pymaplibregl-{self.id}", {"id": self.id, "calls": self._message_queue}
        )

maplibre.ipywidget.MapWidget

Bases: AnyWidget, Map

MapWidget

Use this class to display and update maps in Jupyter Notebooks.

See maplibre.Map for available methods.

Examples:

>>> from maplibre import MapOptions
>>> from maplibre.ipywidget import MapWidget as Map
>>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))
>>> m
Source code in maplibre/ipywidget.py
class MapWidget(AnyWidget, Map):
    """MapWidget

    Use this class to display and update maps in Jupyter Notebooks.

    See `maplibre.Map` for available methods.

    Examples:
        >>> from maplibre import MapOptions
        >>> from maplibre.ipywidget import MapWidget as Map
        >>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))
        >>> m # doctest: +SKIP
    """

    _esm = join(Path(__file__).parent, "srcjs", "ipywidget.js")
    _css = join(Path(__file__).parent, "srcjs", "maplibre-gl.css")
    _use_message_queue = False
    _rendered = traitlets.Bool(False, config=True).tag(sync=True)
    map_options = traitlets.Dict().tag(sync=True)
    calls = traitlets.List().tag(sync=True)
    height = traitlets.Union([traitlets.Int(), traitlets.Unicode()]).tag(sync=True)
    lng_lat = traitlets.Dict().tag(sync=True)

    def __init__(self, map_options=MapOptions(), **kwargs) -> None:
        self.calls = []
        AnyWidget.__init__(self, **kwargs)
        Map.__init__(self, map_options, **kwargs)

    @traitlets.default("height")
    def _default_height(self):
        return "400px"

    @traitlets.validate("height")
    def _validate_height(self, proposal):
        height = proposal["value"]
        if isinstance(height, int):
            return f"{height}px"

        return height

    @traitlets.observe("_rendered")
    def _on_rendered(self, change):
        self.send({"calls": self._message_queue, "msg": "init"})
        self._message_queue = []

    def use_message_queue(self, value: bool = True) -> None:
        self._use_message_queue = value

    def add_call(self, method_name: str, *args) -> None:
        call = [method_name, args]
        if not self._rendered:
            if not self._use_message_queue:
                self.calls = self.calls + [call]
                return

            self._message_queue.append(call)
            return

        self.send({"calls": [call], "msg": "custom call"})