Skip to content

Map

openlayers.Map

Bases: object

Initialize a new Map instance

Parameters:

Name Type Description Default
view View

The initial view state of the map

View()
layers list[LayerT | LayerLike | dict]

Layers initially added to the map

None
controls list[ControlT | dict]

Controls initially added to the map

None
Source code in openlayers/map.py
class Map(object):
    """Initialize a new `Map` instance

    Args:
        view (View): The initial view state of the map
        layers (list[LayerT | LayerLike | dict]): Layers initially added to the map
        controls (list[ControlT | dict]): Controls initially added to the map
    """

    def __init__(
        self,
        view: View | dict = View(),
        layers: list[LayerT | LayerLike | dict] = None,
        controls: list[ControlT | dict] = None,
    ):
        self._initial_view_state = view.to_dict(exclude="type", exclude_none=True)
        self.calls = []
        if layers is None:
            layers = [TileLayer(id="osm", source=OSM())]

        self.options = MapOptions(
            view=view, layers=layers, controls=controls
        ).model_dump()

    @property
    def initial_view_state(self):
        return self._initial_view_state

    # 'apply_call_to_map'
    def add_call(self, method_name: str, *args: Any) -> None:
        call = dict(method=method_name, args=args)
        self.calls.append(call)

    # 'apply_call_to_layer'
    def add_layer_call(self, layer_id: str, method_name: str, *args: Any):
        layer_call = dict(method=method_name, args=args)
        self.add_call("applyCallToLayer", layer_id, layer_call)

    def add_view_call(self, method_name: str, *args: Any) -> None:
        view_call = dict(method=method_name, args=args)
        self.add_call("applyCallToView", view_call)

    def fit_bounds(self, bounds: tuple[float, float, float, float]) -> None:
        self.add_call("fitBounds", bounds)

    def set_view(self, view: View) -> None:
        """Set the view state of the map

        Args:
            view (View): The view state of the map
        """
        self.add_call("setView", view.model_dump())

    def set_view_from_source(self, layer_id: str) -> None:
        self.add_call("setViewFromSource", layer_id)

    def set_zoom(self, zoom_level: float | int) -> None:
        """Set the zoom level of the view

        Args:
            zoom_level (float | int): The zoom level
        """
        self.add_view_call("setZoom", zoom_level)

    def set_center(self, lon: float = 0, lat: float = 0) -> None:
        """Set the center of the view

        Args:
            lon (float): The center's longitude
            lat (float): The center's latitude
        """
        self.add_view_call("setCenter", (lon, lat))

    def add_layer(self, layer: LayerT | LayerLike | dict) -> None:
        """Add a layer to the map

        Args:
            layer (LayerT | LayerLike | dict): The layer to be added
        """
        if isinstance(layer, LayerLike):
            layer = layer.model

        if isinstance(layer, LayerT):
            layer = layer.model_dump()

        self.add_call("addLayer", layer)

    def remove_layer(self, layer_id: str) -> None:
        """Remove a layer from the map

        Args:
            layer_id (str): The ID of the layer to be removed
        """
        self.add_call("removeLayer", layer_id)

    def add_control(self, control: ControlT | dict) -> None:
        """Add a control to the map

        Args:
            control (ControlT | dict): The control to be added
        """
        if isinstance(control, ControlT):
            control = control.model_dump()

        self.add_call("addControl", control)

    def remove_control(self, control_id: str) -> None:
        """Remove a control from the map

        Args:
            control_id (str): The ID of the control to be removed
        """
        self.add_call("removeControl", control_id)

    def add_default_tooltip(self) -> None:
        """Add a default tooltip to the map

        It renders all feature properties
        and is activated for all layers of the map.
        """
        self.add_tooltip()

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

        Args:
            template (str): A mustache template string.
                If `None`, a default tooltip is added to the map
        """
        self.add_call("addTooltip", template)

    def add_select_interaction(self) -> None:
        """Add `Select-Features` interaction to the map

        Note:
            Currently, highlighting selected features is not supported
            for layers of type `WebGLVectorLayer`.
        """
        self.add_call("addSelectFeatures")

    def add_drag_and_drop_interaction(
        self,
        formats: list[FormatT] = [GeoJSON(), TopoJSON(), GPX(), KML()],
        style: FlatStyle | dict = None,
    ) -> None:
        """Add a drag and drop interaction to the map"""
        formats = [f.model_dump() for f in formats]
        if isinstance(style, FlatStyle):
            style = style.model_dump()

        return self.add_call("addDragAndDropVectorLayers", formats, style)

    def add_click_interaction(self) -> None:
        """Add a click interaction to map"""
        self.add_call("addClickInteraction")

    def add_modify_interaction(self, layer_id) -> None:
        """Add a modify interaction to the map

        Modify features of a vector layer.

        Note:
            Layers of type `WebGLVectorLayer` are not supported.

        Args:
            layer_id (str): The ID of the layer you want to modify
        """
        return self.add_call("addModifyInteraction", layer_id)

    def set_opacity(self, layer_id: str, opacity: float = 1) -> None:
        """Set the opacity of a layer

        Args:
            layer_id (str): The ID of the layer
            opacity (float): The opacity of the layer. A value between 0 and 1
        """
        self.add_layer_call(layer_id, "setOpacity", opacity)

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

        Args:
            layer_id (str): The ID of the layer
            visible (bool): Whether the layer is visible or not
        """
        self.add_layer_call(layer_id, "setVisible", visible)

    def set_style(self, layer_id: str, style: FlatStyle | dict) -> None:
        """Set the style of a layer

        Args:
            layer_id (str): The ID of the layer
            style (FlatStyle | dict): The style of the layer
        """
        if isinstance(style, FlatStyle):
            style = style.model_dump()

        self.add_layer_call(layer_id, "setStyle", style)

    def set_source(self, layer_id: str, source: SourceT | dict) -> None:
        """Set the source of a layer

        Args:
            layer_id {str}: The ID of the layer
            source (SourceT | dict): The source of the layer
        """
        if isinstance(source, SourceT):
            source = source.model_dump()

        self.add_call("setSource", layer_id, source)

    def to_html(self, **kwargs) -> str:
        """Render map to HTML"""
        data = self.options | dict(calls=self.calls)
        return HTMLTemplate().render(data=data, **kwargs)

    def save(self, path: Path | str = None, preview: bool = True, **kwargs) -> str:
        """Save map as an HTML document

        Args:
            path (Path | str): The Path to the output file. If `None`, a temporary file is created
            preview (bool): Whether the file should be opened in your default browser after saving
        """
        path = write_file(content=self.to_html(**kwargs), path=path)
        if preview:
            webbrowser.open(path)

        return path

