Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion folium/folium.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ class Map(JSCSSMixin, Evented):
Explore more provider names available in ``xyzservices`` here:
https://leaflet-extras.github.io/leaflet-providers/preview/.

Some providers, including CartoDB, require an API key. Pass one with
``tiles=folium.TileLayer("CartoDB Positron", api_key="...")``.

You can also pass a custom tileset by passing a
:class:`xyzservices.TileProvider` or a Leaflet-style
URL to the tiles parameter: ``https://{s}.yourtiles.com/{z}/{x}/{y}.png``.
Expand Down Expand Up @@ -175,7 +178,10 @@ class Map(JSCSSMixin, Evented):
Examples
--------
>>> m = folium.Map(location=[45.523, -122.675], width=750, height=500)
>>> m = folium.Map(location=[45.523, -122.675], tiles="cartodb positron")
>>> m = folium.Map(
... location=[45.523, -122.675],
... tiles=folium.TileLayer("cartodb positron", api_key="your-carto-key"),
... )
>>> m = folium.Map(
... location=[45.523, -122.675],
... zoom_start=2,
Expand Down
2 changes: 1 addition & 1 deletion folium/plugins/dual_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class DualMap(JSCSSMixin, MacroElement):
Examples
--------
>>> # DualMap accepts the same arguments as Map:
>>> m = DualMap(location=(0, 0), tiles="cartodbpositron", zoom_start=5)
>>> m = DualMap(location=(0, 0), tiles="OpenStreetMap", zoom_start=5)
>>> # Add the same marker to both maps:
>>> Marker((0, 0)).add_to(m)
>>> # The individual maps are attributes called `m1` and `m2`:
Expand Down
42 changes: 40 additions & 2 deletions folium/raster_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@
)


def _with_api_key(
provider: xyzservices.TileProvider, api_key: str
) -> xyzservices.TileProvider:
"""Return a copy of `provider` with its token placeholder set to `api_key`.

Providers name their token field differently (``apikey``, ``accessToken``,
``subscriptionKey``, ...). Like ``TileProvider.requires_token``, we look for
the field that holds an ``"<insert your ...>"`` placeholder and is used in
the URL.
"""
token_fields = [
key
for key, value in provider.items()
if isinstance(value, str) and "<insert your" in value and key in provider.url
]
if not token_fields:
raise ValueError(
f"Tile provider {provider.name!r} has no API key placeholder to fill: "
"it either does not need a key or already has one."
)
return provider(**{key: api_key for key in token_fields})


class TileLayer(Layer):
"""
Create a tile layer to append on a Map.
Expand All @@ -34,15 +57,21 @@ class TileLayer(Layer):
any of the following to the "tiles" keyword:

- "OpenStreetMap"
- "CartoDB Positron"
- "CartoDB Voyager"
- "CartoDB Positron" (requires an API key, see ``api_key``)
- "CartoDB Voyager" (requires an API key, see ``api_key``)

Explore more provider names available in ``xyzservices`` here:
https://leaflet-extras.github.io/leaflet-providers/preview/.

You can also pass a custom tileset by passing a
:class:`xyzservices.TileProvider` or a Leaflet-style
URL to the tiles parameter: ``https://{s}.yourtiles.com/{z}/{x}/{y}.png``.
api_key: str, optional
API key or access token for tile providers that require one, such as
CartoDB, Thunderforest or MapBox. It fills in the provider's token
placeholder, whatever that provider calls it (``apikey``, ``accessToken``,
...). Only valid when ``tiles`` is an ``xyzservices`` provider or one of
its names. For a custom URL, put the key in the URL itself.
min_zoom: int, optional, default 0
Minimum allowed zoom level for this tile layer. Filled by xyzservices by default.
max_zoom: int, optional, default 18
Expand Down Expand Up @@ -106,6 +135,7 @@ def __init__(
subdomains: str = "abc",
tms: bool = False,
opacity: float = 1,
api_key: str | None = None,
**kwargs,
):
if isinstance(tiles, str):
Expand All @@ -119,6 +149,14 @@ def __init__(
# no match, likely a custom URL
pass

if api_key is not None:
if not isinstance(tiles, xyzservices.TileProvider):
raise ValueError(
"`api_key` can only be used with an xyzservices tile provider. "
"For a custom tile URL, include the key in the URL itself."
)
tiles = _with_api_key(tiles, api_key)

if isinstance(tiles, xyzservices.TileProvider):
attr = attr if attr else tiles.html_attribution # type: ignore
min_zoom = min_zoom or tiles.get("min_zoom")
Expand Down
41 changes: 41 additions & 0 deletions tests/test_raster_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

"""

import warnings

import numpy as np
import pytest
import xyzservices
Expand Down Expand Up @@ -148,3 +150,42 @@ def test_xyzservices(tiles):
)
in out
)


@pytest.mark.parametrize(
"tiles", ["CartoDB Positron", xyzservices.providers.CartoDB.Positron]
)
def test_tile_layer_api_key(tiles):
with warnings.catch_warnings():
warnings.simplefilter("error") # no "API key required" warning
layer = folium.TileLayer(tiles, api_key="my-key")
assert layer.tiles == xyzservices.providers.CartoDB.Positron.build_url(
fill_subdomain=False, scale_factor="{r}", apikey="my-key"
)
assert layer.tiles.endswith("?key=my-key")
assert "api_key" not in layer.options
assert "apiKey" not in layer.options


def test_tile_layer_api_key_other_placeholder_name():
# MapBox calls its token placeholder `accessToken`, not `apikey`.
layer = folium.TileLayer("MapBox", api_key="my-token")
assert "access_token=my-token" in layer.tiles


def test_tile_layer_api_key_does_not_modify_provider():
provider = xyzservices.providers.CartoDB.Positron
folium.TileLayer(provider, api_key="my-key")
assert provider.requires_token()


def test_tile_layer_api_key_rejects_custom_url():
with pytest.raises(ValueError, match="custom tile URL"):
folium.TileLayer(
"https://{s}.example.com/{z}/{x}/{y}.png", attr="x", api_key="my-key"
)


def test_tile_layer_api_key_rejects_provider_without_placeholder():
with pytest.raises(ValueError, match="no API key placeholder"):
folium.TileLayer("OpenStreetMap", api_key="my-key")