Skip to content

foliumap module

Map (Map)

The Map class inherits folium.Map. By default, the Map will add OpenStreetMap as the basemap.

Returns:

Type Description
object

folium map object.

add_basemap(self, basemap='HYBRID')

Adds a basemap to the map.

Parameters:

Name Type Description Default
basemap str

Can be one of string from ee_basemaps. Defaults to 'HYBRID'.

'HYBRID'
Source code in leafmap/foliumap.py
def add_basemap(self, basemap="HYBRID"):
    """Adds a basemap to the map.

    Args:
        basemap (str, optional): Can be one of string from ee_basemaps. Defaults to 'HYBRID'.
    """
    import xyzservices

    try:
        if isinstance(basemap, xyzservices.TileProvider):
            name = basemap.name
            url = basemap.build_url()
            attribution = basemap.attribution
            if "max_zoom" in basemap.keys():
                max_zoom = basemap["max_zoom"]
            else:
                max_zoom = 22
            layer = folium.TileLayer(
                tiles=url,
                attr=attribution,
                name=name,
                max_zoom=max_zoom,
                overlay=True,
                control=True,
            )

            self.add_layer(layer)
        elif basemap in folium_basemaps:
            folium_basemaps[basemap].add_to(self)
        else:
            print(
                "Basemap can only be one of the following: {}".format(
                    ", ".join(folium_basemaps.keys())
                )
            )
    except Exception:
        raise Exception(
            "Basemap can only be one of the following: {}".format(
                ", ".join(folium_basemaps.keys())
            )
        )

add_census_data(self, wms, layer, census_dict=None, **kwargs)

Adds a census data layer to the map.

Parameters:

Name Type Description Default
wms str

The wms to use. For example, "Current", "ACS 2021", "Census 2020". See the complete list at https://tigerweb.geo.census.gov/tigerwebmain/TIGERweb_wms.html

required
layer str

The layer name to add to the map.

required
census_dict dict

A dictionary containing census data. Defaults to None. It can be obtained from the get_census_dict() function.

None
Source code in leafmap/foliumap.py
def add_census_data(self, wms, layer, census_dict=None, **kwargs):
    """Adds a census data layer to the map.

    Args:
        wms (str): The wms to use. For example, "Current", "ACS 2021", "Census 2020".  See the complete list at https://tigerweb.geo.census.gov/tigerwebmain/TIGERweb_wms.html
        layer (str): The layer name to add to the map.
        census_dict (dict, optional): A dictionary containing census data. Defaults to None. It can be obtained from the get_census_dict() function.
    """

    try:
        if census_dict is None:
            census_dict = get_census_dict()

        if wms not in census_dict.keys():
            raise ValueError(
                f"The provided WMS is invalid. It must be one of {census_dict.keys()}"
            )

        layers = census_dict[wms]["layers"]
        if layer not in layers:
            raise ValueError(
                f"The layer name is not valid. It must be one of {layers}"
            )

        url = census_dict[wms]["url"]
        if "name" not in kwargs:
            kwargs["name"] = layer
        if "attribution" not in kwargs:
            kwargs["attribution"] = "U.S. Census Bureau"
        if "format" not in kwargs:
            kwargs["format"] = "image/png"
        if "transparent" not in kwargs:
            kwargs["transparent"] = True

        self.add_wms_layer(url, layer, **kwargs)

    except Exception as e:
        raise Exception(e)

add_cog_layer(self, url, name='Untitled', attribution='.', opacity=1.0, shown=True, titiler_endpoint='https://api.cogeo.xyz/', **kwargs)

Adds a COG TileLayer to the map.

Parameters:

Name Type Description Default
url str

The URL of the COG tile layer.

required
name str

The layer name to use for the layer. Defaults to 'Untitled'.

'Untitled'
attribution str

The attribution to use. Defaults to '.'.

'.'
opacity float

The opacity of the layer. Defaults to 1.

1.0
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
titiler_endpoint str

Titiler endpoint. Defaults to "https://api.cogeo.xyz/".

'https://api.cogeo.xyz/'
Source code in leafmap/foliumap.py
def add_cog_layer(
    self,
    url,
    name="Untitled",
    attribution=".",
    opacity=1.0,
    shown=True,
    titiler_endpoint="https://api.cogeo.xyz/",
    **kwargs,
):
    """Adds a COG TileLayer to the map.

    Args:
        url (str): The URL of the COG tile layer.
        name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
        attribution (str, optional): The attribution to use. Defaults to '.'.
        opacity (float, optional): The opacity of the layer. Defaults to 1.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://api.cogeo.xyz/".
    """
    tile_url = cog_tile(url, titiler_endpoint, **kwargs)
    center = cog_center(url, titiler_endpoint)  # (lon, lat)
    self.add_tile_layer(
        url=tile_url,
        name=name,
        attribution=attribution,
        opacity=opacity,
        shown=shown,
    )
    self.set_center(lon=center[0], lat=center[1], zoom=10)

add_cog_mosaic(self, links, name='Untitled', attribution='.', opacity=1.0, shown=True, titiler_endpoint='https://api.cogeo.xyz/', username='anonymous', overwrite=False, show_footprints=False, verbose=True, **kwargs)

Add a virtual mosaic of COGs to the map.

Parameters:

Name Type Description Default
links list

A list of links pointing to COGs.

required
name str

The layer name to use for the layer. Defaults to 'Untitled'.

'Untitled'
attribution str

The attribution to use. Defaults to '.'.

'.'
opacity float

The opacity of the layer. Defaults to 1.

1.0
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
titiler_endpoint str

Titiler endpoint. Defaults to "https://api.cogeo.xyz/".

'https://api.cogeo.xyz/'
username str

The username to create mosaic using the titiler endpoint. Defaults to 'anonymous'.

'anonymous'
overwrite bool

Whether or not to replace existing layer with the same layer name. Defaults to False.

False
show_footprints bool

Whether or not to show footprints of COGs. Defaults to False.

False
verbose bool

Whether or not to print descriptions. Defaults to True.

True
Source code in leafmap/foliumap.py
def add_cog_mosaic(
    self,
    links,
    name="Untitled",
    attribution=".",
    opacity=1.0,
    shown=True,
    titiler_endpoint="https://api.cogeo.xyz/",
    username="anonymous",
    overwrite=False,
    show_footprints=False,
    verbose=True,
    **kwargs,
):
    """Add a virtual mosaic of COGs to the map.

    Args:
        links (list): A list of links pointing to COGs.
        name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
        attribution (str, optional): The attribution to use. Defaults to '.'.
        opacity (float, optional): The opacity of the layer. Defaults to 1.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://api.cogeo.xyz/".
        username (str, optional): The username to create mosaic using the titiler endpoint. Defaults to 'anonymous'.
        overwrite (bool, optional): Whether or not to replace existing layer with the same layer name. Defaults to False.
        show_footprints (bool, optional): Whether or not to show footprints of COGs. Defaults to False.
        verbose (bool, optional): Whether or not to print descriptions. Defaults to True.
    """
    layername = name.replace(" ", "_")
    tile = cog_mosaic(
        links,
        titiler_endpoint=titiler_endpoint,
        username=username,
        layername=layername,
        overwrite=overwrite,
        verbose=verbose,
    )
    self.add_tile_layer(tile, name, attribution, opacity, shown)

    if show_footprints:
        if verbose:
            print(
                f"Generating footprints of {len(links)} COGs. This might take a while ..."
            )
        coords = []
        for link in links:
            coord = cog_bounds(link)
            if coord is not None:
                coords.append(coord)
        fc = coords_to_geojson(coords)

        # style_function = lambda x: {'opacity': 1, 'dashArray': '1', 'fillOpacity': 0, 'weight': 1}

        folium.GeoJson(
            data=fc,
            # style_function=style_function,
            name=name + "_footprints",
        ).add_to(self)

        center = get_center(fc)
        if verbose:
            print("The footprint layer has been added.")
    else:
        center = cog_center(links[0], titiler_endpoint)

    self.set_center(center[0], center[1], zoom=6)