add_click_interaction()

Add a click interaction to map

Source code in openlayers/map.py
def add_click_interaction(self) -> None:
    """Add a click interaction to map"""
    self.add_call("addClickInteraction")

add_control(control)

Add a control to the map

Parameters:

Name Type Description Default
control ControlT | dict

The control to be added

required
Source code in openlayers/map.py
def add_control(self, control: ControlT | dict) -> None:
    """Add a control to the map

    Args:
        control (ControlT | dict): The control to be added
    """
    if isinstance(control, ControlT):
        control = control.model_dump()

    self.add_call("addControl", control)

add_default_tooltip()

Add a default tooltip to the map

It renders all feature properties and is activated for all layers of the map.

Source code in openlayers/map.py
def add_default_tooltip(self) -> None:
    """Add a default tooltip to the map

    It renders all feature properties
    and is activated for all layers of the map.
    """
    self.add_tooltip()

add_drag_and_drop_interaction(formats=[GeoJSON(), TopoJSON(), GPX(), KML()], style=None)

Add a drag and drop interaction to the map

Source code in openlayers/map.py
def add_drag_and_drop_interaction(
    self,
    formats: list[FormatT] = [GeoJSON(), TopoJSON(), GPX(), KML()],
    style: FlatStyle | dict = None,
) -> None:
    """Add a drag and drop interaction to the map"""
    formats = [f.model_dump() for f in formats]
    if isinstance(style, FlatStyle):
        style = style.model_dump()

    return self.add_call("addDragAndDropVectorLayers", formats, style)

add_layer(layer)

Add a layer to the map

Parameters:

Name Type Description Default
layer LayerT | LayerLike | dict

The layer to be added

required
Source code in openlayers/map.py
def add_layer(self, layer: LayerT | LayerLike | dict) -> None:
    """Add a layer to the map

    Args:
        layer (LayerT | LayerLike | dict): The layer to be added
    """
    if isinstance(layer, LayerLike):
        layer = layer.model

    if isinstance(layer, LayerT):
        layer = layer.model_dump()

    self.add_call("addLayer", layer)

add_modify_interaction(layer_id)

Add a modify interaction to the map

Modify features of a vector layer.

Note

Layers of type WebGLVectorLayer are not supported.

Parameters:

Name Type Description Default
layer_id str

The ID of the layer you want to modify

required
Source code in openlayers/map.py
def add_modify_interaction(self, layer_id) -> None:
    """Add a modify interaction to the map

    Modify features of a vector layer.

    Note:
        Layers of type `WebGLVectorLayer` are not supported.

    Args:
        layer_id (str): The ID of the layer you want to modify
    """
    return self.add_call("addModifyInteraction", layer_id)

