diff --git a/leafmap/basemaps.py b/leafmap/basemaps.py
index 4662a9be92..8b10b71266 100644
--- a/leafmap/basemaps.py
+++ b/leafmap/basemaps.py
@@ -28,7 +28,13 @@
import xyzservices
from traitlets import Unicode
-from .common import GoogleMapsTileProvider, check_package, planet_tiles
+from .common import (
+ GoogleMapsTileProvider,
+ check_package,
+ is_carto_provider,
+ normalize_carto_provider,
+ planet_tiles,
+)
GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY", None)
@@ -331,7 +337,11 @@ def get_xyz_dict(free_only: bool = True, france: bool = False) -> dict:
xyz_bunch = xyzservices.providers
if free_only:
- xyz_bunch = xyz_bunch.filter(requires_token=False)
+ # CARTO providers require a key since xyzservices 2026.9.0. Keep them,
+ # since leafmap adds the CARTO_API_KEY key when a layer is created.
+ xyz_bunch = xyz_bunch.filter(
+ function=lambda tile: not tile.requires_token() or is_carto_provider(tile)
+ )
if not france:
xyz_bunch = xyz_bunch.filter(
function=lambda tile: "france" not in dict(tile)["name"].lower()
@@ -340,7 +350,7 @@ def get_xyz_dict(free_only: bool = True, france: bool = False) -> dict:
xyz_dict = xyz_bunch.flatten()
for key, value in xyz_dict.items():
- tile = xyzservices.TileProvider(value)
+ tile = normalize_carto_provider(xyzservices.TileProvider(value))
if "type" not in tile:
tile["type"] = "xyz"
xyz_dict[key] = tile
diff --git a/leafmap/common.py b/leafmap/common.py
index d289a3c51f..b3faf01330 100644
--- a/leafmap/common.py
+++ b/leafmap/common.py
@@ -1989,6 +1989,135 @@ def get_api_key(name: Optional[str] = None, key: Optional[str] = None) -> Option
return None
+_CARTO_KEY_WARNED = False
+
+
+def _is_carto_url(url: Any) -> bool:
+ """Checks whether a URL is hosted on basemaps.cartocdn.com.
+
+ Args:
+ url (Any): The URL to check. Non-string values return False.
+
+ Returns:
+ True if the URL's hostname is basemaps.cartocdn.com or a subdomain of it.
+ """
+ from urllib.parse import urlsplit
+
+ if not isinstance(url, str):
+ return False
+ try:
+ host = (urlsplit(url).hostname or "").lower()
+ except ValueError:
+ return False
+ return host == "basemaps.cartocdn.com" or host.endswith(".basemaps.cartocdn.com")
+
+
+def add_carto_api_key(url: Any, key: Optional[str] = None, warn: bool = True) -> Any:
+ """Appends a CARTO Basemaps API key to a basemaps.cartocdn.com URL.
+
+ CARTO requires an API key on every basemaps.cartocdn.com URL (raster tiles
+ and vector styles). Without a key, raster tiles show an "API key required"
+ watermark. Request a free key at https://carto.com/basemaps/apikey and set
+ it as the ``CARTO_API_KEY`` environment variable (or Colab secret).
+
+ Note that the key becomes part of the layer URL, so it is included in
+ anything that serializes the map, such as HTML exports, saved notebook
+ outputs, and widget state. Restrict the key to your domains in the CARTO
+ dashboard before publishing such maps.
+
+ Args:
+ url (Any): The tile or style URL. Non-string values and URLs that are
+ not hosted on basemaps.cartocdn.com are returned unchanged.
+ key (str, optional): The CARTO API key. Defaults to None, which reads
+ the ``CARTO_API_KEY`` environment variable or Colab secret.
+ warn (bool, optional): Whether to print a one-time notice when no key
+ is found. Defaults to True.
+
+ Returns:
+ The URL with the ``key`` query parameter appended when a key is available.
+ """
+ global _CARTO_KEY_WARNED
+ from urllib.parse import parse_qs, quote, urlsplit
+
+ if not _is_carto_url(url):
+ return url
+ if "key" in parse_qs(urlsplit(url).query, keep_blank_values=True):
+ return url
+
+ key = get_api_key("CARTO_API_KEY", key)
+ if not key:
+ if warn and not _CARTO_KEY_WARNED:
+ print(
+ "CARTO basemaps now require an API key. Request a free key at "
+ "https://carto.com/basemaps/apikey and set it with "
+ "leafmap.set_api_key(key, 'CARTO_API_KEY') or the CARTO_API_KEY "
+ "environment variable. Without it, tiles show an "
+ "'API key required' watermark."
+ )
+ _CARTO_KEY_WARNED = True
+ return url
+
+ sep = "&" if "?" in url else "?"
+ return f"{url}{sep}key={quote(str(key), safe='')}"
+
+
+def is_carto_provider(provider: Any) -> bool:
+ """Checks whether an xyzservices TileProvider serves CARTO basemaps.
+
+ Args:
+ provider (Any): The xyzservices TileProvider (or dict) to check.
+
+ Returns:
+ True if the provider's URL is hosted on basemaps.cartocdn.com.
+ """
+ try:
+ return _is_carto_url(provider.get("url"))
+ except AttributeError:
+ return False
+
+
+def normalize_carto_provider(provider: Any) -> Any:
+ """Removes the API key placeholder from a CARTO xyzservices TileProvider.
+
+ xyzservices >= 2026.9.0 defines CARTO providers with a ``?key={apikey}``
+ URL template and a placeholder key, so they count as requiring a token.
+ Leafmap adds the real key when a layer is created (see
+ :func:`add_carto_api_key`), so the placeholder is stripped here.
+
+ Args:
+ provider (Any): The xyzservices TileProvider.
+
+ Returns:
+ A copy of the provider without the key template, or the provider
+ unchanged if it is not a CARTO provider.
+ """
+ import re
+
+ if not is_carto_provider(provider):
+ return provider
+ tile = xyzservices.TileProvider(dict(provider))
+ # Remove the key={apikey} pair and tidy the remaining query separators.
+ url = re.sub(r"([?&])key=\{apikey\}(&|$)", r"\1", tile["url"])
+ tile["url"] = re.sub(r"[?&]$", "", url)
+ tile.pop("apikey", None)
+ return tile
+
+
+def xyz_provider_url(provider: Any) -> str:
+ """Builds the tile URL of an xyzservices TileProvider.
+
+ CARTO providers get the ``CARTO_API_KEY`` key instead of the xyzservices
+ placeholder.
+
+ Args:
+ provider (Any): The xyzservices TileProvider.
+
+ Returns:
+ The tile URL.
+ """
+ return add_carto_api_key(normalize_carto_provider(provider).build_url())
+
+
def set_api_key(key: str, name: str = "GOOGLE_MAPS_API_KEY"):
"""Sets the Google Maps API key. You can generate one from https://bit.ly/3sw0THG.
@@ -9620,7 +9749,7 @@ def filter_date(
mask = (data[new_field] >= start_date) & (data[new_field] <= end_date)
result = data.loc[mask]
- return result.drop(columns=[new_field], axis=1)
+ return result.drop(columns=[new_field])
def skip_mkdocs_build():
@@ -9664,7 +9793,7 @@ def disjoint(input_features, selecting_features, output=None, **kwargs: Any) ->
input_features["savedindex"] = input_features.index
intersecting = selecting_features.sjoin(input_features, how="inner")["savedindex"]
results = input_features[~input_features.savedindex.isin(intersecting)].drop(
- columns=["savedindex"], axis=1
+ columns=["savedindex"]
)
if output is not None:
@@ -15454,6 +15583,38 @@ def check_url(url: str) -> bool:
return False
+def _geoparquet_crs(source: str, geometry: str = "geometry") -> Optional[Any]:
+ """Reads the CRS of a geometry column from GeoParquet file metadata.
+
+ Args:
+ source (str): The path or URL to a single GeoParquet file.
+ geometry (str, optional): The geometry column name. Defaults to "geometry".
+
+ Returns:
+ The CRS (a PROJJSON dict or "OGC:CRS84"), or None if the file has no
+ GeoParquet metadata or the CRS cannot be determined.
+ """
+ try:
+ import pyarrow.parquet as pq
+
+ if isinstance(source, str) and source.startswith(("http://", "https://")):
+ import fsspec
+
+ with fsspec.open(source, "rb") as f:
+ metadata = pq.read_schema(f).metadata
+ else:
+ metadata = pq.read_schema(source).metadata
+
+ geo = json.loads((metadata or {}).get(b"geo", b"{}"))
+ column = geo.get("columns", {}).get(geometry)
+ if column is None:
+ return None
+ # Per the GeoParquet spec, a missing "crs" key means OGC:CRS84.
+ return column.get("crs", "OGC:CRS84")
+ except Exception:
+ return None
+
+
def read_parquet(
source: str,
geometry: Optional[str] = None,
@@ -15480,7 +15641,10 @@ def read_parquet(
table_name (str, optional): The name of the table in the DuckDB database. Defaults to None.
sql (str, optional): The SQL query to execute. Defaults to None.
limit (int, optional): The maximum number of rows to return. Defaults to None (return all rows).
- src_crs (str, optional): The source CRS (Coordinate Reference System) of the geometries. Defaults to None.
+ src_crs (str, optional): The source CRS (Coordinate Reference System) of the geometries.
+ Defaults to None, which reads the CRS from the GeoParquet metadata of a single
+ file when no custom ``sql`` is given. Globs, directories, and custom ``sql``
+ queries get no CRS unless ``src_crs`` is set.
dst_crs (str, optional): The target CRS to reproject the geometries. Defaults to None.
return_type (str, optional): The type of object to return:
- 'gdf': GeoDataFrame (default)
@@ -15527,6 +15691,7 @@ def read_parquet(
columns = f"{columns} EXCLUDE {exclude}"
result = None
+ custom_sql = sql is not None
if return_type in ["df", "numpy", "arrow", "polars"]:
if sql is None:
sql = f"SELECT {columns} FROM '{source}'"
@@ -15560,6 +15725,8 @@ def read_parquet(
df = con.sql(sql, **kwargs).df()
if table_name is not None:
con.sql(f"CREATE OR REPLACE TABLE {table_name} AS FROM df", **kwargs)
+ if src_crs is None and not custom_sql:
+ src_crs = _geoparquet_crs(source, geometry)
result = df_to_gdf(df, geometry=geometry, src_crs=src_crs, dst_crs=dst_crs)
con.close()
@@ -19058,35 +19225,32 @@ def get_color_for_categorical(value: Any) -> Optional[str]:
def get_overture_latest_release(patch=False) -> str:
"""
- Retrieves the value of the 'latest' key from the Overture Maps release JSON file.
+ Retrieves the latest Overture Maps release from the Overture STAC catalog.
Args:
patch (bool): If True, returns the full version string (e.g., "2025-02-19.0").
+ Otherwise, returns the release date only (e.g., "2025-02-19").
Returns:
- The value of the 'latest' key from the releases.json file.
+ The latest release version.
Raises:
requests.RequestException: If there's an issue with the HTTP request.
KeyError: If the 'latest' key is not found in the JSON data.
json.JSONDecodeError: If the response cannot be parsed as JSON.
"""
- url = "https://labs.overturemaps.org/data/releases.json"
+ url = "https://stac.overturemaps.org/catalog.json"
try:
- response = requests.get(url)
+ response = requests.get(url, timeout=30)
response.raise_for_status() # Raise an exception for HTTP errors
- data = response.json()
- if patch:
- latest_release = data.get("latest")
- else:
- latest_release = data.get("latest").split(".")[
- 0
- ] # Extract the version number
-
+ latest_release = response.json().get("latest")
if latest_release is None:
- raise KeyError("The 'latest' key was not found in the releases.json file")
+ raise KeyError("The 'latest' key was not found in the STAC catalog")
+
+ if not patch:
+ latest_release = latest_release.split(".")[0]
return latest_release
@@ -19101,6 +19265,28 @@ def get_overture_latest_release(patch=False) -> str:
raise
+def get_overture_pmtiles_url(
+ theme: str = "buildings", release: Optional[str] = None
+) -> str:
+ """Get the URL of an Overture Maps PMTiles file for a theme.
+
+ Args:
+ theme (str): The Overture theme, e.g., "buildings", "places", "base",
+ "transportation", "divisions", or "addresses". Defaults to "buildings".
+ release (str, optional): The release version, e.g., "2025-02-19.0". A
+ release without a patch number (e.g., "2025-02-19") gets ".0"
+ appended. Defaults to None, which uses the latest release.
+
+ Returns:
+ The URL of the PMTiles file.
+ """
+ if release is None:
+ release = get_overture_latest_release(patch=True)
+ elif "." not in release:
+ release = f"{release}.0"
+ return f"https://tiles.overturemaps.org/{release}/{theme}.pmtiles"
+
+
def set_proj_lib_path(verbose=False):
"""
Set the PROJ_LIB and GDAL_DATA environment variables based on the current conda environment.
@@ -19222,7 +19408,6 @@ def read_vector(source, layer=None, **kwargs: Any):
import urllib.parse
- import fiona
import geopandas as gpd
# Determine if source is a URL or local file
@@ -19250,11 +19435,16 @@ def read_vector(source, layer=None, **kwargs: Any):
return gpd.read_file(source, layer=layer, **kwargs)
return gpd.read_file(source, **kwargs)
- # Try to use fiona to identify valid layers for formats that might have them
- # Only attempt this for local files as fiona.listlayers might not work with URLs
+ # Identify valid layers for formats that might have them
+ # Only attempt this for local files as listing layers might not work with URLs
if layer is None and ext in [".gpkg", ".gml"] and not is_url:
try:
- layers = fiona.listlayers(source)
+ if hasattr(gpd, "list_layers"): # geopandas >= 1.0
+ layers = list(gpd.list_layers(source)["name"])
+ else:
+ from pyogrio import list_layers
+
+ layers = [name for name, _ in list_layers(source)]
if layers:
return gpd.read_file(source, layer=layers[0], **kwargs)
except Exception:
diff --git a/leafmap/download.py b/leafmap/download.py
index c26f6ac25d..f1bc5e4cee 100644
--- a/leafmap/download.py
+++ b/leafmap/download.py
@@ -211,35 +211,32 @@ def json_serializable(obj: Any) -> Any:
def get_overture_latest_release(patch=True) -> str:
"""
- Retrieves the value of the 'latest' key from the Overture Maps release JSON file.
+ Retrieves the latest Overture Maps release from the Overture STAC catalog.
Args:
patch (bool): If True, returns the full version string (e.g., "2025-02-19.0").
+ Otherwise, returns the release date only (e.g., "2025-02-19").
Returns:
- str: The value of the 'latest' key from the releases.json file.
+ The latest release version.
Raises:
requests.RequestException: If there's an issue with the HTTP request.
KeyError: If the 'latest' key is not found in the JSON data.
json.JSONDecodeError: If the response cannot be parsed as JSON.
"""
- url = "https://labs.overturemaps.org/data/releases.json"
+ url = "https://stac.overturemaps.org/catalog.json"
try:
- response = requests.get(url)
+ response = requests.get(url, timeout=30)
response.raise_for_status() # Raise an exception for HTTP errors
- data = response.json()
- if patch:
- latest_release = data.get("latest")
- else:
- latest_release = data.get("latest").split(".")[
- 0
- ] # Extract the version number
-
+ latest_release = response.json().get("latest")
if latest_release is None:
- raise KeyError("The 'latest' key was not found in the releases.json file")
+ raise KeyError("The 'latest' key was not found in the STAC catalog")
+
+ if not patch:
+ latest_release = latest_release.split(".")[0]
return latest_release
diff --git a/leafmap/foliumap.py b/leafmap/foliumap.py
index 27c93b8b08..80acc4dfac 100644
--- a/leafmap/foliumap.py
+++ b/leafmap/foliumap.py
@@ -425,7 +425,7 @@ def add_basemap(
if isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
- url = basemap.build_url()
+ url = common.xyz_provider_url(basemap)
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
max_zoom = basemap["max_zoom"]
@@ -448,12 +448,26 @@ def add_basemap(
elif basemap in basemaps:
bmap = basemaps[basemap]
+ if isinstance(bmap, folium.TileLayer):
+ keyed_url = common.add_carto_api_key(bmap.tiles)
+ if keyed_url != bmap.tiles:
+ # Build a new layer so the key is not stored on the
+ # shared basemap object, and copy all of its options.
+ keyed_layer = folium.TileLayer(
+ tiles=keyed_url,
+ attr=bmap.options.get("attribution"),
+ name=bmap.layer_name,
+ overlay=bmap.overlay,
+ control=bmap.control,
+ )
+ keyed_layer.options = dict(bmap.options)
+ bmap = keyed_layer
bmap.show = show
bmap.add_to(self)
- if isinstance(basemaps[basemap], folium.TileLayer):
- url = basemaps[basemap].tiles
- elif isinstance(basemaps[basemap], folium.WmsTileLayer):
- url = basemaps[basemap].url
+ if isinstance(bmap, folium.TileLayer):
+ url = bmap.tiles
+ elif isinstance(bmap, folium.WmsTileLayer):
+ url = bmap.url
common.arc_add_layer(url, basemap)
else:
print(
@@ -2800,7 +2814,7 @@ def add_xyz_service(self, provider: str, **kwargs):
if provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
- url = xyz_provider.build_url()
+ url = common.xyz_provider_url(xyz_provider)
attribution = xyz_provider.attribution
if attribution.strip() == "":
attribution = " "
diff --git a/leafmap/leafmap.py b/leafmap/leafmap.py
index 66ceda977e..84416bff17 100644
--- a/leafmap/leafmap.py
+++ b/leafmap/leafmap.py
@@ -595,7 +595,7 @@ def add_basemap(self, basemap="HYBRID", show=True, **kwargs) -> None:
if isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
- url = basemap.build_url()
+ url = common.xyz_provider_url(basemap)
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
max_zoom = basemap["max_zoom"]
@@ -4978,7 +4978,7 @@ def add_xyz_service(self, provider: str, **kwargs) -> None:
if provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
- url = xyz_provider.build_url()
+ url = common.xyz_provider_url(xyz_provider)
attribution = xyz_provider.attribution
if attribution.strip() == "":
attribution = " "
@@ -8177,7 +8177,7 @@ def get_basemap(name: str):
basemap = basemaps[name]
if basemap["type"] == "xyz":
layer = TileLayer(
- url=basemap["url"],
+ url=common.add_carto_api_key(basemap["url"]),
name=basemap["name"],
max_zoom=24,
attribution=basemap["attribution"],
diff --git a/leafmap/maplibregl.py b/leafmap/maplibregl.py
index e39c611e0e..863bc57f45 100644
--- a/leafmap/maplibregl.py
+++ b/leafmap/maplibregl.py
@@ -177,7 +177,7 @@ def __init__(
]
if isinstance(style, str):
if style.startswith("http"):
- response = requests.get(style)
+ response = requests.get(common.add_carto_api_key(style, warn=False))
if response.status_code != 200:
print(
"The provided style URL is invalid. Falling back to 'dark-matter'."
@@ -217,6 +217,9 @@ def __init__(
if style in carto_basemaps:
style = construct_carto_basemap_url(style)
+ if isinstance(style, str):
+ style = common.add_carto_api_key(style, warn=False)
+
if style is not None:
kwargs["style"] = style
@@ -1459,7 +1462,7 @@ def add_basemap(
elif isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
- url = basemap.build_url()
+ url = common.xyz_provider_url(basemap)
if attribution is None:
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
@@ -1493,6 +1496,7 @@ def add_basemap(
)
return
+ url = common.add_carto_api_key(url)
raster_source = RasterTileSource(
tiles=[url],
attribution=attribution,
@@ -5823,10 +5827,7 @@ def add_overture_3d_buildings(
ValueError: If the length of values and colors lists are not the same.
"""
- if release is None:
- release = common.get_overture_latest_release()
-
- url = f"https://overturemaps-tiles-us-west-2-beta.s3.amazonaws.com/{release}/buildings.pmtiles"
+ url = common.get_overture_pmtiles_url("buildings", release)
if template == "simple":
template = "Name: {{@name}}
Subtype: {{subtype}}
Class: {{class}}
Height: {{height}}"
@@ -5916,8 +5917,10 @@ def add_overture_data(
"""Add Overture Maps data to the map.
Args:
- release (str, optional): The release date of the data. Defaults to
- "2024-12-28". For more info, see https://github.com/OvertureMaps/overture-tiles
+ release (str, optional): The release version of the data, e.g.,
+ "2026-10-21.0". Defaults to None, which uses the latest release.
+ Only recent releases are available. For more info, see
+ https://stac.overturemaps.org/catalog.json
theme (str, optional): The theme of the data. It can be one of the following:
"addresses", "base", "buildings", "divisions", "places", "transportation".
Defaults to "buildings".
@@ -5934,8 +5937,6 @@ def add_overture_data(
Raises:
ValueError: If the theme is not one of the allowed themes.
"""
- if release is None:
- release = common.get_overture_latest_release()
allowed_themes = [
"addresses",
@@ -6137,7 +6138,7 @@ def add_overture_data(
},
}
- url = f"https://overturemaps-tiles-us-west-2-beta.s3.amazonaws.com/{release}/{theme}.pmtiles"
+ url = common.get_overture_pmtiles_url(theme, release)
if style is None:
style = styles.get(theme, None)
self.add_pmtiles(
@@ -6164,8 +6165,10 @@ def add_overture_buildings(
"""Add Overture Maps data to the map.
Args:
- release (str, optional): The release date of the data. Defaults to
- "2024-12-18". For more info, see https://github.com/OvertureMaps/overture-tiles
+ release (str, optional): The release version of the data, e.g.,
+ "2026-10-21.0". Defaults to None, which uses the latest release.
+ Only recent releases are available. For more info, see
+ https://stac.overturemaps.org/catalog.json
style (Optional[Dict[str, Any]], optional): The style dictionary for
the data. Defaults to None.
type (str, optional): The type of the data. It can be "line" or "fill".
@@ -6177,10 +6180,7 @@ def add_overture_buildings(
data layer. Defaults to False.
**kwargs (Any): Additional keyword arguments for the paint properties.
"""
- if release is None:
- release = common.get_overture_latest_release()
-
- url = f"https://overturemaps-tiles-us-west-2-beta.s3.amazonaws.com/{release}/buildings.pmtiles"
+ url = common.get_overture_pmtiles_url("buildings", release)
kwargs = common.replace_underscores_in_keys(kwargs)
diff --git a/leafmap/stac.py b/leafmap/stac.py
index 1e5295694c..9345ec37c4 100644
--- a/leafmap/stac.py
+++ b/leafmap/stac.py
@@ -896,7 +896,7 @@ def cog_tile(
r = requests.get(
f"{titiler_endpoint}/cog/{TileMatrixSetId}/tilejson.json",
params=kwargs,
- timeout=10,
+ timeout=60,
).json()
except Exception as e:
print(e)
@@ -2874,7 +2874,7 @@ def maxar_search(
mask = (data[new_field] >= start_date) & (data[new_field] <= end_date)
result = data.loc[mask]
- return result.drop(columns=[new_field], axis=1)
+ return result.drop(columns=[new_field])
def maxar_collection_url(collection, dtype="geojson", raw=True) -> str:
diff --git a/leafmap/toolbar.py b/leafmap/toolbar.py
index 11f19fdb37..8cfa60f5a3 100644
--- a/leafmap/toolbar.py
+++ b/leafmap/toolbar.py
@@ -2316,7 +2316,7 @@ def providers_change(change):
elif provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
- url = xyz_provider.build_url()
+ url = xyz_provider_url(xyz_provider)
attribution = xyz_provider.attribution
m.layers = layers
if xyz_provider.requires_token():
@@ -3532,7 +3532,7 @@ def providers_change(change):
elif provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
- url = xyz_provider.build_url()
+ url = xyz_provider_url(xyz_provider)
attribution = xyz_provider.attribution
if xyz_provider.requires_token():
with output:
diff --git a/requirements.txt b/requirements.txt
index 274b6e60ad..551810b801 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -19,5 +19,5 @@ plotly
pystac-client
python-box
scooby
-whiteboxgui
+whiteboxgui>=2.3.1
xyzservices
diff --git a/tests/test_notebook_breakages.py b/tests/test_notebook_breakages.py
new file mode 100644
index 0000000000..64ca4a3fd5
--- /dev/null
+++ b/tests/test_notebook_breakages.py
@@ -0,0 +1,243 @@
+"""Regression tests for fixes to Overture URLs, date filtering, and read_vector."""
+
+import geopandas as gpd
+import pandas as pd
+from shapely.geometry import Point
+
+from leafmap import common
+
+
+def test_get_overture_pmtiles_url_adds_patch_number():
+ """A release without a patch number gets '.0' appended."""
+ url = common.get_overture_pmtiles_url("places", "2026-10-21")
+ assert url == "https://tiles.overturemaps.org/2026-10-21.0/places.pmtiles"
+
+
+def test_get_overture_pmtiles_url_keeps_full_release():
+ """A full release version is used as is."""
+ url = common.get_overture_pmtiles_url("buildings", "2026-09-23.1")
+ assert url == "https://tiles.overturemaps.org/2026-09-23.1/buildings.pmtiles"
+
+
+def test_filter_date_drops_temp_column():
+ """filter_date works with pandas versions that reject columns= plus axis=."""
+ df = pd.DataFrame({"date": ["2023-01-01", "2023-06-01", "2024-01-01"]})
+ result = common.filter_date(df, start_date="2023-03-01", end_date="2023-12-31")
+ assert list(result["date"]) == ["2023-06-01"]
+ assert "date_temp" not in result.columns
+
+
+def test_read_vector_gpkg_without_layer(tmp_path):
+ """read_vector picks the first layer of a GeoPackage without fiona."""
+ path = tmp_path / "points.gpkg"
+ gdf = gpd.GeoDataFrame({"id": [1, 2]}, geometry=[Point(0, 0), Point(1, 1)])
+ gdf.to_file(path, layer="pts", driver="GPKG")
+ result = common.read_vector(str(path))
+ assert len(result) == 2
+
+
+def test_add_carto_api_key_appends_key():
+ """CARTO URLs get the key appended with the right separator."""
+ tile = "https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(tile, key="abc") == tile + "?key=abc"
+ style = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json?foo=1"
+ assert common.add_carto_api_key(style, key="abc") == style + "&key=abc"
+
+
+def test_add_carto_api_key_leaves_other_urls(monkeypatch):
+ """Non-CARTO URLs and URLs that already have a key are unchanged."""
+ monkeypatch.setenv("CARTO_API_KEY", "abc")
+ osm = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(osm) == osm
+ keyed = "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=xyz"
+ assert common.add_carto_api_key(keyed) == keyed
+
+
+def test_add_carto_api_key_reads_env(monkeypatch):
+ """The key is read from the CARTO_API_KEY environment variable."""
+ monkeypatch.setenv("CARTO_API_KEY", "envkey")
+ url = "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(url).endswith("?key=envkey")
+
+
+def test_add_carto_api_key_without_key(monkeypatch):
+ """Without a key the URL is returned unchanged."""
+ monkeypatch.delenv("CARTO_API_KEY", raising=False)
+ url = "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(url, warn=False) == url
+
+
+def test_read_parquet_keeps_geoparquet_crs(tmp_path):
+ """read_parquet keeps the CRS stored in GeoParquet metadata."""
+ path = tmp_path / "projected.parquet"
+ gdf = gpd.GeoDataFrame(
+ {"id": [1]}, geometry=[Point(1620000, 1920000)], crs="EPSG:5070"
+ )
+ gdf.to_parquet(path)
+ result = common.read_parquet(str(path))
+ assert result.crs.to_epsg() == 5070
+
+
+def test_read_parquet_custom_sql_has_no_file_crs(tmp_path):
+ """A custom SQL query does not get the file's CRS assigned."""
+ path = tmp_path / "projected.parquet"
+ gdf = gpd.GeoDataFrame(
+ {"id": [1]}, geometry=[Point(1620000, 1920000)], crs="EPSG:5070"
+ )
+ gdf.to_parquet(path)
+ sql = f"SELECT id, ST_AsText(geometry) AS geometry FROM '{path}'"
+ result = common.read_parquet(str(path), sql=sql)
+ assert result.crs is None
+
+
+def test_add_carto_api_key_ignores_similar_params():
+ """Parameters such as apikey are not mistaken for an existing key."""
+ url = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json?apikey=1"
+ assert common.add_carto_api_key(url, key="abc") == url + "&key=abc"
+
+
+def test_add_carto_api_key_matches_host_only():
+ """The key is only added for CARTO hosts, not URLs that mention them."""
+ url = "https://example.com/tiles?u=basemaps.cartocdn.com"
+ assert common.add_carto_api_key(url, key="abc") == url
+ url = "https://basemaps.cartocdn.com.example.com/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(url, key="abc") == url
+
+
+def test_ipyleaflet_add_basemap_adds_carto_key(monkeypatch):
+ """ipyleaflet basemaps get the key, but other TileLayers are untouched."""
+ import ipyleaflet
+
+ from leafmap import leafmap as ipyl
+
+ monkeypatch.setenv("CARTO_API_KEY", "abc")
+ m = ipyl.Map()
+ m.add_basemap("CartoDB.Positron")
+ assert m.layers[-1].url.endswith("?key=abc")
+
+ url = "https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"
+ layer = ipyleaflet.TileLayer(url=url, name="custom")
+ m.add(layer)
+ assert layer.url == url
+
+
+def test_folium_add_basemap_does_not_mutate_shared_layer(monkeypatch):
+ """folium basemaps get the key without changing the shared basemap object."""
+ import leafmap.foliumap as fm
+
+ monkeypatch.setenv("CARTO_API_KEY", "abc")
+ shared = fm.basemaps["CartoDB.Positron"]
+ original = shared.tiles
+ m = fm.Map()
+ m.add_basemap("CartoDB.Positron")
+ assert shared.tiles == original
+ added = [
+ child
+ for child in m._children.values()
+ if getattr(child, "tiles", "").endswith("?key=abc")
+ ]
+ assert len(added) == 1
+ assert added[0] is not shared
+ assert added[0].get_name() != shared.get_name()
+ assert added[0].options == shared.options
+ assert "basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=abc" in (
+ m.get_root().render()
+ )
+
+
+def test_maplibre_style_url_gets_carto_key_before_fetch(monkeypatch):
+ """A user-supplied CARTO style URL is keyed before it is fetched."""
+ import leafmap.maplibregl as ml
+
+ monkeypatch.setenv("CARTO_API_KEY", "abc")
+ requested = []
+
+ class Response:
+ status_code = 200
+ text = '{"version": 8, "sources": {}, "layers": []}'
+
+ def fake_get(url, *args, **kwargs):
+ requested.append(url)
+ return Response()
+
+ monkeypatch.setattr(ml.requests, "get", fake_get)
+ ml.Map(style="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json")
+ assert requested[0].endswith("style.json?key=abc")
+
+
+def _new_style_carto_provider():
+ """Builds a CARTO provider the way xyzservices >= 2026.9.0 defines it."""
+ import xyzservices
+
+ return xyzservices.TileProvider(
+ name="CartoDB.Positron",
+ url="https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png?key={apikey}",
+ attribution="(C) OpenStreetMap contributors (C) CARTO",
+ subdomains="abcd",
+ max_zoom=20,
+ variant="light_all",
+ apikey="",
+ )
+
+
+def test_xyz_provider_url_replaces_carto_placeholder(monkeypatch):
+ """A CARTO provider with the xyzservices key placeholder gets the real key."""
+ monkeypatch.setenv("CARTO_API_KEY", "abc")
+ provider = _new_style_carto_provider()
+ assert provider.requires_token()
+ normalized = common.normalize_carto_provider(provider)
+ assert not normalized.requires_token()
+ assert "apikey" in provider # the original provider is not modified
+ url = common.xyz_provider_url(provider)
+ assert url == "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=abc"
+
+
+def test_get_xyz_dict_keeps_carto_providers():
+ """CARTO basemaps stay available even when xyzservices marks them as keyed."""
+ from leafmap.basemaps import get_xyz_dict
+
+ xyz_dict = get_xyz_dict()
+ assert "CartoDB.Positron" in xyz_dict
+ assert "{apikey}" not in xyz_dict["CartoDB.Positron"]["url"]
+
+
+def test_is_carto_provider_matches_host_only():
+ """Only providers hosted on basemaps.cartocdn.com count as CARTO."""
+ assert common.is_carto_provider(_new_style_carto_provider())
+ assert not common.is_carto_provider(
+ {"url": "https://example.com/?u=basemaps.cartocdn.com"}
+ )
+ assert not common.is_carto_provider({"url": None})
+
+
+def test_add_carto_api_key_encodes_key():
+ """Special characters in the key are URL-encoded."""
+ url = "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"
+ assert common.add_carto_api_key(url, key="a&b c") == url + "?key=a%26b%20c"
+
+
+def test_normalize_carto_provider_keeps_other_params():
+ """Removing the key placeholder keeps other query parameters valid."""
+ import xyzservices
+
+ base = {
+ "name": "C",
+ "attribution": "a",
+ "variant": "v",
+ "apikey": "",
+ }
+ prefix = "https://basemaps.cartocdn.com/{variant}/{z}/{x}/{y}.png"
+ cases = {
+ "?key={apikey}&other=1": "?other=1",
+ "?other=1&key={apikey}": "?other=1",
+ "?a=1&key={apikey}&b=2": "?a=1&b=2",
+ }
+ for query, expected in cases.items():
+ provider = xyzservices.TileProvider(url=prefix + query, **base)
+ assert common.normalize_carto_provider(provider)["url"] == prefix + expected
+
+
+def test_add_carto_api_key_respects_blank_key():
+ """An existing blank key parameter is not duplicated."""
+ url = "https://basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key="
+ assert common.add_carto_api_key(url, key="abc") == url