add_cog_mosaic_from_file(self, filepath, skip_rows=0, name='Untitled', attribution='.', opacity=1.0, shown=True, titiler_endpoint='https://api.cogeo.xyz/', username='anonymous', overwrite=False, show_footprints=False, verbose=True, **kwargs)

Add a virtual mosaic of COGs to the map.

Parameters:

Name Type Description Default
filepath str

Local path or HTTP URL to the csv/txt file containing COG URLs.

required
skip_rows int

The number of rows to skip in the file. Defaults to 0.

0
name str

The layer name to use for the layer. Defaults to 'Untitled'.

'Untitled'
attribution str

The attribution to use. Defaults to '.'.

'.'
opacity float

The opacity of the layer. Defaults to 1.

1.0
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
titiler_endpoint str

Titiler endpoint. Defaults to "https://api.cogeo.xyz/".

'https://api.cogeo.xyz/'
username str

The username to create mosaic using the titiler endpoint. Defaults to 'anonymous'.

'anonymous'
overwrite bool

Whether or not to replace existing layer with the same layer name. Defaults to False.

False
show_footprints bool

Whether or not to show footprints of COGs. Defaults to False.

False
verbose bool

Whether or not to print descriptions. Defaults to True.

True
Source code in leafmap/foliumap.py
def add_cog_mosaic_from_file(
    self,
    filepath,
    skip_rows=0,
    name="Untitled",
    attribution=".",
    opacity=1.0,
    shown=True,
    titiler_endpoint="https://api.cogeo.xyz/",
    username="anonymous",
    overwrite=False,
    show_footprints=False,
    verbose=True,
    **kwargs,
):
    """Add a virtual mosaic of COGs to the map.

    Args:
        filepath (str): Local path or HTTP URL to the csv/txt file containing COG URLs.
        skip_rows (int, optional): The number of rows to skip in the file. Defaults to 0.
        name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
        attribution (str, optional): The attribution to use. Defaults to '.'.
        opacity (float, optional): The opacity of the layer. Defaults to 1.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://api.cogeo.xyz/".
        username (str, optional): The username to create mosaic using the titiler endpoint. Defaults to 'anonymous'.
        overwrite (bool, optional): Whether or not to replace existing layer with the same layer name. Defaults to False.
        show_footprints (bool, optional): Whether or not to show footprints of COGs. Defaults to False.
        verbose (bool, optional): Whether or not to print descriptions. Defaults to True.
    """
    import urllib

    layername = name.replace(" ", "_")

    links = []
    if filepath.startswith("http"):
        data = urllib.request.urlopen(filepath)
        for line in data:
            links.append(line.decode("utf-8").strip())

    else:
        with open(filepath) as f:
            links = [line.strip() for line in f.readlines()]

    links = links[skip_rows:]

    tile = cog_mosaic(
        links,
        titiler_endpoint=titiler_endpoint,
        username=username,
        layername=layername,
        overwrite=overwrite,
        verbose=verbose,
    )
    self.add_tile_layer(tile, name, attribution, opacity, shown)

    if show_footprints:
        if verbose:
            print(
                f"Generating footprints of {len(links)} COGs. This might take a while ..."
            )
        coords = []
        for link in links:
            coord = cog_bounds(link)
            if coord is not None:
                coords.append(coord)
        fc = coords_to_geojson(coords)

        # style_function = lambda x: {'opacity': 1, 'dashArray': '1', 'fillOpacity': 0, 'weight': 1}

        folium.GeoJson(
            data=fc,
            # style_function=style_function,
            name=name + "_footprints",
        ).add_to(self)

        center = get_center(fc)
        if verbose:
            print("The footprint layer has been added.")
    else:
        center = cog_center(links[0], titiler_endpoint)

    self.set_center(center[0], center[1], zoom=6)

add_colorbar(self, colors, vmin=0, vmax=1.0, index=None, caption='', categorical=False, step=None, **kwargs)

Add a colorbar to the map.

Parameters:

Name Type Description Default
colors list

The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)

required
vmin int

The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.

0
vmax float

The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.

1.0
index list

The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.

None
caption str

The caption for the colormap. Defaults to "".

''
categorical bool

Whether or not to create a categorical colormap. Defaults to False.

False
step int

The step to split the LinearColormap into a StepColormap. Defaults to None.

None
Source code in leafmap/foliumap.py
def add_colorbar(
    self,
    colors,
    vmin=0,
    vmax=1.0,
    index=None,
    caption="",
    categorical=False,
    step=None,
    **kwargs,
):
    """Add a colorbar to the map.

    Args:
        colors (list): The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)
        vmin (int, optional): The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.
        vmax (float, optional): The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.
        index (list, optional):The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.
        caption (str, optional): The caption for the colormap. Defaults to "".
        categorical (bool, optional): Whether or not to create a categorical colormap. Defaults to False.
        step (int, optional): The step to split the LinearColormap into a StepColormap. Defaults to None.
    """
    from box import Box
    from branca.colormap import LinearColormap

    if isinstance(colors, Box):
        try:
            colors = list(colors["default"])
        except Exception as e:
            print("The provided color list is invalid.")
            raise Exception(e)

    if all(len(color) == 6 for color in colors):
        colors = ["#" + color for color in colors]

    colormap = LinearColormap(
        colors=colors, index=index, vmin=vmin, vmax=vmax, caption=caption
    )

    if categorical:
        if step is not None:
            colormap = colormap.to_step(step)
        elif index is not None:
            colormap = colormap.to_step(len(index) - 1)
        else:
            colormap = colormap.to_step(3)

    self.add_child(colormap)

add_colormap(self, cmap='gray', colors=None, discrete=False, label=None, width=8.0, height=0.4, orientation='horizontal', vmin=0, vmax=1.0, axis_off=False, show_name=False, font_size=12, transparent_bg=False, position='bottomright', **kwargs)

Adds a matplotlib colormap to the map.