add_select_interaction()

Add Select-Features interaction to the map

Note

Currently, highlighting selected features is not supported for layers of type WebGLVectorLayer.

Source code in openlayers/map.py
def add_select_interaction(self) -> None:
    """Add `Select-Features` interaction to the map

    Note:
        Currently, highlighting selected features is not supported
        for layers of type `WebGLVectorLayer`.
    """
    self.add_call("addSelectFeatures")

add_tooltip(template=None)

Add a tooltip to the map

Parameters:

Name Type Description Default
template str

A mustache template string. If None, a default tooltip is added to the map

None
Source code in openlayers/map.py
def add_tooltip(self, template: str = None) -> None:
    """Add a tooltip to the map

    Args:
        template (str): A mustache template string.
            If `None`, a default tooltip is added to the map
    """
    self.add_call("addTooltip", template)

remove_control(control_id)

Remove a control from the map

Parameters:

Name Type Description Default
control_id str

The ID of the control to be removed

required
Source code in openlayers/map.py
def remove_control(self, control_id: str) -> None:
    """Remove a control from the map

    Args:
        control_id (str): The ID of the control to be removed
    """
    self.add_call("removeControl", control_id)

remove_layer(layer_id)

Remove a layer from the map

Parameters:

Name Type Description Default
layer_id str

The ID of the layer to be removed

required
Source code in openlayers/map.py
def remove_layer(self, layer_id: str) -> None:
    """Remove a layer from the map

    Args:
        layer_id (str): The ID of the layer to be removed
    """
    self.add_call("removeLayer", layer_id)

save(path=None, preview=True, **kwargs)

Save map as an HTML document

Parameters:

Name Type Description Default
path Path | str

The Path to the output file. If None, a temporary file is created

None
preview bool

Whether the file should be opened in your default browser after saving

True
Source code in openlayers/map.py
def save(self, path: Path | str = None, preview: bool = True, **kwargs) -> str:
    """Save map as an HTML document

    Args:
        path (Path | str): The Path to the output file. If `None`, a temporary file is created
        preview (bool): Whether the file should be opened in your default browser after saving
    """
    path = write_file(content=self.to_html(**kwargs), path=path)
    if preview:
        webbrowser.open(path)

    return path

set_center(lon=0, lat=0)

Set the center of the view

Parameters:

Name Type Description Default
lon float

The center's longitude

0
lat float

The center's latitude

0
Source code in openlayers/map.py
def set_center(self, lon: float = 0, lat: float = 0) -> None:
    """Set the center of the view

    Args:
        lon (float): The center's longitude
        lat (float): The center's latitude
    """
    self.add_view_call("setCenter", (lon, lat))

set_opacity(layer_id, opacity=1)

Set the opacity of a layer

Parameters:

Name Type Description Default
layer_id str

The ID of the layer

required
opacity float

The opacity of the layer. A value between 0 and 1

1
Source code in openlayers/map.py
def set_opacity(self, layer_id: str, opacity: float = 1) -> None:
    """Set the opacity of a layer

    Args:
        layer_id (str): The ID of the layer
        opacity (float): The opacity of the layer. A value between 0 and 1
    """
    self.add_layer_call(layer_id, "setOpacity", opacity)

set_source(layer_id, source)

Set the source of a layer

Parameters:

Name Type Description Default
layer_id {str}

The ID of the layer

required
source SourceT | dict

The source of the layer

required
Source code in openlayers/map.py
def set_source(self, layer_id: str, source: SourceT | dict) -> None:
    """Set the source of a layer

    Args:
        layer_id {str}: The ID of the layer
        source (SourceT | dict): The source of the layer
    """
    if isinstance(source, SourceT):
        source = source.model_dump()

    self.add_call("setSource", layer_id, source)

set_style(layer_id, style)

Set the style of a layer

Parameters:

Name Type Description Default
layer_id str

The ID of the layer

required
style FlatStyle | dict

The style of the layer

required
Source code in openlayers/map.py
def set_style(self, layer_id: str, style: FlatStyle | dict) -> None:
    """Set the style of a layer

    Args:
        layer_id (str): The ID of the layer
        style (FlatStyle | dict): The style of the layer
    """
    if isinstance(style, FlatStyle):
        style = style.model_dump()

    self.add_layer_call(layer_id, "setStyle", style)

set_view(view)

Set the view state of the map

Parameters:

Name Type Description Default
view View

The view state of the map

required
Source code in openlayers/map.py
def set_view(self, view: View) -> None:
    """Set the view state of the map

    Args:
        view (View): The view state of the map
    """
    self.add_call("setView", view.model_dump())

