classInfoBoxControl(Control):
+"""InfoBox control
+
+ Attributes:
+ content (str): Content (HTML or plain text) to be displayed in the info box.
+ css_text (str): Optional inline style declaration of the control.
+ """
+
+content:str
+css_text:str=Field(None,serialization_alias="cssText")
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ maplibre.controls.LayerSwitcherControl
+
+
+
+
+
+
+
+ Bases: Control
+
+
+
Layer switcher control
+
+
+
+
Attributes:
+
+
+
+
Name
+
Type
+
Description
+
+
+
+
+
layer_ids
+
+ list
+
+
+
+
A list of layer ids to be shown in the layer switcher control.
classLayerSwitcherControl(Control):
+"""Layer switcher control
+
+ Attributes:
+ layer_ids (list): A list of layer ids to be shown in the layer switcher control.
+ theme (Literal["default", "simple"]): The theme of the layer switcher control.
+ css_text (str): Optional inline style declaration of the control.
+ """
+
+layer_ids:list=Field([],serialization_alias="layerIds")
+theme:Literal["default","simple"]="default"
+css_text:str=Field(None,serialization_alias="cssText")
+
>>> 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_lib=read_internal_file("srcjs","pywidget.js")js_snippet=Template(js_template).render(data=json.dumps(self.to_dict()))
-headers=[]
-
-# Deck.GL headers
-add_deckgl_headers="addDeckOverlay"in[
-item[0]foriteminself._message_queue
-]
-# TODO: Set version in constants
-deckgl_headers=(
-[
-'<script src="https://unpkg.com/deck.gl@9.0.16/dist.min.js"></script>',
-'<script src="https://unpkg.com/@deck.gl/json@9.0.16/dist.min.js"></script>',
-]
-ifadd_deckgl_headers
-else[]
-)
-
-# Mapbox Draw headers
-add_mapbox_draw_headers="addMapboxDraw"in[
-item[0]foriteminself._message_queue
-]
-# TODO: Set version in constants
-mapbox_draw_headers=(
-[
-# "<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.js'></script>",
-# "<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.css' type='text/css' />",
-"<script src='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.js'></script>",
-"<link rel='stylesheet' href='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.css' type='text/css' />",
-]
-ifadd_mapbox_draw_headers
-else[]
-)
-
-output=Template(html_template).render(
-js="\n".join([js_lib,js_snippet]),
-title=title,
-headers=headers+deckgl_headers+mapbox_draw_headers,
-**kwargs,
-)
-returnoutput
-
-# -------------------------
-# Plugins
-# -------------------------
-defadd_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
-"""Add Deck.GL layers to the layer stack
-
- Args:
- layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.
- tooltip (str | dict): Either a single mustache template string applied to all layers
- or a dictionary where keys are layer ids and values are mustache template strings.
- """
-self.add_call("addDeckOverlay",layers,tooltip)
-
-defset_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
-"""Update Deck.GL layers
-
- Args:
- layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.
- New layers will be added. Missing layers will be removed.
- tooltip (str | dict): Must be set to keep tooltip even if it did not change.
- """
-self.add_call("setDeckLayers",layers,tooltip)
-
-defadd_mapbox_draw(
-self,
-options:dict|MapboxDrawOptions=None,
-position:str|ControlPosition=ControlPosition.TOP_LEFT,
-geojson:dict=None,
-)->None:
-"""Add MapboxDraw controls to the map
-
- Note:
- See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)
- for available options.
-
- Args:
- options (dict | MapboxDrawOptions): MapboxDraw options.
- position (str | ControlPosition): The position of the MapboxDraw controls.
- geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
- """
-ifisinstance(options,MapboxDrawOptions):
-options=options.to_dict()
-
-self.add_call(
-"addMapboxDraw",optionsor{},ControlPosition(position).value,geojson
-)
+css=read_internal_file("srcjs","pywidget.css")
+headers=[f"<style>{css}</style>"]
+
+# Deck.GL headers
+add_deckgl_headers="addDeckOverlay"in[
+item[0]foriteminself._message_queue
+]
+# TODO: Set version in constants
+deckgl_headers=(
+[
+'<script src="https://unpkg.com/deck.gl@9.0.16/dist.min.js"></script>',
+'<script src="https://unpkg.com/@deck.gl/json@9.0.16/dist.min.js"></script>',
+]
+ifadd_deckgl_headers
+else[]
+)
+
+# Mapbox Draw headers
+add_mapbox_draw_headers="addMapboxDraw"in[
+item[0]foriteminself._message_queue
+]
+# TODO: Set version in constants
+mapbox_draw_headers=(
+[
+# "<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.js'></script>",
+# "<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.css' type='text/css' />",
+"<script src='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.js'></script>",
+"<link rel='stylesheet' href='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.css' type='text/css' />",
+]
+ifadd_mapbox_draw_headers
+else[]
+)
+
+output=Template(html_template).render(
+js="\n".join([js_lib,js_snippet]),
+title=title,
+headers=headers+deckgl_headers+mapbox_draw_headers,
+**kwargs,
+)
+returnoutput
+
+# -------------------------
+# Plugins
+# -------------------------
+defadd_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
+"""Add Deck.GL layers to the layer stack
+
+ Args:
+ layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.
+ tooltip (str | dict): Either a single mustache template string applied to all layers
+ or a dictionary where keys are layer ids and values are mustache template strings.
+ """
+self.add_call("addDeckOverlay",layers,tooltip)
+
+defset_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
+"""Update Deck.GL layers
+
+ Args:
+ layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.
+ New layers will be added. Missing layers will be removed.
+ tooltip (str | dict): Must be set to keep tooltip even if it did not change.
+ """
+self.add_call("setDeckLayers",layers,tooltip)
+
+defadd_mapbox_draw(
+self,
+options:dict|MapboxDrawOptions=None,
+position:str|ControlPosition=ControlPosition.TOP_LEFT,
+geojson:dict=None,
+)->None:
+"""Add MapboxDraw controls to the map
+
+ Note:
+ See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)
+ for available options.
+
+ Args:
+ options (dict | MapboxDrawOptions): MapboxDraw options.
+ position (str | ControlPosition): The position of the MapboxDraw controls.
+ geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
+ """
+ifisinstance(options,MapboxDrawOptions):
+options=options.to_dict()
+
+self.add_call(
+"addMapboxDraw",optionsor{},ControlPosition(position).value,geojson
+)
defadd_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
-"""Add Deck.GL layers to the layer stack
-
- Args:
- layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.
- tooltip (str | dict): Either a single mustache template string applied to all layers
- or a dictionary where keys are layer ids and values are mustache template strings.
- """
-self.add_call("addDeckOverlay",layers,tooltip)
+313
+314
defadd_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
+"""Add Deck.GL layers to the layer stack
+
+ Args:
+ layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.
+ tooltip (str | dict): Either a single mustache template string applied to all layers
+ or a dictionary where keys are layer ids and values are mustache template strings.
+ """
+self.add_call("addDeckOverlay",layers,tooltip)
defadd_mapbox_draw(
-self,
-options:dict|MapboxDrawOptions=None,
-position:str|ControlPosition=ControlPosition.TOP_LEFT,
-geojson:dict=None,
-)->None:
-"""Add MapboxDraw controls to the map
-
- Note:
- See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)
- for available options.
-
- Args:
- options (dict | MapboxDrawOptions): MapboxDraw options.
- position (str | ControlPosition): The position of the MapboxDraw controls.
- geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
- """
-ifisinstance(options,MapboxDrawOptions):
-options=options.to_dict()
-
-self.add_call(
-"addMapboxDraw",optionsor{},ControlPosition(position).value,geojson
-)
+347
+348
defadd_mapbox_draw(
+self,
+options:dict|MapboxDrawOptions=None,
+position:str|ControlPosition=ControlPosition.TOP_LEFT,
+geojson:dict=None,
+)->None:
+"""Add MapboxDraw controls to the map
+
+ Note:
+ See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)
+ for available options.
+
+ Args:
+ options (dict | MapboxDrawOptions): MapboxDraw options.
+ position (str | ControlPosition): The position of the MapboxDraw controls.
+ geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
+ """
+ifisinstance(options,MapboxDrawOptions):
+options=options.to_dict()
+
+self.add_call(
+"addMapboxDraw",optionsor{},ControlPosition(position).value,geojson
+)
defset_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
-"""Update Deck.GL layers
-
- Args:
- layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.
- New layers will be added. Missing layers will be removed.
- tooltip (str | dict): Must be set to keep tooltip even if it did not change.
- """
-self.add_call("setDeckLayers",layers,tooltip)
+323
+324
defset_deck_layers(self,layers:list[dict],tooltip:str|dict=None)->None:
+"""Update Deck.GL layers
+
+ Args:
+ layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.
+ New layers will be added. Missing layers will be removed.
+ tooltip (str | dict): Must be set to keep tooltip even if it did not change.
+ """
+self.add_call("setDeckLayers",layers,tooltip)
from maplibre.ipywidget import MapWidget as Map\n\nm = Map()\nm\n
"},{"location":"changelog/","title":"Changelog for MapLibre for Python","text":""},{"location":"changelog/#maplibre-v024","title":"maplibre v0.2.4","text":"
Add MapboxDraw plugin
Add Shiny input concerned to MapboxDraw:
<output_id>.draw_features_selected
Add interactive attributes to IpyWidget concerned to MapboxDraw:
Deck.GL layers can be added to the map with Map.add_deck_layers.
They are defined as a dictionary, where classes got the @@type prefix and getter props the @@= prefix. They are inserted into the layer stack of the maplibre context. Therefore, you can also pass a beforeId prop.
Here is an example corresponding to the Deck.GL GridLayer API Example:
MapLibre for Python provides the following reactive inputs:
map-on-click event: Sends the coordinates of the location that was clicked on. The name of the input event corresponds to the output id. For output_maplibregl(\"maplibre\") you need to listen to input.maplibre.
feature-on-click event: Sends the properties of the feature that was clicked on. The name of the \u00ecnput is made up of the output id + layer + layer id. For output_maplibregl(\"maplibre\") and a layer with id=test you need to listen to input.maplibre_layer_test.
def construct_basemap_style(\n name: str = \"nice-style\", sources: dict = {}, layers: list = []\n) -> dict:\n \"\"\"Construct a basemap style\n\n Args:\n name (str): The name of the basemap style.\n sources (dict): The sources to be used for the basemap style.\n layers (list): The layers to be used for the basemap style.\n \"\"\"\n layers = [\n layer.to_dict() if isinstance(layer, Layer) else layer for layer in layers\n ]\n return {\"name\": name, \"version\": 8, \"sources\": sources, \"layers\": layers}\n
"},{"location":"api/controls/","title":"Markers and controls","text":""},{"location":"api/controls/#maplibre.controls.Popup","title":"maplibre.controls.Popup","text":"
Bases: BaseModel
Popup
Attributes:
Name Type Description textstr
The Text of the popup.
optionsPopupOptions | dict
Popup options.
Source code in maplibre/controls.py
class Popup(BaseModel):\n \"\"\"Popup\n\n Attributes:\n text: The Text of the popup.\n options (PopupOptions | dict): Popup options.\n \"\"\"\n\n text: str\n options: Union[PopupOptions, dict] = {}\n
Required. The longitude and latitude of the marker.
popupPopup | dict
The Popup that is displayed when a user clicks on the marker.
optionsMarkerOptions | dict
Marker options.
Source code in maplibre/controls.py
class Marker(BaseModel):\n \"\"\"Marker\n\n Attributes:\n lng_lat (tuple |list): **Required.** The longitude and latitude of the marker.\n popup (Popup | dict): The Popup that is displayed when a user clicks on the marker.\n options (MarkerOptions | dict): Marker options.\n \"\"\"\n\n lng_lat: Union[tuple, list] = Field(None, serialization_alias=\"lngLat\")\n popup: Union[Popup, dict] = None\n options: Union[MarkerOptions, dict] = {}\n
class Layer(BaseModel):\n \"\"\"Layer properties\n\n Notes:\n See [layers](https://maplibre.org/maplibre-style-spec/layers/) for more details on the\n `paint` and `layout` properties of the layers.\n\n Attributes:\n id (str): **Required.** The unique ID of the layer. Defaults to `str(uuid4())`.\n type (str | LayerType): **Required.** The type of the layer.\n filter (list): The filter expression that is applied to the source of the layer.\n layout (dict): The layout properties of the layer.\n max_zoom (int): The maximum zoom level for the layer.\n min_zoom (int): The minimum zoom level for the layer.\n paint (dict): The paint properties of the layer.\n source (str | Source): The name (unique ID) of a source or a source object to be used for the layer.\n source_layer (str): The layer to use from a vector tile source.\n\n Examples:\n >>> from maplibre.layer import Layer, LayerType\n\n >>> layer = Layer(id=\"test-layer\", type=LayerType.CIRCLE, source=\"test-source\")\n \"\"\"\n\n id: str = Field(default_factory=lambda: str(uuid4()))\n type: LayerType\n filter: list = None\n layout: dict = None\n max_zoom: int = Field(None, serialization_alias=\"maxzoom\")\n metadata: dict = None\n min_zoom: int = Field(None, serialization_alias=\"minzoom\")\n paint: dict = None\n source: Union[str, Source, dict, None] = None\n source_layer: str = Field(None, serialization_alias=\"source-layer\")\n\n @field_validator(\"source\")\n def validate_source(cls, v):\n if isinstance(v, Source):\n return v.to_dict()\n\n return v\n\n @field_validator(\"paint\", \"layout\")\n def fix_paint(cls, v):\n if isinstance(v, dict):\n return fix_keys(v)\n\n return v\n
A Client-side hillshading visualization based on DEM data.
BACKGROUND \u2013
A background color or pattern.
Source code in maplibre/layer.py
class LayerType(Enum):\n \"\"\"Rendering type of layer\n\n Attributes:\n CIRCLE: A filled circle.\n FILL: A filled polygon with an optional stroked border.\n FILL_EXTRUSION: An extruded polygon.\n LINE: A stroked line.\n SYMBOL: An icon or a text label.\n RASTER: Raster map textures such as satellite imagery.\n HEATMAP: A heatmap.\n HILLSHADE: A Client-side hillshading visualization based on DEM data.\n BACKGROUND: A background color or pattern.\n \"\"\"\n\n CIRCLE = \"circle\"\n FILL = \"fill\"\n FILL_EXTRUSION = \"fill-extrusion\"\n LINE = \"line\"\n SYMBOL = \"symbol\"\n RASTER = \"raster\"\n HEATMAP = \"heatmap\"\n HILLSHADE = \"hillshade\"\n BACKGROUND = \"background\"\n
class Map(object):\n \"\"\"Map\n\n Args:\n map_options (MapOptions): Map options.\n **kwargs: Keyword arguments that are appended to the `MapOptions` object.\n\n Examples:\n >>> from maplibre.map import Map, MapOptions\n\n >>> map_options = MapOptions(center=(9.5, 51.31667), zoom=8)\n >>> map = Map(map_options)\n >>> dict(map)\n {'mapOptions': {'center': (9.5, 51.31667), 'style': 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json', 'zoom': 8}, 'calls': []}\n \"\"\"\n\n MESSAGE = \"not implemented yet\"\n\n def __init__(self, map_options: MapOptions = MapOptions(), **kwargs):\n self.map_options = map_options.to_dict() | kwargs\n self._message_queue = []\n\n def __iter__(self):\n for k, v in self.to_dict().items():\n yield k, v\n\n def to_dict(self) -> dict:\n return {\"mapOptions\": self.map_options, \"calls\": self._message_queue}\n\n \"\"\"\n @property\n def sources(self) -> list:\n return [item[\"data\"] for item in self._calls if item[\"name\"] == \"addSource\"]\n\n @property\n def layers(self) -> list:\n return [item[\"data\"] for item in self._calls if item[\"name\"] == \"addLayer\"]\n \"\"\"\n\n # TODO: Rename to add_map_call\n def add_call_(self, func_name: str, params: list) -> None:\n self._message_queue.append(\n {\"name\": \"applyFunc\", \"data\": {\"funcName\": func_name, \"params\": params}}\n )\n\n def add_call(self, method_name: str, *args) -> None:\n \"\"\"Add a method call that is executed on the map instance\n\n Args:\n method_name (str): The name of the map method to be executed.\n *args (any): The arguments to be passed to the map method.\n \"\"\"\n # TODO: Pass as dict? {\"name\": method_name, \"args\": args}\n call = [method_name, args]\n self._message_queue.append(call)\n\n def add_control(\n self,\n control: Control,\n position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,\n ) -> None:\n \"\"\"Add a control to the map\n\n Args:\n control (Control): The control to be added to the map.\n position (str | ControlPosition): The position of the control.\n \"\"\"\n self.add_call(\n \"addControl\",\n control.type,\n control.to_dict(),\n ControlPosition(position).value,\n )\n\n def add_source(self, id: str, source: [Source | dict]) -> None:\n \"\"\"Add a source to the map\n\n Args:\n id (str): The unique ID of the source.\n source (Source | dict): The source to be added to the map.\n \"\"\"\n if isinstance(source, Source):\n source = source.to_dict()\n\n self.add_call(\"addSource\", id, source)\n\n def add_layer(self, layer: [Layer | dict], before_id: str = None) -> None:\n \"\"\"Add a layer to the map\n\n Args:\n layer (Layer | dict): The Layer to be added to the map.\n before_id (str): The ID of an existing layer to insert the new layer before,\n resulting in the new layer appearing visually beneath the existing layer.\n If `None`, the new layer will appear above all other layers.\n \"\"\"\n if isinstance(layer, Layer):\n layer = layer.to_dict()\n\n self.add_call(\"addLayer\", layer, before_id)\n\n def add_marker(self, marker: Marker) -> None:\n \"\"\"Add a marker to the map\n\n Args:\n marker (Marker): The marker to be added to the map.\n \"\"\"\n self.add_call(\"addMarker\", marker.to_dict())\n\n def add_popup(self, layer_id: str, prop: str = None, template: str = None) -> None:\n \"\"\"Add a popup to the map\n\n Args:\n layer_id (str): The layer to which the popup is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n \"\"\"\n self.add_call(\"addPopup\", layer_id, prop, template)\n\n def add_tooltip(\n self, layer_id: str, prop: str = None, template: str = None\n ) -> None:\n \"\"\"Add a tooltip to the map\n\n Args:\n layer_id (str): The layer to which the tooltip is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n\n Examples:\n >>> map = Map()\n >>> # ...\n >>> map.add_tooltip(\"test-layer\", template=\"Name: {{ name }}\")\n \"\"\"\n self.add_call(\"addTooltip\", layer_id, prop, template)\n\n def set_filter(self, layer_id: str, filter_: list):\n \"\"\"Update the filter of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n filter_ (list): The filter expression that is applied to the source of the layer.\n \"\"\"\n self.add_call(\"setFilter\", layer_id, filter_)\n\n def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update the paint property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the paint property to be updated.\n value (any): The new value of the paint property.\n \"\"\"\n self.add_call(\"setPaintProperty\", layer_id, prop, value)\n\n def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update a layout property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the layout property to be updated.\n value (any): The new value of the layout property.\n \"\"\"\n self.add_call(\"setLayoutProperty\", layer_id, prop, value)\n\n def set_data(self, source_id: str, data: dict) -> None:\n \"\"\"Update the data of a GeoJSON source\n\n Args:\n source_id (str): The name of the source to be updated.\n data (dict): The data of the source.\n \"\"\"\n self.add_call(\"setSourceData\", source_id, data)\n\n def set_visibility(self, layer_id: str, visible: bool = True) -> None:\n \"\"\"Update the visibility of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n visible (bool): Whether the layer is visible or not.\n \"\"\"\n value = \"visible\" if visible else \"none\"\n self.add_call(\"setLayoutProperty\", layer_id, \"visibility\", value)\n\n def to_html(self, title: str = \"My Awesome Map\", **kwargs) -> str:\n \"\"\"Render to html\n\n Args:\n title (str): The Title of the HTML document.\n **kwargs (Any): Additional keyword arguments that are passed to the template.\n Currently, `style` is the only supported keyword argument.\n\n Examples:\n >>> from maplibre import Map\n\n >>> map = Map()\n >>> with open(\"/tmp/map.html\", \"w\") as f:\n ... f.write(map.to_html(style=\"height: 800px;\") # doctest: +SKIP\n \"\"\"\n js_lib = read_internal_file(\"srcjs\", \"index.js\")\n js_snippet = Template(js_template).render(data=json.dumps(self.to_dict()))\n headers = []\n\n # Deck.GL headers\n add_deckgl_headers = \"addDeckOverlay\" in [\n item[0] for item in self._message_queue\n ]\n # TODO: Set version in constants\n deckgl_headers = (\n [\n '<script src=\"https://unpkg.com/deck.gl@9.0.16/dist.min.js\"></script>',\n '<script src=\"https://unpkg.com/@deck.gl/json@9.0.16/dist.min.js\"></script>',\n ]\n if add_deckgl_headers\n else []\n )\n\n # Mapbox Draw headers\n add_mapbox_draw_headers = \"addMapboxDraw\" in [\n item[0] for item in self._message_queue\n ]\n # TODO: Set version in constants\n mapbox_draw_headers = (\n [\n # \"<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.js'></script>\",\n # \"<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.css' type='text/css' />\",\n \"<script src='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.js'></script>\",\n \"<link rel='stylesheet' href='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.css' type='text/css' />\",\n ]\n if add_mapbox_draw_headers\n else []\n )\n\n output = Template(html_template).render(\n js=\"\\n\".join([js_lib, js_snippet]),\n title=title,\n headers=headers + deckgl_headers + mapbox_draw_headers,\n **kwargs,\n )\n return output\n\n # -------------------------\n # Plugins\n # -------------------------\n def add_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Add Deck.GL layers to the layer stack\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.\n tooltip (str | dict): Either a single mustache template string applied to all layers\n or a dictionary where keys are layer ids and values are mustache template strings.\n \"\"\"\n self.add_call(\"addDeckOverlay\", layers, tooltip)\n\n def set_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Update Deck.GL layers\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.\n New layers will be added. Missing layers will be removed.\n tooltip (str | dict): Must be set to keep tooltip even if it did not change.\n \"\"\"\n self.add_call(\"setDeckLayers\", layers, tooltip)\n\n def add_mapbox_draw(\n self,\n options: dict | MapboxDrawOptions = None,\n position: str | ControlPosition = ControlPosition.TOP_LEFT,\n geojson: dict = None,\n ) -> None:\n \"\"\"Add MapboxDraw controls to the map\n\n Note:\n See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)\n for available options.\n\n Args:\n options (dict | MapboxDrawOptions): MapboxDraw options.\n position (str | ControlPosition): The position of the MapboxDraw controls.\n geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.\n \"\"\"\n if isinstance(options, MapboxDrawOptions):\n options = options.to_dict()\n\n self.add_call(\n \"addMapboxDraw\", options or {}, ControlPosition(position).value, geojson\n )\n
Add a method call that is executed on the map instance
Parameters:
Name Type Description Default method_namestr
The name of the map method to be executed.
required *argsany
The arguments to be passed to the map method.
() Source code in maplibre/map.py
def add_call(self, method_name: str, *args) -> None:\n \"\"\"Add a method call that is executed on the map instance\n\n Args:\n method_name (str): The name of the map method to be executed.\n *args (any): The arguments to be passed to the map method.\n \"\"\"\n # TODO: Pass as dict? {\"name\": method_name, \"args\": args}\n call = [method_name, args]\n self._message_queue.append(call)\n
def add_control(\n self,\n control: Control,\n position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,\n) -> None:\n \"\"\"Add a control to the map\n\n Args:\n control (Control): The control to be added to the map.\n position (str | ControlPosition): The position of the control.\n \"\"\"\n self.add_call(\n \"addControl\",\n control.type,\n control.to_dict(),\n ControlPosition(position).value,\n )\n
A list of dictionaries containing the Deck.GL layers to be added.
required tooltipstr | dict
Either a single mustache template string applied to all layers or a dictionary where keys are layer ids and values are mustache template strings.
None Source code in maplibre/map.py
def add_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Add Deck.GL layers to the layer stack\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.\n tooltip (str | dict): Either a single mustache template string applied to all layers\n or a dictionary where keys are layer ids and values are mustache template strings.\n \"\"\"\n self.add_call(\"addDeckOverlay\", layers, tooltip)\n
The ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If None, the new layer will appear above all other layers.
None Source code in maplibre/map.py
def add_layer(self, layer: [Layer | dict], before_id: str = None) -> None:\n \"\"\"Add a layer to the map\n\n Args:\n layer (Layer | dict): The Layer to be added to the map.\n before_id (str): The ID of an existing layer to insert the new layer before,\n resulting in the new layer appearing visually beneath the existing layer.\n If `None`, the new layer will appear above all other layers.\n \"\"\"\n if isinstance(layer, Layer):\n layer = layer.to_dict()\n\n self.add_call(\"addLayer\", layer, before_id)\n
See MapboxDraw API Reference for available options.
Parameters:
Name Type Description Default optionsdict | MapboxDrawOptions
MapboxDraw options.
Nonepositionstr | ControlPosition
The position of the MapboxDraw controls.
TOP_LEFTgeojsondict
A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
None Source code in maplibre/map.py
def add_mapbox_draw(\n self,\n options: dict | MapboxDrawOptions = None,\n position: str | ControlPosition = ControlPosition.TOP_LEFT,\n geojson: dict = None,\n) -> None:\n \"\"\"Add MapboxDraw controls to the map\n\n Note:\n See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)\n for available options.\n\n Args:\n options (dict | MapboxDrawOptions): MapboxDraw options.\n position (str | ControlPosition): The position of the MapboxDraw controls.\n geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.\n \"\"\"\n if isinstance(options, MapboxDrawOptions):\n options = options.to_dict()\n\n self.add_call(\n \"addMapboxDraw\", options or {}, ControlPosition(position).value, geojson\n )\n
def add_marker(self, marker: Marker) -> None:\n \"\"\"Add a marker to the map\n\n Args:\n marker (Marker): The marker to be added to the map.\n \"\"\"\n self.add_call(\"addMarker\", marker.to_dict())\n
The property of the source to be displayed. If None, all properties are displayed.
Nonetemplatestr
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:\n \"\"\"Add a popup to the map\n\n Args:\n layer_id (str): The layer to which the popup is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n \"\"\"\n self.add_call(\"addPopup\", layer_id, prop, template)\n
def add_source(self, id: str, source: [Source | dict]) -> None:\n \"\"\"Add a source to the map\n\n Args:\n id (str): The unique ID of the source.\n source (Source | dict): The source to be added to the map.\n \"\"\"\n if isinstance(source, Source):\n source = source.to_dict()\n\n self.add_call(\"addSource\", id, source)\n
def add_tooltip(\n self, layer_id: str, prop: str = None, template: str = None\n) -> None:\n \"\"\"Add a tooltip to the map\n\n Args:\n layer_id (str): The layer to which the tooltip is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n\n Examples:\n >>> map = Map()\n >>> # ...\n >>> map.add_tooltip(\"test-layer\", template=\"Name: {{ name }}\")\n \"\"\"\n self.add_call(\"addTooltip\", layer_id, prop, template)\n
def set_data(self, source_id: str, data: dict) -> None:\n \"\"\"Update the data of a GeoJSON source\n\n Args:\n source_id (str): The name of the source to be updated.\n data (dict): The data of the source.\n \"\"\"\n self.add_call(\"setSourceData\", source_id, data)\n
A list of dictionaries containing the Deck.GL layers to be updated. New layers will be added. Missing layers will be removed.
required tooltipstr | dict
Must be set to keep tooltip even if it did not change.
None Source code in maplibre/map.py
def set_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Update Deck.GL layers\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.\n New layers will be added. Missing layers will be removed.\n tooltip (str | dict): Must be set to keep tooltip even if it did not change.\n \"\"\"\n self.add_call(\"setDeckLayers\", layers, tooltip)\n
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):\n \"\"\"Update the filter of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n filter_ (list): The filter expression that is applied to the source of the layer.\n \"\"\"\n self.add_call(\"setFilter\", layer_id, filter_)\n
def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update a layout property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the layout property to be updated.\n value (any): The new value of the layout property.\n \"\"\"\n self.add_call(\"setLayoutProperty\", layer_id, prop, value)\n
def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update the paint property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the paint property to be updated.\n value (any): The new value of the paint property.\n \"\"\"\n self.add_call(\"setPaintProperty\", layer_id, prop, value)\n
def set_visibility(self, layer_id: str, visible: bool = True) -> None:\n \"\"\"Update the visibility of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n visible (bool): Whether the layer is visible or not.\n \"\"\"\n value = \"visible\" if visible else \"none\"\n self.add_call(\"setLayoutProperty\", layer_id, \"visibility\", value)\n
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 idstring
The id of the map to be updated.
required sessionSession
A Shiny session. If None, the active session is used.
None Source code in maplibre/mapcontext.py
class MapContext(Map):\n \"\"\"MapContext\n\n Use this class to update a `Map` instance in a Shiny app.\n Must be used inside an async function.\n\n See `maplibre.Map` for available methods.\n\n Args:\n id (string): The id of the map to be updated.\n session (Session): A Shiny session.\n If `None`, the active session is used.\n \"\"\"\n\n def __init__(self, id: str, session: Session = None) -> None:\n self.id = id\n self._session = require_active_session(session)\n self.map_options = {}\n self._message_queue = []\n\n async def __aenter__(self):\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.render()\n\n async def render(self):\n await self._session.send_custom_message(\n f\"pymaplibregl-{self.id}\", {\"id\": self.id, \"calls\": self._message_queue}\n )\n
Use this class to display and update maps in Jupyter Notebooks.
See maplibre.Map for available methods.
Examples:
>>> from maplibre import MapOptions\n>>> from maplibre.ipywidget import MapWidget as Map\n>>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))\n>>> m\n
Source code in maplibre/ipywidget.py
class MapWidget(AnyWidget, Map):\n \"\"\"MapWidget\n\n Use this class to display and update maps in Jupyter Notebooks.\n\n See `maplibre.Map` for available methods.\n\n Examples:\n >>> from maplibre import MapOptions\n >>> from maplibre.ipywidget import MapWidget as Map\n >>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))\n >>> m # doctest: +SKIP\n \"\"\"\n\n _esm = join(Path(__file__).parent, \"srcjs\", \"ipywidget.js\")\n # _css = join(Path(__file__).parent, \"srcjs\", \"maplibre-gl.css\")\n _css = join(Path(__file__).parent, \"srcjs\", \"ipywidget.css\")\n _use_message_queue = True\n _rendered = traitlets.Bool(False, config=True).tag(sync=True)\n map_options = traitlets.Dict().tag(sync=True)\n calls = traitlets.List().tag(sync=True)\n height = traitlets.Union([traitlets.Int(), traitlets.Unicode()]).tag(sync=True)\n\n # Interactions\n clicked = traitlets.Dict().tag(sync=True)\n center = traitlets.Dict().tag(sync=True)\n zoom = traitlets.Float().tag(sync=True)\n bounds = traitlets.Dict().tag(sync=True)\n draw_features_selected = traitlets.List().tag(sync=True)\n draw_feature_collection_all = traitlets.Dict().tag(sync=True)\n\n def __init__(self, map_options=MapOptions(), **kwargs) -> None:\n self.calls = []\n AnyWidget.__init__(self, **kwargs)\n Map.__init__(self, map_options, **kwargs)\n\n @traitlets.default(\"height\")\n def _default_height(self):\n return \"400px\"\n\n @traitlets.validate(\"height\")\n def _validate_height(self, proposal):\n height = proposal[\"value\"]\n if isinstance(height, int):\n return f\"{height}px\"\n\n return height\n\n @traitlets.observe(\"_rendered\")\n def _on_rendered(self, change):\n self.send({\"calls\": self._message_queue, \"msg\": \"init\"})\n self._message_queue = []\n\n def use_message_queue(self, value: bool = True) -> None:\n self._use_message_queue = value\n\n def add_call(self, method_name: str, *args) -> None:\n call = [method_name, args]\n if not self._rendered:\n if not self._use_message_queue:\n self.calls = self.calls + [call]\n return\n\n self._message_queue.append(call)\n return\n\n self.send({\"calls\": [call], \"msg\": \"custom call\"})\n
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"MapLibre for Python","text":"
MapLibre for Python provides Python bindings for MapLibre GL JS.
It integrates seamlessly into Shiny for Python and Jupyter.
from maplibre.ipywidget import MapWidget as Map\n\nm = Map()\nm\n
"},{"location":"changelog/","title":"Changelog for MapLibre for Python","text":""},{"location":"changelog/#maplibre-v025","title":"maplibre v0.2.5","text":"
Deck.GL layers can be added to the map with Map.add_deck_layers.
They are defined as a dictionary, where classes got the @@type prefix and getter props the @@= prefix. They are inserted into the layer stack of the maplibre context. Therefore, you can also pass a beforeId prop.
Here is an example corresponding to the Deck.GL GridLayer API Example:
MapLibre for Python provides the following reactive inputs:
map-on-click event: Sends the coordinates of the location that was clicked on. The name of the input event corresponds to the output id. For output_maplibregl(\"maplibre\") you need to listen to input.maplibre.
feature-on-click event: Sends the properties of the feature that was clicked on. The name of the \u00ecnput is made up of the output id + layer + layer id. For output_maplibregl(\"maplibre\") and a layer with id=test you need to listen to input.maplibre_layer_test.
def construct_basemap_style(\n name: str = \"nice-style\", sources: dict = {}, layers: list = []\n) -> dict:\n \"\"\"Construct a basemap style\n\n Args:\n name (str): The name of the basemap style.\n sources (dict): The sources to be used for the basemap style.\n layers (list): The layers to be used for the basemap style.\n \"\"\"\n layers = [\n layer.to_dict() if isinstance(layer, Layer) else layer for layer in layers\n ]\n return {\"name\": name, \"version\": 8, \"sources\": sources, \"layers\": layers}\n
"},{"location":"api/controls/","title":"Markers and controls","text":""},{"location":"api/controls/#maplibre.controls.Popup","title":"maplibre.controls.Popup","text":"
Bases: BaseModel
Popup
Attributes:
Name Type Description textstr
The Text of the popup.
optionsPopupOptions | dict
Popup options.
Source code in maplibre/controls.py
class Popup(BaseModel):\n \"\"\"Popup\n\n Attributes:\n text: The Text of the popup.\n options (PopupOptions | dict): Popup options.\n \"\"\"\n\n text: str\n options: Union[PopupOptions, dict] = {}\n
Required. The longitude and latitude of the marker.
popupPopup | dict
The Popup that is displayed when a user clicks on the marker.
optionsMarkerOptions | dict
Marker options.
Source code in maplibre/controls.py
class Marker(BaseModel):\n \"\"\"Marker\n\n Attributes:\n lng_lat (tuple |list): **Required.** The longitude and latitude of the marker.\n popup (Popup | dict): The Popup that is displayed when a user clicks on the marker.\n options (MarkerOptions | dict): Marker options.\n \"\"\"\n\n lng_lat: Union[tuple, list] = Field(None, serialization_alias=\"lngLat\")\n popup: Union[Popup, dict] = None\n options: Union[MarkerOptions, dict] = {}\n
Content (HTML or plain text) to be displayed in the info box.
css_textstr
Optional inline style declaration of the control.
Source code in maplibre/controls.py
class InfoBoxControl(Control):\n \"\"\"InfoBox control\n\n Attributes:\n content (str): Content (HTML or plain text) to be displayed in the info box.\n css_text (str): Optional inline style declaration of the control.\n \"\"\"\n\n content: str\n css_text: str = Field(None, serialization_alias=\"cssText\")\n
A list of layer ids to be shown in the layer switcher control.
themeLiteral['default', 'simple']
The theme of the layer switcher control.
css_textstr
Optional inline style declaration of the control.
Source code in maplibre/controls.py
class LayerSwitcherControl(Control):\n \"\"\"Layer switcher control\n\n Attributes:\n layer_ids (list): A list of layer ids to be shown in the layer switcher control.\n theme (Literal[\"default\", \"simple\"]): The theme of the layer switcher control.\n css_text (str): Optional inline style declaration of the control.\n \"\"\"\n\n layer_ids: list = Field([], serialization_alias=\"layerIds\")\n theme: Literal[\"default\", \"simple\"] = \"default\"\n css_text: str = Field(None, serialization_alias=\"cssText\")\n
class Layer(BaseModel):\n \"\"\"Layer properties\n\n Notes:\n See [layers](https://maplibre.org/maplibre-style-spec/layers/) for more details on the\n `paint` and `layout` properties of the layers.\n\n Attributes:\n id (str): **Required.** The unique ID of the layer. Defaults to `str(uuid4())`.\n type (str | LayerType): **Required.** The type of the layer.\n filter (list): The filter expression that is applied to the source of the layer.\n layout (dict): The layout properties of the layer.\n max_zoom (int): The maximum zoom level for the layer.\n min_zoom (int): The minimum zoom level for the layer.\n paint (dict): The paint properties of the layer.\n source (str | Source): The name (unique ID) of a source or a source object to be used for the layer.\n source_layer (str): The layer to use from a vector tile source.\n\n Examples:\n >>> from maplibre.layer import Layer, LayerType\n\n >>> layer = Layer(id=\"test-layer\", type=LayerType.CIRCLE, source=\"test-source\")\n \"\"\"\n\n id: str = Field(default_factory=lambda: str(uuid4()))\n type: LayerType\n filter: list = None\n layout: dict = None\n max_zoom: int = Field(None, serialization_alias=\"maxzoom\")\n metadata: dict = None\n min_zoom: int = Field(None, serialization_alias=\"minzoom\")\n paint: dict = None\n source: Union[str, Source, dict, None] = None\n source_layer: str = Field(None, serialization_alias=\"source-layer\")\n\n @field_validator(\"source\")\n def validate_source(cls, v):\n if isinstance(v, Source):\n return v.to_dict()\n\n return v\n\n @field_validator(\"paint\", \"layout\")\n def fix_paint(cls, v):\n if isinstance(v, dict):\n return fix_keys(v)\n\n return v\n
A Client-side hillshading visualization based on DEM data.
BACKGROUND \u2013
A background color or pattern.
Source code in maplibre/layer.py
class LayerType(Enum):\n \"\"\"Rendering type of layer\n\n Attributes:\n CIRCLE: A filled circle.\n FILL: A filled polygon with an optional stroked border.\n FILL_EXTRUSION: An extruded polygon.\n LINE: A stroked line.\n SYMBOL: An icon or a text label.\n RASTER: Raster map textures such as satellite imagery.\n HEATMAP: A heatmap.\n HILLSHADE: A Client-side hillshading visualization based on DEM data.\n BACKGROUND: A background color or pattern.\n \"\"\"\n\n CIRCLE = \"circle\"\n FILL = \"fill\"\n FILL_EXTRUSION = \"fill-extrusion\"\n LINE = \"line\"\n SYMBOL = \"symbol\"\n RASTER = \"raster\"\n HEATMAP = \"heatmap\"\n HILLSHADE = \"hillshade\"\n BACKGROUND = \"background\"\n
class Map(object):\n \"\"\"Map\n\n Args:\n map_options (MapOptions): Map options.\n **kwargs: Keyword arguments that are appended to the `MapOptions` object.\n\n Examples:\n >>> from maplibre.map import Map, MapOptions\n\n >>> map_options = MapOptions(center=(9.5, 51.31667), zoom=8)\n >>> map = Map(map_options)\n >>> dict(map)\n {'mapOptions': {'center': (9.5, 51.31667), 'style': 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json', 'zoom': 8}, 'calls': []}\n \"\"\"\n\n MESSAGE = \"not implemented yet\"\n\n def __init__(self, map_options: MapOptions = MapOptions(), **kwargs):\n self.map_options = map_options.to_dict() | kwargs\n self._message_queue = []\n\n def __iter__(self):\n for k, v in self.to_dict().items():\n yield k, v\n\n def to_dict(self) -> dict:\n return {\"mapOptions\": self.map_options, \"calls\": self._message_queue}\n\n \"\"\"\n @property\n def sources(self) -> list:\n return [item[\"data\"] for item in self._calls if item[\"name\"] == \"addSource\"]\n\n @property\n def layers(self) -> list:\n return [item[\"data\"] for item in self._calls if item[\"name\"] == \"addLayer\"]\n \"\"\"\n\n # TODO: Rename to add_map_call\n def add_call_(self, func_name: str, params: list) -> None:\n self._message_queue.append(\n {\"name\": \"applyFunc\", \"data\": {\"funcName\": func_name, \"params\": params}}\n )\n\n def add_call(self, method_name: str, *args) -> None:\n \"\"\"Add a method call that is executed on the map instance\n\n Args:\n method_name (str): The name of the map method to be executed.\n *args (any): The arguments to be passed to the map method.\n \"\"\"\n # TODO: Pass as dict? {\"name\": method_name, \"args\": args}\n call = [method_name, args]\n self._message_queue.append(call)\n\n def add_control(\n self,\n control: Control,\n position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,\n ) -> None:\n \"\"\"Add a control to the map\n\n Args:\n control (Control): The control to be added to the map.\n position (str | ControlPosition): The position of the control.\n \"\"\"\n self.add_call(\n \"addControl\",\n control.type,\n control.to_dict(),\n ControlPosition(position).value,\n )\n\n def add_source(self, id: str, source: [Source | dict]) -> None:\n \"\"\"Add a source to the map\n\n Args:\n id (str): The unique ID of the source.\n source (Source | dict): The source to be added to the map.\n \"\"\"\n if isinstance(source, Source):\n source = source.to_dict()\n\n self.add_call(\"addSource\", id, source)\n\n def add_layer(self, layer: [Layer | dict], before_id: str = None) -> None:\n \"\"\"Add a layer to the map\n\n Args:\n layer (Layer | dict): The Layer to be added to the map.\n before_id (str): The ID of an existing layer to insert the new layer before,\n resulting in the new layer appearing visually beneath the existing layer.\n If `None`, the new layer will appear above all other layers.\n \"\"\"\n if isinstance(layer, Layer):\n layer = layer.to_dict()\n\n self.add_call(\"addLayer\", layer, before_id)\n\n def add_marker(self, marker: Marker) -> None:\n \"\"\"Add a marker to the map\n\n Args:\n marker (Marker): The marker to be added to the map.\n \"\"\"\n self.add_call(\"addMarker\", marker.to_dict())\n\n def add_popup(self, layer_id: str, prop: str = None, template: str = None) -> None:\n \"\"\"Add a popup to the map\n\n Args:\n layer_id (str): The layer to which the popup is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n \"\"\"\n self.add_call(\"addPopup\", layer_id, prop, template)\n\n def add_tooltip(\n self, layer_id: str, prop: str = None, template: str = None\n ) -> None:\n \"\"\"Add a tooltip to the map\n\n Args:\n layer_id (str): The layer to which the tooltip is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n\n Examples:\n >>> map = Map()\n >>> # ...\n >>> map.add_tooltip(\"test-layer\", template=\"Name: {{ name }}\")\n \"\"\"\n self.add_call(\"addTooltip\", layer_id, prop, template)\n\n def set_filter(self, layer_id: str, filter_: list):\n \"\"\"Update the filter of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n filter_ (list): The filter expression that is applied to the source of the layer.\n \"\"\"\n self.add_call(\"setFilter\", layer_id, filter_)\n\n def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update the paint property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the paint property to be updated.\n value (any): The new value of the paint property.\n \"\"\"\n self.add_call(\"setPaintProperty\", layer_id, prop, value)\n\n def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update a layout property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the layout property to be updated.\n value (any): The new value of the layout property.\n \"\"\"\n self.add_call(\"setLayoutProperty\", layer_id, prop, value)\n\n def set_data(self, source_id: str, data: dict) -> None:\n \"\"\"Update the data of a GeoJSON source\n\n Args:\n source_id (str): The name of the source to be updated.\n data (dict): The data of the source.\n \"\"\"\n self.add_call(\"setSourceData\", source_id, data)\n\n def set_visibility(self, layer_id: str, visible: bool = True) -> None:\n \"\"\"Update the visibility of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n visible (bool): Whether the layer is visible or not.\n \"\"\"\n value = \"visible\" if visible else \"none\"\n self.add_call(\"setLayoutProperty\", layer_id, \"visibility\", value)\n\n def to_html(self, title: str = \"My Awesome Map\", **kwargs) -> str:\n \"\"\"Render to html\n\n Args:\n title (str): The Title of the HTML document.\n **kwargs (Any): Additional keyword arguments that are passed to the template.\n Currently, `style` is the only supported keyword argument.\n\n Examples:\n >>> from maplibre import Map\n\n >>> map = Map()\n >>> with open(\"/tmp/map.html\", \"w\") as f:\n ... f.write(map.to_html(style=\"height: 800px;\") # doctest: +SKIP\n \"\"\"\n js_lib = read_internal_file(\"srcjs\", \"pywidget.js\")\n js_snippet = Template(js_template).render(data=json.dumps(self.to_dict()))\n css = read_internal_file(\"srcjs\", \"pywidget.css\")\n headers = [f\"<style>{css}</style>\"]\n\n # Deck.GL headers\n add_deckgl_headers = \"addDeckOverlay\" in [\n item[0] for item in self._message_queue\n ]\n # TODO: Set version in constants\n deckgl_headers = (\n [\n '<script src=\"https://unpkg.com/deck.gl@9.0.16/dist.min.js\"></script>',\n '<script src=\"https://unpkg.com/@deck.gl/json@9.0.16/dist.min.js\"></script>',\n ]\n if add_deckgl_headers\n else []\n )\n\n # Mapbox Draw headers\n add_mapbox_draw_headers = \"addMapboxDraw\" in [\n item[0] for item in self._message_queue\n ]\n # TODO: Set version in constants\n mapbox_draw_headers = (\n [\n # \"<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.js'></script>\",\n # \"<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.css' type='text/css' />\",\n \"<script src='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.js'></script>\",\n \"<link rel='stylesheet' href='https://www.unpkg.com/@mapbox/mapbox-gl-draw@1.4.3/dist/mapbox-gl-draw.css' type='text/css' />\",\n ]\n if add_mapbox_draw_headers\n else []\n )\n\n output = Template(html_template).render(\n js=\"\\n\".join([js_lib, js_snippet]),\n title=title,\n headers=headers + deckgl_headers + mapbox_draw_headers,\n **kwargs,\n )\n return output\n\n # -------------------------\n # Plugins\n # -------------------------\n def add_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Add Deck.GL layers to the layer stack\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.\n tooltip (str | dict): Either a single mustache template string applied to all layers\n or a dictionary where keys are layer ids and values are mustache template strings.\n \"\"\"\n self.add_call(\"addDeckOverlay\", layers, tooltip)\n\n def set_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Update Deck.GL layers\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.\n New layers will be added. Missing layers will be removed.\n tooltip (str | dict): Must be set to keep tooltip even if it did not change.\n \"\"\"\n self.add_call(\"setDeckLayers\", layers, tooltip)\n\n def add_mapbox_draw(\n self,\n options: dict | MapboxDrawOptions = None,\n position: str | ControlPosition = ControlPosition.TOP_LEFT,\n geojson: dict = None,\n ) -> None:\n \"\"\"Add MapboxDraw controls to the map\n\n Note:\n See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)\n for available options.\n\n Args:\n options (dict | MapboxDrawOptions): MapboxDraw options.\n position (str | ControlPosition): The position of the MapboxDraw controls.\n geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.\n \"\"\"\n if isinstance(options, MapboxDrawOptions):\n options = options.to_dict()\n\n self.add_call(\n \"addMapboxDraw\", options or {}, ControlPosition(position).value, geojson\n )\n
Add a method call that is executed on the map instance
Parameters:
Name Type Description Default method_namestr
The name of the map method to be executed.
required *argsany
The arguments to be passed to the map method.
() Source code in maplibre/map.py
def add_call(self, method_name: str, *args) -> None:\n \"\"\"Add a method call that is executed on the map instance\n\n Args:\n method_name (str): The name of the map method to be executed.\n *args (any): The arguments to be passed to the map method.\n \"\"\"\n # TODO: Pass as dict? {\"name\": method_name, \"args\": args}\n call = [method_name, args]\n self._message_queue.append(call)\n
def add_control(\n self,\n control: Control,\n position: [str | ControlPosition] = ControlPosition.TOP_RIGHT,\n) -> None:\n \"\"\"Add a control to the map\n\n Args:\n control (Control): The control to be added to the map.\n position (str | ControlPosition): The position of the control.\n \"\"\"\n self.add_call(\n \"addControl\",\n control.type,\n control.to_dict(),\n ControlPosition(position).value,\n )\n
A list of dictionaries containing the Deck.GL layers to be added.
required tooltipstr | dict
Either a single mustache template string applied to all layers or a dictionary where keys are layer ids and values are mustache template strings.
None Source code in maplibre/map.py
def add_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Add Deck.GL layers to the layer stack\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be added.\n tooltip (str | dict): Either a single mustache template string applied to all layers\n or a dictionary where keys are layer ids and values are mustache template strings.\n \"\"\"\n self.add_call(\"addDeckOverlay\", layers, tooltip)\n
The ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If None, the new layer will appear above all other layers.
None Source code in maplibre/map.py
def add_layer(self, layer: [Layer | dict], before_id: str = None) -> None:\n \"\"\"Add a layer to the map\n\n Args:\n layer (Layer | dict): The Layer to be added to the map.\n before_id (str): The ID of an existing layer to insert the new layer before,\n resulting in the new layer appearing visually beneath the existing layer.\n If `None`, the new layer will appear above all other layers.\n \"\"\"\n if isinstance(layer, Layer):\n layer = layer.to_dict()\n\n self.add_call(\"addLayer\", layer, before_id)\n
See MapboxDraw API Reference for available options.
Parameters:
Name Type Description Default optionsdict | MapboxDrawOptions
MapboxDraw options.
Nonepositionstr | ControlPosition
The position of the MapboxDraw controls.
TOP_LEFTgeojsondict
A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.
None Source code in maplibre/map.py
def add_mapbox_draw(\n self,\n options: dict | MapboxDrawOptions = None,\n position: str | ControlPosition = ControlPosition.TOP_LEFT,\n geojson: dict = None,\n) -> None:\n \"\"\"Add MapboxDraw controls to the map\n\n Note:\n See [MapboxDraw API Reference](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md)\n for available options.\n\n Args:\n options (dict | MapboxDrawOptions): MapboxDraw options.\n position (str | ControlPosition): The position of the MapboxDraw controls.\n geojson (dict): A GeoJSON Feature, FeatureCollection or Geometry to be added to the draw layer.\n \"\"\"\n if isinstance(options, MapboxDrawOptions):\n options = options.to_dict()\n\n self.add_call(\n \"addMapboxDraw\", options or {}, ControlPosition(position).value, geojson\n )\n
def add_marker(self, marker: Marker) -> None:\n \"\"\"Add a marker to the map\n\n Args:\n marker (Marker): The marker to be added to the map.\n \"\"\"\n self.add_call(\"addMarker\", marker.to_dict())\n
The property of the source to be displayed. If None, all properties are displayed.
Nonetemplatestr
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:\n \"\"\"Add a popup to the map\n\n Args:\n layer_id (str): The layer to which the popup is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n \"\"\"\n self.add_call(\"addPopup\", layer_id, prop, template)\n
def add_source(self, id: str, source: [Source | dict]) -> None:\n \"\"\"Add a source to the map\n\n Args:\n id (str): The unique ID of the source.\n source (Source | dict): The source to be added to the map.\n \"\"\"\n if isinstance(source, Source):\n source = source.to_dict()\n\n self.add_call(\"addSource\", id, source)\n
def add_tooltip(\n self, layer_id: str, prop: str = None, template: str = None\n) -> None:\n \"\"\"Add a tooltip to the map\n\n Args:\n layer_id (str): The layer to which the tooltip is added.\n prop (str): The property of the source to be displayed. If `None`, all properties are displayed.\n template (str): A mustache template. If supplied, `prop` is ignored.\n\n Examples:\n >>> map = Map()\n >>> # ...\n >>> map.add_tooltip(\"test-layer\", template=\"Name: {{ name }}\")\n \"\"\"\n self.add_call(\"addTooltip\", layer_id, prop, template)\n
def set_data(self, source_id: str, data: dict) -> None:\n \"\"\"Update the data of a GeoJSON source\n\n Args:\n source_id (str): The name of the source to be updated.\n data (dict): The data of the source.\n \"\"\"\n self.add_call(\"setSourceData\", source_id, data)\n
A list of dictionaries containing the Deck.GL layers to be updated. New layers will be added. Missing layers will be removed.
required tooltipstr | dict
Must be set to keep tooltip even if it did not change.
None Source code in maplibre/map.py
def set_deck_layers(self, layers: list[dict], tooltip: str | dict = None) -> None:\n \"\"\"Update Deck.GL layers\n\n Args:\n layers (list[dict]): A list of dictionaries containing the Deck.GL layers to be updated.\n New layers will be added. Missing layers will be removed.\n tooltip (str | dict): Must be set to keep tooltip even if it did not change.\n \"\"\"\n self.add_call(\"setDeckLayers\", layers, tooltip)\n
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):\n \"\"\"Update the filter of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n filter_ (list): The filter expression that is applied to the source of the layer.\n \"\"\"\n self.add_call(\"setFilter\", layer_id, filter_)\n
def set_layout_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update a layout property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the layout property to be updated.\n value (any): The new value of the layout property.\n \"\"\"\n self.add_call(\"setLayoutProperty\", layer_id, prop, value)\n
def set_paint_property(self, layer_id: str, prop: str, value: any) -> None:\n \"\"\"Update the paint property of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n prop (str): The name of the paint property to be updated.\n value (any): The new value of the paint property.\n \"\"\"\n self.add_call(\"setPaintProperty\", layer_id, prop, value)\n
def set_visibility(self, layer_id: str, visible: bool = True) -> None:\n \"\"\"Update the visibility of a layer\n\n Args:\n layer_id (str): The name of the layer to be updated.\n visible (bool): Whether the layer is visible or not.\n \"\"\"\n value = \"visible\" if visible else \"none\"\n self.add_call(\"setLayoutProperty\", layer_id, \"visibility\", value)\n
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 idstring
The id of the map to be updated.
required sessionSession
A Shiny session. If None, the active session is used.
None Source code in maplibre/mapcontext.py
class MapContext(Map):\n \"\"\"MapContext\n\n Use this class to update a `Map` instance in a Shiny app.\n Must be used inside an async function.\n\n See `maplibre.Map` for available methods.\n\n Args:\n id (string): The id of the map to be updated.\n session (Session): A Shiny session.\n If `None`, the active session is used.\n \"\"\"\n\n def __init__(self, id: str, session: Session = None) -> None:\n self.id = id\n self._session = require_active_session(session)\n self.map_options = {}\n self._message_queue = []\n\n async def __aenter__(self):\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.render()\n\n async def render(self):\n await self._session.send_custom_message(\n f\"pymaplibregl-{self.id}\", {\"id\": self.id, \"calls\": self._message_queue}\n )\n
Use this class to display and update maps in Jupyter Notebooks.
See maplibre.Map for available methods.
Examples:
>>> from maplibre import MapOptions\n>>> from maplibre.ipywidget import MapWidget as Map\n>>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))\n>>> m\n
Source code in maplibre/ipywidget.py
class MapWidget(AnyWidget, Map):\n \"\"\"MapWidget\n\n Use this class to display and update maps in Jupyter Notebooks.\n\n See `maplibre.Map` for available methods.\n\n Examples:\n >>> from maplibre import MapOptions\n >>> from maplibre.ipywidget import MapWidget as Map\n >>> m = Map(MapOptions(center=(-123.13, 49.254), zoom=11, pitch=45))\n >>> m # doctest: +SKIP\n \"\"\"\n\n _esm = join(Path(__file__).parent, \"srcjs\", \"ipywidget.js\")\n # _css = join(Path(__file__).parent, \"srcjs\", \"maplibre-gl.css\")\n _css = join(Path(__file__).parent, \"srcjs\", \"ipywidget.css\")\n _use_message_queue = True\n _rendered = traitlets.Bool(False, config=True).tag(sync=True)\n map_options = traitlets.Dict().tag(sync=True)\n calls = traitlets.List().tag(sync=True)\n height = traitlets.Union([traitlets.Int(), traitlets.Unicode()]).tag(sync=True)\n\n # Interactions\n clicked = traitlets.Dict().tag(sync=True)\n center = traitlets.Dict().tag(sync=True)\n zoom = traitlets.Float().tag(sync=True)\n bounds = traitlets.Dict().tag(sync=True)\n draw_features_selected = traitlets.List().tag(sync=True)\n draw_feature_collection_all = traitlets.Dict().tag(sync=True)\n\n def __init__(self, map_options=MapOptions(), **kwargs) -> None:\n self.calls = []\n AnyWidget.__init__(self, **kwargs)\n Map.__init__(self, map_options, **kwargs)\n\n @traitlets.default(\"height\")\n def _default_height(self):\n return \"400px\"\n\n @traitlets.validate(\"height\")\n def _validate_height(self, proposal):\n height = proposal[\"value\"]\n if isinstance(height, int):\n return f\"{height}px\"\n\n return height\n\n @traitlets.observe(\"_rendered\")\n def _on_rendered(self, change):\n self.send({\"calls\": self._message_queue, \"msg\": \"init\"})\n self._message_queue = []\n\n def use_message_queue(self, value: bool = True) -> None:\n self._use_message_queue = value\n\n def add_call(self, method_name: str, *args) -> None:\n call = [method_name, args]\n if not self._rendered:\n if not self._use_message_queue:\n self.calls = self.calls + [call]\n return\n\n self._message_queue.append(call)\n return\n\n self.send({\"calls\": [call], \"msg\": \"custom call\"})\n