Source code in leafmap/foliumap.py
def add_colormap(
    self,
    cmap="gray",
    colors=None,
    discrete=False,
    label=None,
    width=8.0,
    height=0.4,
    orientation="horizontal",
    vmin=0,
    vmax=1.0,
    axis_off=False,
    show_name=False,
    font_size=12,
    transparent_bg=False,
    position="bottomright",
    **kwargs,
):
    """Adds a matplotlib colormap to the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_gdf(self, gdf, layer_name='Untitled', zoom_to_layer=True, **kwargs)

Adds a GeoPandas GeoDataFrameto the map.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoPandas GeoDataFrame.

required
layer_name str

The layer name to be used. Defaults to "Untitled".

'Untitled'
zoom_to_layer bool

Whether to zoom to the layer.

True
Source code in leafmap/foliumap.py
def add_gdf(self, gdf, layer_name="Untitled", zoom_to_layer=True, **kwargs):
    """Adds a GeoPandas GeoDataFrameto the map.

    Args:
        gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
        layer_name (str, optional): The layer name to be used. Defaults to "Untitled".
        zoom_to_layer (bool, optional): Whether to zoom to the layer.

    """

    data = gdf_to_geojson(gdf, epsg="4326")

    self.add_geojson(data, layer_name=layer_name, **kwargs)

    if zoom_to_layer:
        import numpy as np

        bounds = gdf.to_crs(epsg="4326").bounds
        west = np.min(bounds["minx"])
        south = np.min(bounds["miny"])
        east = np.max(bounds["maxx"])
        north = np.max(bounds["maxy"])
        self.fit_bounds([[south, east], [north, west]])

add_gdf_from_postgis(self, sql, con, layer_name='Untitled', zoom_to_layer=True, **kwargs)

Adds a GeoPandas GeoDataFrameto the map.

Parameters:

Name Type Description Default
sql str

SQL query to execute in selecting entries from database, or name of the table to read from the database.

required
con sqlalchemy.engine.Engine

Active connection to the database to query.

required
layer_name str

The layer name to be used. Defaults to "Untitled".

'Untitled'
zoom_to_layer bool

Whether to zoom to the layer.

True
Source code in leafmap/foliumap.py
def add_gdf_from_postgis(
    self, sql, con, layer_name="Untitled", zoom_to_layer=True, **kwargs
):
    """Adds a GeoPandas GeoDataFrameto the map.

    Args:
        sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database.
        con (sqlalchemy.engine.Engine): Active connection to the database to query.
        layer_name (str, optional): The layer name to be used. Defaults to "Untitled".
        zoom_to_layer (bool, optional): Whether to zoom to the layer.

    """
    if "fill_colors" in kwargs:
        kwargs.pop("fill_colors")
    gdf = read_postgis(sql, con, **kwargs)
    data = gdf_to_geojson(gdf, epsg="4326")

    self.add_geojson(data, layer_name=layer_name, **kwargs)

    if zoom_to_layer:
        import numpy as np

        bounds = gdf.to_crs(epsg="4326").bounds
        west = np.min(bounds["minx"])
        south = np.min(bounds["miny"])
        east = np.max(bounds["maxx"])
        north = np.max(bounds["maxy"])
        self.fit_bounds([[south, east], [north, west]])

add_geojson(self, in_geojson, layer_name='Untitled', **kwargs)

Adds a GeoJSON file to the map.

Parameters:

Name Type Description Default
in_geojson str

The input file path to the GeoJSON.

required
layer_name str

The layer name to be used. Defaults to "Untitled".

'Untitled'

Exceptions:

Type Description
FileNotFoundError

The provided GeoJSON file could not be found.

Source code in leafmap/foliumap.py
def add_geojson(self, in_geojson, layer_name="Untitled", **kwargs):
    """Adds a GeoJSON file to the map.

    Args:
        in_geojson (str): The input file path to the GeoJSON.
        layer_name (str, optional): The layer name to be used. Defaults to "Untitled".

    Raises:
        FileNotFoundError: The provided GeoJSON file could not be found.
    """
    import json
    import requests
    import random

    try:

        if isinstance(in_geojson, str):

            if in_geojson.startswith("http"):
                data = requests.get(in_geojson).json()
            else:
                in_geojson = os.path.abspath(in_geojson)
                if not os.path.exists(in_geojson):
                    raise FileNotFoundError(
                        "The provided GeoJSON file could not be found."
                    )

                with open(in_geojson) as f:
                    data = json.load(f)
        elif isinstance(in_geojson, dict):
            data = in_geojson
        else:
            raise TypeError("The input geojson must be a type of str or dict.")
    except Exception as e:
        raise Exception(e)

    # interchangeable parameters between ipyleaflet and folium.
    if "style" in kwargs:
        style_dict = kwargs["style"]
        if isinstance(kwargs["style"], dict) and len(kwargs["style"]) > 0:
            kwargs["style_function"] = lambda x: style_dict
        kwargs.pop("style")
    else:
        style_dict = {
            # "stroke": True,
            "color": "#000000",
            "weight": 1,
            "opacity": 1,
            # "fill": True,
            # "fillColor": "#ffffff",
            "fillOpacity": 0.1,
            # "dashArray": "9"
            # "clickable": True,
        }
        kwargs["style_function"] = lambda x: style_dict

    if "style_callback" in kwargs:
        if kwargs["style_callback"] is not None:
            kwargs["style_function"] = kwargs["style_callback"]
        kwargs.pop("style_callback")

    if "hover_style" in kwargs:
        if len(kwargs["hover_style"]) > 0:
            hover_dict = kwargs["hover_style"]
            kwargs["highlight_function"] = lambda x: hover_dict
        kwargs.pop("hover_style")
    else:
        hover_dict = {"weight": style_dict["weight"] + 1, "fillOpacity": 0.5}
        kwargs["highlight_function"] = lambda x: hover_dict

    if "fill_colors" in kwargs:
        fill_colors = kwargs["fill_colors"]

        def random_color(feature):
            style_dict["fillColor"] = random.choice(fill_colors)
            return style_dict

        kwargs["style_function"] = random_color

        kwargs.pop("fill_colors")
    if "info_mode" in kwargs:
        kwargs.pop("info_mode")

    geojson = folium.GeoJson(data=data, name=layer_name, **kwargs)
    geojson.add_to(self)

add_heatmap(self, filepath=None, latitude='latitude', longitude='longitude', value='value', data=None, name='Heat map', radius=25, **kwargs)

Adds a heat map to the map. Reference: https://stackoverflow.com/a/54756617

Parameters:

Name Type Description Default
filepath str

File path or HTTP URL to the input file. Defaults to None.

None
latitude str

The column name of latitude. Defaults to "latitude".

'latitude'
longitude str

The column name of longitude. Defaults to "longitude".

'longitude'
value str

The column name of values. Defaults to "value".

'value'
data list

A list of data points in the format of [[x1, y1, z1], [x2, y2, z2]]. Defaults to None.

None
name str

Layer name to use. Defaults to "Heat map".

'Heat map'
radius int

Radius of each “point” of the heatmap. Defaults to 25.

25

Exceptions:

Type Description
ValueError

If data is not a list.

Source code in leafmap/foliumap.py
def add_heatmap(
    self,
    filepath=None,
    latitude="latitude",
    longitude="longitude",
    value="value",
    data=None,
    name="Heat map",
    radius=25,
    **kwargs,
):
    """Adds a heat map to the map. Reference: https://stackoverflow.com/a/54756617

    Args:
        filepath (str, optional): File path or HTTP URL to the input file. Defaults to None.
        latitude (str, optional): The column name of latitude. Defaults to "latitude".
        longitude (str, optional): The column name of longitude. Defaults to "longitude".
        value (str, optional): The column name of values. Defaults to "value".
        data (list, optional): A list of data points in the format of [[x1, y1, z1], [x2, y2, z2]]. Defaults to None.
        name (str, optional): Layer name to use. Defaults to "Heat map".
        radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25.

    Raises:
        ValueError: If data is not a list.
    """
    import pandas as pd

    if data is None:
        if filepath is None:
            filepath = "https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_cities.csv"
            value = "pop_max"

        df = pd.read_csv(filepath)
        data = df[[latitude, longitude, value]].values.tolist()
    elif not isinstance(data, list):
        raise ValueError("data must be a list in the format of ")

    plugins.HeatMap(data, name=name, radius=radius, **kwargs).add_to(
        folium.FeatureGroup(name=name).add_to(self)
    )

add_kml(self, in_kml, layer_name='Untitled', **kwargs)

Adds a KML file to the map.

Parameters:

Name Type Description Default
in_kml str

The input file path to the KML.

required
layer_name str

The layer name to be used. Defaults to "Untitled".

'Untitled'

Exceptions:

Type Description
FileNotFoundError

The provided KML file could not be found.

Source code in leafmap/foliumap.py
def add_kml(self, in_kml, layer_name="Untitled", **kwargs):
    """Adds a KML file to the map.

    Args:
        in_kml (str): The input file path to the KML.
        layer_name (str, optional): The layer name to be used. Defaults to "Untitled".

    Raises:
        FileNotFoundError: The provided KML file could not be found.
    """

    if in_kml.startswith("http") and in_kml.endswith(".kml"):
        out_dir = os.path.abspath("./cache")
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        download_from_url(in_kml, out_dir=out_dir, unzip=False, verbose=False)
        in_kml = os.path.join(out_dir, os.path.basename(in_kml))
        if not os.path.exists(in_kml):
            raise FileNotFoundError("The downloaded kml file could not be found.")
    else:
        in_kml = os.path.abspath(in_kml)
        if not os.path.exists(in_kml):
            raise FileNotFoundError("The provided KML could not be found.")

    data = kml_to_geojson(in_kml)

    self.add_geojson(data, layer_name=layer_name, **kwargs)

add_layer(self, layer)

Adds a layer to the map.

Parameters:

Name Type Description Default
layer TileLayer

A TileLayer instance.

required
Source code in leafmap/foliumap.py
def add_layer(self, layer):
    """Adds a layer to the map.

    Args:
        layer (TileLayer): A TileLayer instance.
    """
    layer.add_to(self)

add_layer_control(self)

Adds layer control to the map.

Source code in leafmap/foliumap.py
def add_layer_control(self):
    """Adds layer control to the map."""
    layer_ctrl = False
    for item in self.to_dict()["children"]:
        if item.startswith("layer_control"):
            layer_ctrl = True
            break
    if not layer_ctrl:
        folium.LayerControl().add_to(self)

add_legend(self, title='Legend', colors=None, labels=None, legend_dict=None, builtin_legend=None, opacity=1.0, **kwargs)

Adds a customized legend to the map. Reference: https://bit.ly/3oV6vnH

Parameters:

Name Type Description Default
title str

Title of the legend. Defaults to 'Legend'. Defaults to "Legend".

'Legend'
colors [type]

A list of legend colors. Defaults to None.

None
labels [type]

A list of legend labels. Defaults to None.

None
legend_dict [type]

A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.

None
builtin_legend [type]

Name of the builtin legend to add to the map. Defaults to None.

None
opacity float

The opacity of the legend. Defaults to 1.0.

1.0
Source code in leafmap/foliumap.py
def add_legend(
    self,
    title="Legend",
    colors=None,
    labels=None,
    legend_dict=None,
    builtin_legend=None,
    opacity=1.0,
    **kwargs,
):
    """Adds a customized legend to the map. Reference: https://bit.ly/3oV6vnH

    Args:
        title (str, optional): Title of the legend. Defaults to 'Legend'. Defaults to "Legend".
        colors ([type], optional): A list of legend colors. Defaults to None.
        labels ([type], optional): A list of legend labels. Defaults to None.
        legend_dict ([type], optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
        builtin_legend ([type], optional): Name of the builtin legend to add to the map. Defaults to None.
        opacity (float, optional): The opacity of the legend. Defaults to 1.0.

    """

    import pkg_resources
    from branca.element import Template, MacroElement

    pkg_dir = os.path.dirname(
        pkg_resources.resource_filename("leafmap", "leafmap.py")
    )
    legend_template = os.path.join(pkg_dir, "data/template/legend.txt")

    if not os.path.exists(legend_template):
        raise FileNotFoundError("The legend template does not exist.")

    if labels is not None:
        if not isinstance(labels, list):
            raise ValueError("The legend labels must be a list.")
    else:
        labels = ["One", "Two", "Three", "Four", "etc"]

    if colors is not None:
        if not isinstance(colors, list):
            raise ValueError("The legend colors must be a list.")
        elif all(isinstance(item, tuple) for item in colors):
            try:
                colors = ["#" + rgb_to_hex(x) for x in colors]
            except Exception as e:
                raise Exception(e)
        elif all((item.startswith("#") and len(item) == 7) for item in colors):
            pass
        elif all((len(item) == 6) for item in colors):
            pass
        else:
            raise ValueError("The legend colors must be a list of tuples.")
    else:
        colors = ["#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3"]

    if len(labels) != len(colors):
        raise ValueError("The legend keys and values must be the same length.")

    allowed_builtin_legends = builtin_legends.keys()
    if builtin_legend is not None:
        if builtin_legend not in allowed_builtin_legends:
            raise ValueError(
                "The builtin legend must be one of the following: {}".format(
                    ", ".join(allowed_builtin_legends)
                )
            )
        else:
            legend_dict = builtin_legends[builtin_legend]
            labels = list(legend_dict.keys())
            colors = list(legend_dict.values())
            if all(isinstance(item, tuple) for item in colors):
                try:
                    colors = [rgb_to_hex(x) for x in colors]
                except Exception as e:
                    raise Exception(e)
            elif all(isinstance(item, str) for item in colors):
                colors = ["#" + color for color in colors]

    if legend_dict is not None:
        if not isinstance(legend_dict, dict):
            raise ValueError("The legend dict must be a dictionary.")
        else:
            labels = list(legend_dict.keys())
            colors = list(legend_dict.values())

            if all(isinstance(item, tuple) for item in colors):
                try:
                    colors = ["#" + rgb_to_hex(x) for x in colors]
                except Exception as e:
                    raise Exception(e)
            elif all(isinstance(item, str) for item in colors):
                colors = ["#" + color for color in colors]

    content = []

    with open(legend_template) as f:
        lines = f.readlines()
        for index, line in enumerate(lines):
            if index < 36:
                content.append(line)
            elif index == 36:
                line = lines[index].replace("Legend", title)
                content.append(line)
            elif index < 39:
                content.append(line)
            elif index == 39:
                for i, color in enumerate(colors):
                    item = f"    <li><span style='background:{check_color(color)};opacity:{opacity};'></span>{labels[i]}</li>\n"
                    content.append(item)
            elif index > 41:
                content.append(line)

    template = "".join(content)
    macro = MacroElement()
    macro._template = Template(template)

    self.get_root().add_child(macro)

add_marker_cluster(self, event='click', add_marker=True)

Captures user inputs and add markers to the map.

Source code in leafmap/foliumap.py
def add_marker_cluster(self, event="click", add_marker=True):
    """Captures user inputs and add markers to the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_minimap(self, zoom=5, position='bottomright')

Adds a minimap (overview) to the ipyleaflet map.

Source code in leafmap/foliumap.py
def add_minimap(self, zoom=5, position="bottomright"):
    """Adds a minimap (overview) to the ipyleaflet map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_osm_from_address(self, address, tags, dist=1000, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within some distance N, S, E, W of address to the map.

Parameters:

Name Type Description Default
address str

The address to geocode and use as the central point around which to get the geometries.

required
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
dist int

Distance in meters. Defaults to 1000.

1000
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_address(
    self,
    address,
    tags,
    dist=1000,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within some distance N, S, E, W of address to the map.

    Args:
        address (str): The address to geocode and use as the central point around which to get the geometries.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        dist (int, optional): Distance in meters. Defaults to 1000.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    gdf = osm_gdf_from_address(address, tags, dist)
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_bbox(self, north, south, east, west, tags, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within a N, S, E, W bounding box to the map.

Parameters:

Name Type Description Default
north float

Northern latitude of bounding box.

required
south float

Southern latitude of bounding box.

required
east float

Eastern longitude of bounding box.

required
west float

Western longitude of bounding box.

required
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_bbox(
    self,
    north,
    south,
    east,
    west,
    tags,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within a N, S, E, W bounding box to the map.


    Args:
        north (float): Northern latitude of bounding box.
        south (float): Southern latitude of bounding box.
        east (float): Eastern longitude of bounding box.
        west (float): Western longitude of bounding box.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    gdf = osm_gdf_from_bbox(north, south, east, west, tags)
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_geocode(self, query, which_result=None, by_osmid=False, buffer_dist=None, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM data of place(s) by name or ID to the map.

Parameters:

Name Type Description Default
query str | dict | list

Query string(s) or structured dict(s) to geocode.

required
which_result int

Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.

None
by_osmid bool

If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.

False
buffer_dist float

Distance to buffer around the place geometry, in meters. Defaults to None.

None
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_geocode(
    self,
    query,
    which_result=None,
    by_osmid=False,
    buffer_dist=None,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM data of place(s) by name or ID to the map.

    Args:
        query (str | dict | list): Query string(s) or structured dict(s) to geocode.
        which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
        by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.
        buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """

    gdf = osm_gdf_from_geocode(
        query, which_result=which_result, by_osmid=by_osmid, buffer_dist=buffer_dist
    )
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_place(self, query, tags, which_result=None, buffer_dist=None, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within boundaries of geocodable place(s) to the map.

Parameters:

Name Type Description Default
query str | dict | list

Query string(s) or structured dict(s) to geocode.

required
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
which_result int

Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.

None
buffer_dist float

Distance to buffer around the place geometry, in meters. Defaults to None.

None
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_place(
    self,
    query,
    tags,
    which_result=None,
    buffer_dist=None,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within boundaries of geocodable place(s) to the map.

    Args:
        query (str | dict | list): Query string(s) or structured dict(s) to geocode.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
        buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    gdf = osm_gdf_from_place(query, tags, which_result, buffer_dist)
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_point(self, center_point, tags, dist=1000, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within some distance N, S, E, W of a point to the map.

Parameters:

Name Type Description Default
center_point tuple

The (lat, lng) center point around which to get the geometries.

required
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
dist int

Distance in meters. Defaults to 1000.

1000
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_point(
    self,
    center_point,
    tags,
    dist=1000,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within some distance N, S, E, W of a point to the map.

    Args:
        center_point (tuple): The (lat, lng) center point around which to get the geometries.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        dist (int, optional): Distance in meters. Defaults to 1000.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    gdf = osm_gdf_from_point(center_point, tags, dist)
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_polygon(self, polygon, tags, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within boundaries of a (multi)polygon to the map.

Parameters:

Name Type Description Default
polygon shapely.geometry.Polygon | shapely.geometry.MultiPolygon

Geographic boundaries to fetch geometries within

required
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_polygon(
    self,
    polygon,
    tags,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within boundaries of a (multi)polygon to the map.

    Args:
        polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    gdf = osm_gdf_from_polygon(polygon, tags)
    geojson = gdf.__geo_interface__

    self.add_geojson(
        geojson,
        layer_name=layer_name,
        style=style,
        hover_style=hover_style,
        style_callback=style_callback,
        fill_colors=fill_colors,
        info_mode=info_mode,
    )
    self.zoom_to_gdf(gdf)

add_osm_from_view(self, tags, layer_name='Untitled', style={}, hover_style={}, style_callback=None, fill_colors=['black'], info_mode='on_hover')

Adds OSM entities within the current map view to the map.

Parameters:

Name Type Description Default
tags dict

Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.

required
layer_name str

The layer name to be used.. Defaults to "Untitled".

'Untitled'
style dict

A dictionary specifying the style to be used. Defaults to {}.

{}
hover_style dict

Hover style dictionary. Defaults to {}.

{}
style_callback function

Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.

None
fill_colors list

The random colors to use for filling polygons. Defaults to ["black"].

['black']
info_mode str

Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

'on_hover'
Source code in leafmap/foliumap.py
def add_osm_from_view(
    self,
    tags,
    layer_name="Untitled",
    style={},
    hover_style={},
    style_callback=None,
    fill_colors=["black"],
    info_mode="on_hover",
):
    """Adds OSM entities within the current map view to the map.

    Args:
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
        style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
        hover_style (dict, optional): Hover style dictionary. Defaults to {}.
        style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
        fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
        info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".

    """
    pass  # folium can't get map bounds. See https://github.com/python-visualization/folium/issues/1118
    # bounds = self.get_bounds()
    # north, south, east, west = (
    #     bounds[1][0],
    #     bounds[0][0],
    #     bounds[1][1],
    #     bounds[0][1],
    # )

    # gdf = osm_gdf_from_bbox(north, south, east, west, tags)
    # geojson = gdf.__geo_interface__

    # self.add_geojson(
    #     geojson,
    #     layer_name=layer_name,
    #     style=style,
    #     hover_style=hover_style,
    #     style_callback=style_callback,
    #     fill_colors=fill_colors,
    #     info_mode=info_mode,
    # )
    # self.zoom_to_gdf(gdf)

add_planet_by_month(self, year=2016, month=1, name=None, api_key=None, token_name='PLANET_API_KEY')

Adds a Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
month int

The month of Planet global mosaic, must be 1-12. Defaults to 1.

1
name str

The layer name to use. Defaults to None.

None
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
Source code in leafmap/foliumap.py
def add_planet_by_month(
    self, year=2016, month=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
    """Adds a Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis

    Args:
        year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
        month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
        name (str, optional): The layer name to use. Defaults to None.
        api_key (str, optional): The Planet API key. Defaults to None.
        token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
    """
    layer = planet_tile_by_month(
        year, month, name, api_key, token_name, tile_format="folium"
    )
    layer.add_to(self)

add_planet_by_quarter(self, year=2016, quarter=1, name=None, api_key=None, token_name='PLANET_API_KEY')

Adds a Planet global mosaic by quarter to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
quarter int

The quarter of Planet global mosaic, must be 1-12. Defaults to 1.

1
name str

The layer name to use. Defaults to None.

None
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
Source code in leafmap/foliumap.py
def add_planet_by_quarter(
    self, year=2016, quarter=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
    """Adds a Planet global mosaic by quarter to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis

    Args:
        year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
        quarter (int, optional): The quarter of Planet global mosaic, must be 1-12. Defaults to 1.
        name (str, optional): The layer name to use. Defaults to None.
        api_key (str, optional): The Planet API key. Defaults to None.
        token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
    """
    layer = planet_tile_by_quarter(
        year, quarter, name, api_key, token_name, tile_format="folium"
    )
    layer.add_to(self)

add_point_layer(self, filename, popup=None, layer_name='Marker Cluster', **kwargs)

Adds a point layer to the map with a popup attribute.

Source code in leafmap/foliumap.py
def add_point_layer(
    self, filename, popup=None, layer_name="Marker Cluster", **kwargs
):
    """Adds a point layer to the map with a popup attribute."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_raster(self, image, bands=None, layer_name=None, colormap=None, x_dim='x', y_dim='y')

Adds a local raster dataset to the map.

Source code in leafmap/foliumap.py
def add_raster(
    self,
    image,
    bands=None,
    layer_name=None,
    colormap=None,
    x_dim="x",
    y_dim="y",
):
    """Adds a local raster dataset to the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_shp(self, in_shp, layer_name='Untitled', **kwargs)

Adds a shapefile to the map. See https://python-visualization.github.io/folium/modules.html#folium.features.GeoJson for more info about setting style.

Parameters:

Name Type Description Default
in_shp str

The input file path to the shapefile.

required
layer_name str

The layer name to be used. Defaults to "Untitled".

'Untitled'

Exceptions:

Type Description
FileNotFoundError

The provided shapefile could not be found.

Source code in leafmap/foliumap.py
def add_shp(self, in_shp, layer_name="Untitled", **kwargs):
    """Adds a shapefile to the map. See https://python-visualization.github.io/folium/modules.html#folium.features.GeoJson for more info about setting style.

    Args:
        in_shp (str): The input file path to the shapefile.
        layer_name (str, optional): The layer name to be used. Defaults to "Untitled".

    Raises:
        FileNotFoundError: The provided shapefile could not be found.
    """
    import glob

    if in_shp.startswith("http") and in_shp.endswith(".zip"):
        out_dir = os.path.abspath("./cache/shp")
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        download_from_url(in_shp, out_dir=out_dir, verbose=False)
        files = list(glob.glob(os.path.join(out_dir, "*.shp")))
        if len(files) > 0:
            in_shp = files[0]
        else:
            raise FileNotFoundError(
                "The downloaded zip file does not contain any shapefile in the root directory."
            )
    else:
        in_shp = os.path.abspath(in_shp)
        if not os.path.exists(in_shp):
            raise FileNotFoundError("The provided shapefile could not be found.")

    data = shp_to_geojson(in_shp)

    self.add_geojson(data, layer_name=layer_name, **kwargs)

add_stac_layer(self, url, bands=None, name='Untitled', attribution='.', opacity=1.0, shown=True, titiler_endpoint='https://api.cogeo.xyz/', **kwargs)

Adds a STAC TileLayer to the map.

Parameters:

Name Type Description Default
url str

The URL of the COG tile layer.

required
name str

The layer name to use for the layer. Defaults to 'Untitled'.

'Untitled'
attribution str

The attribution to use. Defaults to '.'.

'.'
opacity float

The opacity of the layer. Defaults to 1.

1.0
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
titiler_endpoint str

Titiler endpoint. Defaults to "https://api.cogeo.xyz/".

'https://api.cogeo.xyz/'
Source code in leafmap/foliumap.py
def add_stac_layer(
    self,
    url,
    bands=None,
    name="Untitled",
    attribution=".",
    opacity=1.0,
    shown=True,
    titiler_endpoint="https://api.cogeo.xyz/",
    **kwargs,
):
    """Adds a STAC TileLayer to the map.

    Args:
        url (str): The URL of the COG tile layer.
        name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
        attribution (str, optional): The attribution to use. Defaults to '.'.
        opacity (float, optional): The opacity of the layer. Defaults to 1.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://api.cogeo.xyz/".
    """
    tile_url = stac_tile(url, bands, titiler_endpoint, **kwargs)
    center = stac_center(url, titiler_endpoint)
    self.add_tile_layer(
        url=tile_url,
        name=name,
        attribution=attribution,
        opacity=opacity,
        shown=shown,
    )
    self.set_center(lon=center[0], lat=center[1], zoom=10)

add_tile_layer(self, url, name, attribution, overlay=True, control=True, shown=True, opacity=1.0, API_key=None, **kwargs)

Add a XYZ tile layer to the map.

Parameters:

Name Type Description Default
url str

The URL of the XYZ tile service.

required
name str

The layer name to use on the layer control.

required
attribution str

The attribution of the data layer.

required
overlay str

Allows overlay. Defaults to True.

True
control str

Adds the layer to the layer control. Defaults to True.

True
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
opacity float

Sets the opacity for the layer.

1.0
API_key str

– API key for Cloudmade or Mapbox tiles. Defaults to True.

None
Source code in leafmap/foliumap.py
def add_tile_layer(
    self,
    url,
    name,
    attribution,
    overlay=True,
    control=True,
    shown=True,
    opacity=1.0,
    API_key=None,
    **kwargs,
):
    """Add a XYZ tile layer to the map.

    Args:
        url (str): The URL of the XYZ tile service.
        name (str): The layer name to use on the layer control.
        attribution (str): The attribution of the data layer.
        overlay (str, optional): Allows overlay. Defaults to True.
        control (str, optional): Adds the layer to the layer control. Defaults to True.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        opacity (float, optional): Sets the opacity for the layer.
        API_key (str, optional): – API key for Cloudmade or Mapbox tiles. Defaults to True.
    """

    try:
        folium.raster_layers.TileLayer(
            tiles=url,
            name=name,
            attr=attribution,
            overlay=overlay,
            control=control,
            show=shown,
            opacity=opacity,
            API_key=API_key,
            **kwargs,
        ).add_to(self)
    except Exception as e:
        raise Exception(e)

add_time_slider(self, layers_dict={}, labels=None, time_interval=1, position='bottomright', slider_length='150px')

Adds a time slider to the map.

Source code in leafmap/foliumap.py
def add_time_slider(
    self,
    layers_dict={},
    labels=None,
    time_interval=1,
    position="bottomright",
    slider_length="150px",
):
    """Adds a time slider to the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_title(self, title, align='center', font_size='16px', style=None)

Adds a title to the map.

Parameters:

Name Type Description Default
title str

The title to use.

required
align str

The alignment of the title, can be ["center", "left", "right"]. Defaults to "center".

'center'
font_size str

The font size in the unit of px. Defaults to "16px".

'16px'
style [type]

The style to use. Defaults to None.

None
Source code in leafmap/foliumap.py
def add_title(self, title, align="center", font_size="16px", style=None):
    """Adds a title to the map.

    Args:
        title (str): The title to use.
        align (str, optional): The alignment of the title, can be ["center", "left", "right"]. Defaults to "center".
        font_size (str, optional): The font size in the unit of px. Defaults to "16px".
        style ([type], optional): The style to use. Defaults to None.
    """
    if style is None:
        title_html = """
                <h3 align={} style="font-size:{}"><b>{}</b></h3>
                """.format(
            align, font_size, title
        )
    else:
        title_html = """
            <h3 align={} style={}><b>{}</b></h3>
            """.format(
            align, style, title
        )
    self.get_root().html.add_child(folium.Element(title_html))

add_vector(self, filename, layer_name='Untitled', bbox=None, mask=None, rows=None, **kwargs)

Adds any geopandas-supported vector dataset to the map.

Parameters:

Name Type Description Default
filename str

Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).

required
layer_name str

The layer name to use. Defaults to "Untitled".

'Untitled'
bbox tuple | GeoDataFrame or GeoSeries | shapely Geometry

Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.

None
mask dict | GeoDataFrame or GeoSeries | shapely Geometry

Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.

None
rows int or slice

Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.

None
Source code in leafmap/foliumap.py
def add_vector(
    self,
    filename,
    layer_name="Untitled",
    bbox=None,
    mask=None,
    rows=None,
    **kwargs,
):
    """Adds any geopandas-supported vector dataset to the map.

    Args:
        filename (str): Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).
        layer_name (str, optional): The layer name to use. Defaults to "Untitled".
        bbox (tuple | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.
        mask (dict | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.
        rows (int or slice, optional): Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.

    """
    if not filename.startswith("http"):
        filename = os.path.abspath(filename)

    ext = os.path.splitext(filename)[1].lower()
    if ext == ".shp":
        self.add_shp(filename, layer_name, **kwargs)
    elif ext in [".json", ".geojson"]:
        self.add_geojson(filename, layer_name, **kwargs)
    else:
        geojson = vector_to_geojson(
            filename,
            bbox=bbox,
            mask=mask,
            rows=rows,
            epsg="4326",
            **kwargs,
        )

        self.add_geojson(geojson, layer_name, **kwargs)

add_vector_tile_layer(self, url='https://tile.nextzen.org/tilezen/vector/v1/512/all/{z}/{x}/{y}.mvt?api_key=gCZXZglvRQa6sB2z7JzL1w', attribution='', vector_tile_layer_styles={}, **kwargs)

Adds a VectorTileLayer to the map.

Source code in leafmap/foliumap.py
def add_vector_tile_layer(
    self,
    url="https://tile.nextzen.org/tilezen/vector/v1/512/all/{z}/{x}/{y}.mvt?api_key=gCZXZglvRQa6sB2z7JzL1w",
    attribution="",
    vector_tile_layer_styles=dict(),
    **kwargs,
):
    """Adds a VectorTileLayer to the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_wms_layer(self, url, layers, name=None, attribution='', overlay=True, control=True, shown=True, format='image/png', transparent=False, version='1.1.1', styles='', **kwargs)

Add a WMS layer to the map.

Parameters:

Name Type Description Default
url str

The URL of the WMS web service.

required
layers str

Comma-separated list of WMS layers to show.

required
name str

The layer name to use on the layer control. Defaults to None.

None
attribution str

The attribution of the data layer. Defaults to ''.

''
overlay str

Allows overlay. Defaults to True.

True
control str

Adds the layer to the layer control. Defaults to True.

True
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
format str

WMS image format (use ‘image/png’ for layers with transparency). Defaults to 'image/png'.

'image/png'
transparent bool

Whether the layer shall allow transparency. Defaults to False.

False
version str

Version of the WMS service to use. Defaults to "1.1.1".

'1.1.1'
styles str

Comma-separated list of WMS styles. Defaults to "".

''
Source code in leafmap/foliumap.py
def add_wms_layer(
    self,
    url,
    layers,
    name=None,
    attribution="",
    overlay=True,
    control=True,
    shown=True,
    format="image/png",
    transparent=False,
    version="1.1.1",
    styles="",
    **kwargs,
):

    """Add a WMS layer to the map.

    Args:
        url (str): The URL of the WMS web service.
        layers (str): Comma-separated list of WMS layers to show.
        name (str, optional): The layer name to use on the layer control. Defaults to None.
        attribution (str, optional): The attribution of the data layer. Defaults to ''.
        overlay (str, optional): Allows overlay. Defaults to True.
        control (str, optional): Adds the layer to the layer control. Defaults to True.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        format (str, optional): WMS image format (use ‘image/png’ for layers with transparency). Defaults to 'image/png'.
        transparent (bool, optional): Whether the layer shall allow transparency. Defaults to False.
        version (str, optional): Version of the WMS service to use. Defaults to "1.1.1".
        styles (str, optional): Comma-separated list of WMS styles. Defaults to "".
    """
    try:
        folium.raster_layers.WmsTileLayer(
            url=url,
            layers=layers,
            name=name,
            attr=attribution,
            overlay=overlay,
            control=control,
            show=shown,
            styles=styles,
            fmt=format,
            transparent=transparent,
            version=version,
            **kwargs,
        ).add_to(self)
    except Exception as e:
        raise Exception(e)

add_xy_data(self, in_csv, x='longitude', y='latitude', label=None, layer_name='Marker cluster')

Adds points from a CSV file containing lat/lon information and display data on the map.

Source code in leafmap/foliumap.py
def add_xy_data(
    self,
    in_csv,
    x="longitude",
    y="latitude",
    label=None,
    layer_name="Marker cluster",
):
    """Adds points from a CSV file containing lat/lon information and display data on the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

add_xyz_service(self, provider, **kwargs)

Add a XYZ tile layer to the map.

Parameters:

Name Type Description Default
provider str

A tile layer name starts with xyz or qms. For example, xyz.OpenTopoMap,

required

Exceptions:

Type Description
ValueError

The provider is not valid. It must start with xyz or qms.

Source code in leafmap/foliumap.py
def add_xyz_service(self, provider, **kwargs):
    """Add a XYZ tile layer to the map.

    Args:
        provider (str): A tile layer name starts with xyz or qms. For example, xyz.OpenTopoMap,

    Raises:
        ValueError: The provider is not valid. It must start with xyz or qms.
    """
    import xyzservices.providers as xyz
    from xyzservices import TileProvider

    if provider.startswith("xyz"):
        name = provider[4:]
        xyz_provider = xyz.flatten()[name]
        url = xyz_provider.build_url()
        attribution = xyz_provider.attribution
        if attribution.strip() == "":
            attribution = " "
        self.add_tile_layer(url, name, attribution)
    elif provider.startswith("qms"):
        name = provider[4:]
        qms_provider = TileProvider.from_qms(name)
        url = qms_provider.build_url()
        attribution = qms_provider.attribution
        if attribution.strip() == "":
            attribution = " "
        self.add_tile_layer(url=url, name=name, attribution=attribution)
    else:
        raise ValueError(
            f"The provider {provider} is not valid. It must start with xyz or qms."
        )

basemap_demo(self)

A demo for using leafmap basemaps.

Source code in leafmap/foliumap.py
def basemap_demo(self):
    """A demo for using leafmap basemaps."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

find_layer(self, name)

Finds layer by name.

Source code in leafmap/foliumap.py
def find_layer(self, name):
    """Finds layer by name."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

find_layer_index(self, name)

Finds layer index by name.

Source code in leafmap/foliumap.py
def find_layer_index(self, name):
    """Finds layer index by name."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

get_layer_names(self)

Gets layer names as a list.

Source code in leafmap/foliumap.py
def get_layer_names(self):
    """Gets layer names as a list."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

get_scale(self)

Returns the approximate pixel scale of the current map view, in meters.

Source code in leafmap/foliumap.py
def get_scale(self):
    """Returns the approximate pixel scale of the current map view, in meters."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

image_overlay(self, url, bounds, name)

Overlays an image from the Internet or locally on the map.

Parameters:

Name Type Description Default
url str

http URL or local file path to the image.

required
bounds tuple

bounding box of the image in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).

required
name str

name of the layer to show on the layer control.

required
Source code in leafmap/foliumap.py
def image_overlay(self, url, bounds, name):
    """Overlays an image from the Internet or locally on the map.

    Args:
        url (str): http URL or local file path to the image.
        bounds (tuple): bounding box of the image in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).
        name (str): name of the layer to show on the layer control.
    """
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

layer_opacity(self, name, value=1.0)

Changes layer opacity.

Source code in leafmap/foliumap.py
def layer_opacity(self, name, value=1.0):
    """Changes layer opacity."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

publish(self, name='Folium Map', description='', source_url='', tags=None, source_file=None, open=True, formatting=None, token=None, **kwargs)

Publish the map to datapane.com

Parameters:

Name Type Description Default
name str

The document name - can include spaces, caps, symbols, etc., e.g. "Profit & Loss 2020". Defaults to "Folium Map".

'Folium Map'
description str

A high-level description for the document, this is displayed in searches and thumbnails. Defaults to ''.

''
source_url str

A URL pointing to the source code for the document, e.g. a GitHub repo or a Colab notebook. Defaults to ''.

''
tags bool

A list of tags (as strings) used to categorise your document. Defaults to None.

None
source_file str

Path of jupyter notebook file to upload. Defaults to None.

None
open bool

Whether to open the map. Defaults to True.

True
formatting ReportFormatting

Set the basic styling for your report.

None
token str

The token to use to datapane to publish the map. See https://docs.datapane.com/tut-getting-started. Defaults to None.

None
Source code in leafmap/foliumap.py
def publish(
    self,
    name="Folium Map",
    description="",
    source_url="",
    tags=None,
    source_file=None,
    open=True,
    formatting=None,
    token=None,
    **kwargs,
):
    """Publish the map to datapane.com

    Args:
        name (str, optional): The document name - can include spaces, caps, symbols, etc., e.g. "Profit & Loss 2020". Defaults to "Folium Map".
        description (str, optional): A high-level description for the document, this is displayed in searches and thumbnails. Defaults to ''.
        source_url (str, optional): A URL pointing to the source code for the document, e.g. a GitHub repo or a Colab notebook. Defaults to ''.
        tags (bool, optional): A list of tags (as strings) used to categorise your document. Defaults to None.
        source_file (str, optional): Path of jupyter notebook file to upload. Defaults to None.
        open (bool, optional): Whether to open the map. Defaults to True.
        formatting (ReportFormatting, optional): Set the basic styling for your report.
        token (str, optional): The token to use to datapane to publish the map. See https://docs.datapane.com/tut-getting-started. Defaults to None.
    """
    import webbrowser
    import warnings

    warnings.filterwarnings("ignore")
    try:
        import datapane as dp
    except Exception:
        webbrowser.open_new_tab("https://docs.datapane.com/tut-getting-started")
        raise ImportError(
            "The datapane Python package is not installed. You need to install and authenticate datapane first."
        )

    if token is None:
        try:
            _ = dp.ping(verbose=False)
        except Exception as e:
            if os.environ.get("DP_TOKEN") is not None:
                dp.login(token=os.environ.get("DP_TOKEN"))
            else:
                raise Exception(e)
    else:
        dp.login(token)

    try:

        dp.Report(dp.Plot(self)).upload(
            name=name,
            description=description,
            source_url=source_url,
            tags=tags,
            source_file=source_file,
            open=open,
            formatting=formatting,
        )

    except Exception as e:
        raise Exception(e)

set_center(self, lon, lat, zoom=10)

Centers the map view at a given coordinates with the given zoom level.

Parameters:

Name Type Description Default
lon float

The longitude of the center, in degrees.

required
lat float

The latitude of the center, in degrees.

required
zoom int

The zoom level, from 1 to 24. Defaults to 10.

10
Source code in leafmap/foliumap.py
def set_center(self, lon, lat, zoom=10):
    """Centers the map view at a given coordinates with the given zoom level.

    Args:
        lon (float): The longitude of the center, in degrees.
        lat (float): The latitude of the center, in degrees.
        zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10.
    """
    self.fit_bounds([[lat, lon], [lat, lon]], max_zoom=zoom)

split_map(self, left_layer='HYBRID', right_layer='OpenStreetMap')

Adds split map.

Source code in leafmap/foliumap.py
def split_map(self, left_layer="HYBRID", right_layer="OpenStreetMap"):
    """Adds split map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

static_map(self, width=950, height=600, out_file=None, **kwargs)

Display a folium static map in a Jupyter Notebook.

Args m (folium.Map): A folium map. width (int, optional): Width of the map. Defaults to 950. height (int, optional): Height of the map. Defaults to 600. read_only (bool, optional): Whether to hide the side panel to disable map customization. Defaults to False. out_file (str, optional): Output html file path. Defaults to None.

Source code in leafmap/foliumap.py
def static_map(self, width=950, height=600, out_file=None, **kwargs):
    """Display a folium static map in a Jupyter Notebook.

    Args
        m (folium.Map): A folium map.
        width (int, optional): Width of the map. Defaults to 950.
        height (int, optional): Height of the map. Defaults to 600.
        read_only (bool, optional): Whether to hide the side panel to disable map customization. Defaults to False.
        out_file (str, optional): Output html file path. Defaults to None.
    """
    if isinstance(self, folium.Map):
        if out_file is None:
            out_file = "./cache/" + "folium_" + random_string(3) + ".html"
        out_dir = os.path.abspath(os.path.dirname(out_file))
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)

        self.to_html(out_file)
        display_html(src=out_file, width=width, height=height)
    else:
        raise TypeError("The provided map is not a folium map.")

to_html(self, outfile=None, **kwargs)

Exports a map as an HTML file.

Parameters:

Name Type Description Default
outfile str

File path to the output HTML. Defaults to None.

None

Exceptions:

Type Description
ValueError

If it is an invalid HTML file.

Returns:

Type Description
str

A string containing the HTML code.

Source code in leafmap/foliumap.py
def to_html(self, outfile=None, **kwargs):
    """Exports a map as an HTML file.

    Args:
        outfile (str, optional): File path to the output HTML. Defaults to None.

    Raises:
        ValueError: If it is an invalid HTML file.

    Returns:
        str: A string containing the HTML code.
    """

    if self.options["layersControl"]:
        self.add_layer_control()

    if outfile is not None:
        if not outfile.endswith(".html"):
            raise ValueError("The output file extension must be html.")
        outfile = os.path.abspath(outfile)
        out_dir = os.path.dirname(outfile)
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        self.save(outfile, **kwargs)
    else:
        outfile = os.path.abspath(random_string() + ".html")
        self.save(outfile, **kwargs)
        out_html = ""
        with open(outfile) as f:
            lines = f.readlines()
            out_html = "".join(lines)
        os.remove(outfile)
        return out_html

to_image(self, outfile=None, monitor=1)

Saves the map as a PNG or JPG image.

Source code in leafmap/foliumap.py
def to_image(self, outfile=None, monitor=1):
    """Saves the map as a PNG or JPG image."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

to_streamlit(self, width=700, height=500, add_layer_control=True, **kwargs)

Renders folium.Figure or folium.Map in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.

Parameters:

Name Type Description Default
width int

Width of the map. Defaults to 800.

700
height int

Height of the map. Defaults to 600.

500
add_layer_control bool

Whether to add the layer control. Defaults to True.

True

Exceptions:

Type Description
ImportError

If streamlit-folium is not installed.

Returns:

Type Description
streamlit.components

components.html object.

Source code in leafmap/foliumap.py
def to_streamlit(self, width=700, height=500, add_layer_control=True, **kwargs):
    """Renders `folium.Figure` or `folium.Map` in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.

    Args:
        width (int, optional): Width of the map. Defaults to 800.
        height (int, optional): Height of the map. Defaults to 600.
        add_layer_control (bool, optional): Whether to add the layer control. Defaults to True.

    Raises:
        ImportError: If streamlit-folium is not installed.

    Returns:
        streamlit.components: components.html object.
    """

    try:
        from streamlit_folium import folium_static

        if add_layer_control:
            self.add_layer_control()
        return folium_static(self, width=width, height=height)
    except ImportError:
        raise ImportError(
            "streamlit-folium is not installed. You need to install streamlit-folium first using 'pip install streamlit-folium'. See https://github.com/randyzwitch/streamlit-folium"
        )

toolbar_reset(self)

Reset the toolbar so that no tool is selected.

Source code in leafmap/foliumap.py
def toolbar_reset(self):
    """Reset the toolbar so that no tool is selected."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

video_overlay(self, url, bounds, name)

Overlays a video from the Internet on the map.

Source code in leafmap/foliumap.py
def video_overlay(self, url, bounds, name):
    """Overlays a video from the Internet on the map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

zoom_to_bounds(self, bounds)

Zooms to a bounding box in the form of [minx, miny, maxx, maxy].

Parameters:

Name Type Description Default
bounds list | tuple

A list/tuple containing minx, miny, maxx, maxy values for the bounds.

required
Source code in leafmap/foliumap.py
def zoom_to_bounds(self, bounds):
    """Zooms to a bounding box in the form of [minx, miny, maxx, maxy].

    Args:
        bounds (list | tuple): A list/tuple containing minx, miny, maxx, maxy values for the bounds.
    """
    #  The folium fit_bounds method takes lat/lon bounds in the form [[south, west], [north, east]].
    self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])

zoom_to_gdf(self, gdf)

Zooms to the bounding box of a GeoPandas GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoPandas GeoDataFrame.

required
Source code in leafmap/foliumap.py
def zoom_to_gdf(self, gdf):
    """Zooms to the bounding box of a GeoPandas GeoDataFrame.

    Args:
        gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
    """
    bounds = gdf.total_bounds
    self.zoom_to_bounds(bounds)

delete_dp_report(name)

Deletes a datapane report.

Parameters:

Name Type Description Default
name str

Name of the report to delete.

required
Source code in leafmap/foliumap.py
def delete_dp_report(name):
    """Deletes a datapane report.

    Args:
        name (str): Name of the report to delete.
    """
    try:
        import datapane as dp

        reports = dp.Report.list()
        items = list(reports)
        names = list(map(lambda item: item["name"], items))
        if name in names:
            report = dp.Report.get(name)
            url = report.blocks[0]["url"]
            # print('Deleting {}...'.format(url))
            dp.Report.delete(dp.Report.by_id(url))
    except Exception as e:
        raise Exception(e)

delete_dp_reports()

Deletes all datapane reports.

Source code in leafmap/foliumap.py
def delete_dp_reports():
    """Deletes all datapane reports."""
    try:
        import datapane as dp

        reports = dp.Report.list()
        for item in reports:
            print(item["name"])
            report = dp.Report.get(item["name"])
            url = report.blocks[0]["url"]
            print("Deleting {}...".format(url))
            dp.Report.delete(dp.Report.by_id(url))
    except Exception as e:
        raise Exception(e)

linked_maps(rows=2, cols=2, height='400px', layers=[], labels=[], label_position='topright', **kwargs)

Create linked maps of XYZ tile layers.

Source code in leafmap/foliumap.py
def linked_maps(
    rows=2,
    cols=2,
    height="400px",
    layers=[],
    labels=[],
    label_position="topright",
    **kwargs,
):
    """Create linked maps of XYZ tile layers."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

split_map(left_layer='ROADMAP', right_layer='HYBRID', left_label=None, right_label=None, label_position='bottom', **kwargs)

Creates a split-panel map.

Source code in leafmap/foliumap.py
def split_map(
    left_layer="ROADMAP",
    right_layer="HYBRID",
    left_label=None,
    right_label=None,
    label_position="bottom",
    **kwargs,
):
    """Creates a split-panel map."""
    raise NotImplementedError(
        "The folium plotting backend does not support this function. Use the ipyleaflet plotting backend instead."
    )

Last update: 2021-10-19