set_visibility(layer_id, visible=False)

Set the visibility of a layer

Parameters:

Name Type Description Default
layer_id str

The ID of the layer

required
visible bool

Whether the layer is visible or not

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

    Args:
        layer_id (str): The ID of the layer
        visible (bool): Whether the layer is visible or not
    """
    self.add_layer_call(layer_id, "setVisible", visible)

set_zoom(zoom_level)

Set the zoom level of the view

Parameters:

Name Type Description Default
zoom_level float | int

The zoom level

required
Source code in openlayers/map.py
def set_zoom(self, zoom_level: float | int) -> None:
    """Set the zoom level of the view

    Args:
        zoom_level (float | int): The zoom level
    """
    self.add_view_call("setZoom", zoom_level)

to_html(**kwargs)

Render map to HTML

Source code in openlayers/map.py
def to_html(self, **kwargs) -> str:
    """Render map to HTML"""
    data = self.options | dict(calls=self.calls)
    return HTMLTemplate().render(data=data, **kwargs)

openlayers.view.View

Bases: OLBaseModel

A View object represents a simple 2D view of the map

Note

See module-ol_View-View.html for details.

Attributes:

Name Type Description
center tuple[float, float]

The center for the view as (lon, lat) pair

zoom float | int

The Zoom level used to calculate the resolution for the view

projection str

The projection

rotation float | int

The rotation for the view in radians (positive rotation clockwise, 0 means north).

extent tuple[float, float, float, float] | list[float, float, float, float]

The extent that constrains the view, in other words, nothing outside of this extent can be visible on the map

min_zoom float | int

The minimum zoom level used to determine the resolution constraint

max_zoom float | int

The maximum zoom level used to determine the resolution constraint

Source code in openlayers/models/view.py
class View(OLBaseModel):
    """A View object represents a simple 2D view of the map

    Note:
        See [module-ol_View-View.html](https://openlayers.org/en/latest/apidoc/module-ol_View-View.html) for details.

    Attributes:
        center (tuple[float, float]): The center for the view as (lon, lat) pair
        zoom (float | int): The Zoom level used to calculate the resolution for the view
        projection (str): The projection
        rotation (float | int): The rotation for the view in radians (positive rotation clockwise, 0 means north).
        extent (tuple[float, float, float, float] | list[float, float, float, float]): The extent that constrains the view,
            in other words, nothing outside of this extent can be visible on the map
        min_zoom (float | int): The minimum zoom level used to determine the resolution constraint
        max_zoom (float | int): The maximum zoom level used to determine the resolution constraint
    """

    center: tuple[float, float] | None = (0, 0)
    zoom: float | int | None = 0
    projection: str | None = Projection.WEB_MERCATOR
    rotation: float | int | None = None
    extent: (
        tuple[float, float, float, float] | list[float, float, float, float] | None
    ) = None
    min_zoom: int | float | None = Field(None, serialization_alias="minZoom")
    max_zoom: int | float | None = Field(None, serialization_alias="maxZoom")

openlayers.MapWidget

Bases: Map, AnyWidget

Initialize a new MapWidgetinstance

Note

See Map for details.

Source code in openlayers/anywidget.py
class MapWidget(Map, AnyWidget):
    """Initialize a new `MapWidget`instance

    Note:
        See [Map](openlayers.Map) for details.
    """

    _esm = Path(__file__).parent / "js" / "openlayers.anywidget.js"
    _css = Path(__file__).parent / "js" / "openlayers.anywidget.css"

    height = traitlets.Unicode().tag(sync=True)
    calls = traitlets.List().tag(sync=True)
    created = traitlets.Bool().tag(sync=True)
    options = traitlets.Dict().tag(sync=True)
    clicked = traitlets.Dict().tag(sync=True)
    view_state = traitlets.Dict().tag(sync=True)
    metadata = traitlets.Dict().tag(sync=True)

    # TODO: Move to features as well
    # features_selected = traitlets.List().tag(sync=True)

    features = traitlets.Dict().tag(sync=True)

    def __init__(
        self,
        view: View = View(),
        layers: list[LayerT | dict] | None = None,
        controls: list[ControlT | dict] | None = None,
        height: str = "400px",
        **kwargs,
    ):
        self.created = False
        self.calls = []

        Map.__init__(self, view, layers, controls)
        AnyWidget.__init__(self, height=height, **kwargs)

    def add_call(self, method_name: str, *args: Any) -> None:
        call = dict(method=method_name, args=args)
        if self.created:
            return self.send(call)

        self.calls = self.calls + [call]