From 682484ba3c87a45b7a1a6f2a1260b990d32d81e0 Mon Sep 17 00:00:00 2001 From: t-kramer Date: Thu, 22 Oct 2026 10:34:45 -0700 Subject: [PATCH] fix: switch to vector basemaps --- app.py | 9 +++++- assets/carto_basemap.js | 50 ++++++++++++++++++++++++++++++ assets/img/carto-logo.svg | 6 ++++ pages/lib/basemap.py | 62 +++++++++++++++++++++++++++++++++++++ pages/lib/charts_summary.py | 2 +- pages/lib/utils.py | 36 ++++++++++++--------- pages/select.py | 19 +++++------- pages/summary.py | 13 ++++++-- pyproject.toml | 2 +- pytest.ini | 2 ++ tests/test_basemap.py | 58 ++++++++++++++++++++++++++++++++++ uv.lock | 10 +++--- 12 files changed, 231 insertions(+), 38 deletions(-) create mode 100644 assets/carto_basemap.js create mode 100644 assets/img/carto-logo.svg create mode 100644 pages/lib/basemap.py create mode 100644 pytest.ini create mode 100644 tests/test_basemap.py diff --git a/app.py b/app.py index fee1876d..3c489a61 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,8 @@ import dash_bootstrap_components as dbc from dash_extensions.enrich import DashProxy, ServersideOutputTransform -from flask import send_file +from flask import jsonify, send_file + +from pages.lib.basemap import CARTO_STYLE_ROUTE, keyed_style app = DashProxy( __name__, @@ -29,6 +31,11 @@ def serve_locations_geojson(): ) +@app.server.route(CARTO_STYLE_ROUTE) +def serve_carto_style(): + return jsonify(keyed_style()), {"Cache-Control": "public, max-age=86400"} + + app.index_string = """ diff --git a/assets/carto_basemap.js b/assets/carto_basemap.js new file mode 100644 index 00000000..59b1cf38 --- /dev/null +++ b/assets/carto_basemap.js @@ -0,0 +1,50 @@ +// Adds the CARTO vector basemap, drawn by MapLibre GL, to every Leaflet map +// whose container has the "carto-basemap" class (set via dl.Map(className=...)). +// MapLibre and its Leaflet plugin are only loaded once such a map is created. +// dash-leaflet's own "load" event fires before custom handlers are bound, +// so we use a Leaflet init hook instead. +(function () { + const MAPLIBRE = "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl"; + const PLUGIN = "https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-leaflet@0.0.22/leaflet-maplibre-gl.js"; + const STYLE = "/basemap/positron.json"; + const ATTRIBUTION = + '© OpenStreetMap' + + ' contributors © CARTO'; + let loading = null; + + function loadScript(src) { + return new Promise(function (resolve, reject) { + const script = document.createElement("script"); + script.src = src; + script.onload = resolve; + script.onerror = reject; + document.head.appendChild(script); + }); + } + + function loadMapLibre() { + if (!loading) { + const css = document.createElement("link"); + css.rel = "stylesheet"; + css.href = MAPLIBRE + ".css"; + document.head.appendChild(css); + loading = loadScript(MAPLIBRE + ".js").then(function () { + return loadScript(PLUGIN); + }); + } + return loading; + } + + if (!window.L) { + return; + } + L.Map.addInitHook(function () { + const map = this; + if (!map.getContainer().classList.contains("carto-basemap")) { + return; + } + loadMapLibre().then(function () { + L.maplibreGL({ style: STYLE, attribution: ATTRIBUTION }).addTo(map); + }); + }); +})(); diff --git a/assets/img/carto-logo.svg b/assets/img/carto-logo.svg new file mode 100644 index 00000000..d66ea614 --- /dev/null +++ b/assets/img/carto-logo.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/pages/lib/basemap.py b/pages/lib/basemap.py new file mode 100644 index 00000000..010cf006 --- /dev/null +++ b/pages/lib/basemap.py @@ -0,0 +1,62 @@ +"""CARTO vector basemap: a copy of the Positron style with our API key on every URL. + +CARTO requires the key on every style, tile, glyph and sprite request, but the +published style.json does not carry it. Both maps load the style from our own +route (see app.py), which serves the keyed copy built here. +""" + +import functools +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +import requests + +from config import AppConfig + +CARTO_STYLE_URL = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json" +# also hard-coded in assets/carto_basemap.js +CARTO_STYLE_ROUTE = "/basemap/positron.json" + + +def add_key(url: str, key: str) -> str: + """Append the key to a cartocdn.com URL, keeping {placeholders} intact.""" + if not key or "cartocdn.com" not in urlsplit(url).netloc: + return url + parts = urlsplit(url) + query = dict(parse_qsl(parts.query)) + query["key"] = key + return urlunsplit(parts._replace(query=urlencode(query, safe="{}"))) + + +def _fetch_json(url: str) -> dict: + response = requests.get(url, timeout=10) + response.raise_for_status() + return response.json() + + +def build_keyed_style(key: str, fetch=_fetch_json) -> dict: + """Return the Positron style with the key added to all CARTO URLs.""" + style = fetch(add_key(CARTO_STYLE_URL, key)) + if not key: + return style + + for name in ("sprite", "glyphs"): + if isinstance(style.get(name), str): + style[name] = add_key(style[name], key) + + for source in style.get("sources", {}).values(): + if "url" in source: + # inline the TileJSON so its tile URLs can carry the key too + tilejson = fetch(add_key(source.pop("url"), key)) + for field in ("tiles", "minzoom", "maxzoom", "attribution", "bounds"): + if field in tilejson: + source.setdefault(field, tilejson[field]) + if "tiles" in source: + source["tiles"] = [add_key(tile, key) for tile in source["tiles"]] + + return style + + +@functools.lru_cache(maxsize=1) +def keyed_style() -> dict: + """Keyed style, fetched from CARTO once per server process.""" + return build_keyed_style(AppConfig.CARTO_API_KEY) diff --git a/pages/lib/charts_summary.py b/pages/lib/charts_summary.py index 81100136..22e15b0b 100644 --- a/pages/lib/charts_summary.py +++ b/pages/lib/charts_summary.py @@ -22,7 +22,7 @@ def world_map(meta): } ) - fig = px.scatter_mapbox( + fig = px.scatter_map( lat_long_df, lat="Lat", lon="Long", diff --git a/pages/lib/utils.py b/pages/lib/utils.py index 474a233e..100475e2 100644 --- a/pages/lib/utils.py +++ b/pages/lib/utils.py @@ -8,29 +8,35 @@ from dash import html, dcc import dash_mantine_components as dmc -from config import AppConfig, UnitSystem +from config import UnitSystem +from pages.lib.basemap import CARTO_STYLE_ROUTE from pages.lib.global_scheme import fig_config, month_lst from pages.lib.global_variables import Variables, VariableInfo def apply_carto_basemap(fig): - """Apply the Carto Positron basemap, authenticated with our API key.""" - fig.update_layout( - mapbox_style="white-bg", - mapbox_layers=[ - { - "below": "traces", - "sourcetype": "raster", - "sourceattribution": "© OpenStreetMap contributors, © CARTO", - "source": [ - f"https://basemaps.cartocdn.com/rastertiles/light_all/{{z}}/{{x}}/{{y}}.png?key={AppConfig.CARTO_API_KEY}" - ], - } - ], - ) + """Apply the Carto Positron vector basemap, served with our API key.""" + fig.update_layout(map_style=CARTO_STYLE_ROUTE) return fig +def carto_logo_badge(): + """CARTO logo linked to carto.com, overlaid on the bottom left of a map.""" + return html.A( + html.Img(src="/assets/img/carto-logo.svg", alt="CARTO", height=20), + href="https://carto.com/", + target="_blank", + rel="noopener", + style={ + "position": "absolute", + "bottom": 8, + "left": 8, + "zIndex": 1000, + "lineHeight": 0, + }, + ) + + def code_timer(func): """Print the runtime of the decorated function""" diff --git a/pages/select.py b/pages/select.py index ba0b923d..41850d46 100644 --- a/pages/select.py +++ b/pages/select.py @@ -13,8 +13,8 @@ from pages.lib.extract_df import create_df, get_data, get_location_info from pages.lib.global_variables import Variables from pages.lib.global_element_ids import ElementIds -from config import AppConfig, PageUrls, PageInfo -from pages.lib.utils import get_default_global_filter_store_data +from config import PageUrls, PageInfo +from pages.lib.utils import carto_logo_badge, get_default_global_filter_store_data dash.register_page( __name__, @@ -99,18 +99,12 @@ def layout(): id="map-container", center=[20, 0], zoom=2, + minZoom=2, + maxBounds=[[-85, -180], [85, 180]], + maxBoundsViscosity=1, style={"height": "650px", "width": "100%"}, + className="carto-basemap", # see assets/carto_basemap.js children=[ - dl.TileLayer( - url=( - "https://basemaps.cartocdn.com/rastertiles/light_all" - f"/{{z}}/{{x}}/{{y}}{{r}}.png?key={AppConfig.CARTO_API_KEY}" - ), - attribution=( - '© OpenStreetMap' - ' contributors © CARTO' - ), - ), dl.GeoJSON( id=ElementIds.TAB_ONE_MAP, url=_GEO_URL, @@ -121,6 +115,7 @@ def layout(): ), ], ), + carto_logo_badge(), dmc.Autocomplete( id=ElementIds.TAB_ONE_MAP_SEARCH, placeholder="Search city or station...", diff --git a/pages/summary.py b/pages/summary.py index a900b16e..dd72f1ce 100644 --- a/pages/summary.py +++ b/pages/summary.py @@ -16,6 +16,7 @@ from pages.lib.global_id_buttons import IdButtons from pages.lib.global_tab_names import TabNames from pages.lib.utils import ( + carto_logo_badge, generate_chart_name, generate_units, generate_units_degree, @@ -225,9 +226,15 @@ def update_layout(si_ip): ) def update_map(meta): """Update the contents of tab two. Passing in the general info (df, meta).""" - return dcc.Graph( - config=generate_chart_name(TabNames.MAP, meta), - figure=world_map(meta), + return dmc.Box( + pos="relative", + children=[ + dcc.Graph( + config=generate_chart_name(TabNames.MAP, meta), + figure=world_map(meta), + ), + carto_logo_badge(), + ], ) diff --git a/pyproject.toml b/pyproject.toml index c319c8da..0afb65f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "kgcpy==1.1.8", "numpy==1.26.3", "pandas==2.2.0", - "plotly==5.18.0", + "plotly==5.24.1", "pvlib==0.9.1", "pythermalcomfort==2.9.1", "requests==2.32.4", diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 00000000..a635c5c0 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . diff --git a/tests/test_basemap.py b/tests/test_basemap.py new file mode 100644 index 00000000..289bb6f5 --- /dev/null +++ b/tests/test_basemap.py @@ -0,0 +1,58 @@ +from pages.lib.basemap import CARTO_STYLE_URL, add_key, build_keyed_style + +TILES = "https://tiles.basemaps.cartocdn.com/v/1/vectortiles/carto.streets/v2/{z}/{x}/{y}.mvt" + + +def fake_fetch(responses): + """Return a fetch stub that serves canned JSON by URL (ignoring the query).""" + + def fetch(url): + return responses[url.split("?")[0]] + + return fetch + + +def style(**sources): + return { + "sprite": "https://tiles.basemaps.cartocdn.com/v/1/gl/positron-gl-style/sprite", + "glyphs": "https://tiles.basemaps.cartocdn.com/v/1/fonts/{fontstack}/{range}.pbf", + "sources": sources, + "layers": [], + } + + +def test_add_key_keeps_placeholders_and_skips_other_hosts(): + assert add_key(TILES, "K") == TILES + "?key=K" + assert add_key("https://example.com/a.json", "K") == "https://example.com/a.json" + assert add_key(TILES, "") == TILES + + +def test_key_added_to_sprite_glyphs_and_tiles(): + fetch = fake_fetch({CARTO_STYLE_URL: style(streets={"tiles": [TILES]})}) + result = build_keyed_style("K", fetch) + + assert result["sprite"].endswith("/sprite?key=K") + assert result["glyphs"].endswith("/{fontstack}/{range}.pbf?key=K") + assert result["sources"]["streets"]["tiles"] == [TILES + "?key=K"] + + +def test_tilejson_source_is_inlined_with_key(): + tilejson_url = "https://tiles.basemaps.cartocdn.com/tiles.json" + fetch = fake_fetch( + { + CARTO_STYLE_URL: style(streets={"type": "vector", "url": tilejson_url}), + tilejson_url: {"tiles": [TILES], "maxzoom": 14}, + } + ) + source = build_keyed_style("K", fetch)["sources"]["streets"] + + assert "url" not in source + assert source["tiles"] == [TILES + "?key=K"] + assert source["maxzoom"] == 14 + + +def test_no_key_returns_style_unchanged(): + original = style(streets={"tiles": [TILES]}) + fetch = fake_fetch({CARTO_STYLE_URL: original}) + + assert build_keyed_style("", fetch) == style(streets={"tiles": [TILES]}) diff --git a/uv.lock b/uv.lock index 8fd97b23..9cff5ee9 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.12'", @@ -308,7 +308,7 @@ requires-dist = [ { name = "kgcpy", specifier = "==1.1.8" }, { name = "numpy", specifier = "==1.26.3" }, { name = "pandas", specifier = "==2.2.0" }, - { name = "plotly", specifier = "==5.18.0" }, + { name = "plotly", specifier = "==5.24.1" }, { name = "pvlib", specifier = "==0.9.1" }, { name = "pythermalcomfort", specifier = "==2.9.1" }, { name = "requests", specifier = "==2.32.4" }, @@ -1114,15 +1114,15 @@ wheels = [ [[package]] name = "plotly" -version = "5.18.0" +version = "5.24.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "packaging" }, { name = "tenacity" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0d/17/ba496e60f95020227a15f73965a64ea3f176cae7faed2d9302a14524b681/plotly-5.18.0.tar.gz", hash = "sha256:360a31e6fbb49d12b007036eb6929521343d6bee2236f8459915821baefa2cbb", size = 7824864, upload-time = "2023-10-25T19:43:45.508Z" } +sdist = { url = "https://files.pythonhosted.org/packages/79/4f/428f6d959818d7425a94c190a6b26fbc58035cbef40bf249be0b62a9aedd/plotly-5.24.1.tar.gz", hash = "sha256:dbc8ac8339d248a4bcc36e08a5659bacfe1b079390b8953533f4eb22169b4bae", size = 9479398, upload-time = "2024-09-12T15:36:31.068Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/07/72953cf70e3bd3a24cbc3e743e6f8539abe6e3e6d83c3c0c83426eaffd39/plotly-5.18.0-py3-none-any.whl", hash = "sha256:23aa8ea2f4fb364a20d34ad38235524bd9d691bf5299e800bca608c31e8db8de", size = 15643397, upload-time = "2023-10-25T19:43:41.643Z" }, + { url = "https://files.pythonhosted.org/packages/e5/ae/580600f441f6fc05218bd6c9d5794f4aef072a7d9093b291f1c50a9db8bc/plotly-5.24.1-py3-none-any.whl", hash = "sha256:f67073a1e637eb0dc3e46324d9d51e2fe76e9727c892dde64ddf1e1b51f29089", size = 19054220, upload-time = "2024-09-12T15:36:24.08Z" }, ] [[package]]