From 046a56d609b464ce180838df5b6c63f50f0c5380 Mon Sep 17 00:00:00 2001 From: Parker Hornstein Date: Fri, 30 Oct 2026 09:41:30 -0500 Subject: [PATCH] Add native vector basemap support --- CHANGELOG.md | 3 + crates/ot-server/src/auth/api.rs | 49 ++++++++++- crates/ot-server/src/basemap.rs | 117 +++++++++++++++++-------- crates/ot-server/src/settings_api.rs | 22 ++++- docs/guides/admin.md | 14 +-- ui/src/App.tsx | 6 +- ui/src/api/client.ts | 4 +- ui/src/lib/basemap.ts | 14 +-- ui/src/pages/settings/SettingsPage.tsx | 42 ++++++--- ui/src/pages/trackdb/TrackMap.tsx | 92 +++++++++++++++++-- 10 files changed, 291 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fdf5495..a155d95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Added +- **Vector basemap tiles.** Settings → General → **Basemap tiles** accepts either raster XYZ + images or Mapbox vector tiles (MVT/PBF). Vector tiles are proxied through OpenTrack like raster + tiles and drawn with the built-in OpenMapTiles-compatible style. - **Sources are flows.** A source's editor is a workspace: the step list on the left, the source's steps placed and connected by hand, each clicked open for its settings and samples. After the input (transport and codec) come Reject, Map, Filter, Entity links, Affiliation, Tracker and diff --git a/crates/ot-server/src/auth/api.rs b/crates/ot-server/src/auth/api.rs index b84bc31..554eba1 100644 --- a/crates/ot-server/src/auth/api.rs +++ b/crates/ot-server/src/auth/api.rs @@ -2320,8 +2320,8 @@ mod tests { } /// A stand-in tile server on 127.0.0.1: `/t/{z}/{x}/{y}` answers by - /// zoom (5: HTML, 6: 404, 7: 500, 8: too big, 9: a redirect), else a - /// "PNG" naming what it was asked for. + /// zoom (4: gzipped MVT, 5: HTML, 6: 404, 7: 500, 8: too big, 9: a + /// redirect), else a "PNG" naming what it was asked for. async fn tile_server() -> std::net::SocketAddr { use axum::extract::RawQuery; async fn t( @@ -2331,6 +2331,14 @@ mod tests { ) -> Response { let png = [(axum::http::header::CONTENT_TYPE, "image/png")]; match z { + 4 => ( + [ + (axum::http::header::CONTENT_TYPE, "application/x-protobuf"), + (axum::http::header::CONTENT_ENCODING, "gzip"), + ], + vec![0x1f, 0x8b, 0x08, 0x00], + ) + .into_response(), 5 => ([(axum::http::header::CONTENT_TYPE, "text/html")], "").into_response(), 6 => StatusCode::NOT_FOUND.into_response(), 7 => StatusCode::INTERNAL_SERVER_ERROR.into_response(), @@ -2495,6 +2503,43 @@ mod tests { assert_eq!(h["cache-control"], "private, max-age=86400"); assert_eq!(h["x-content-type-options"], "nosniff"); assert!(!h.contains_key("pragma")); + + // Vector tiles use the same authenticated proxy. Their protobuf media + // type and gzip encoding reach MapLibre intact, while an image is + // rejected when the saved representation says vector. + let (st, body, _) = call( + &app, + "PUT", + "/api/v1/settings", + Some(&admin), + Some(json!({ + "basemap_tiles_url": url, + "basemap_tiles_format": "vector" + })), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(body["settings"]["basemap_tiles_format"], "vector"); + let (st, h, body) = get_raw(&app, "/api/v1/basemap/4/0/0", Some(&viewer)).await; + assert_eq!(st, StatusCode::OK, "{body:?}"); + assert_eq!(h["content-type"], "application/x-protobuf"); + assert_eq!(h["content-encoding"], "gzip"); + assert_eq!(body.as_ref(), &[0x1f, 0x8b, 0x08, 0x00]); + let (st, ..) = get_raw(&app, "/api/v1/basemap/3/2/1", Some(&viewer)).await; + assert_eq!(st, StatusCode::BAD_GATEWAY); + + let (st, body, _) = call( + &app, + "PUT", + "/api/v1/settings", + Some(&admin), + Some(json!({ + "basemap_tiles_url": url, + "basemap_tiles_format": "raster" + })), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); // Signed in only. let (st, ..) = get_raw(&app, "/api/v1/basemap/3/2/1", None).await; assert_eq!(st, StatusCode::UNAUTHORIZED); diff --git a/crates/ot-server/src/basemap.rs b/crates/ot-server/src/basemap.rs index 1a4b795..13b2124 100644 --- a/crates/ot-server/src/basemap.rs +++ b/crates/ot-server/src/basemap.rs @@ -1,5 +1,5 @@ -//! The maps' basemap: raster tiles from the XYZ tile server the settings -//! name (`basemap_tiles_url`), fetched by this server for the browser. The +//! The maps' basemap: raster or vector tiles from the XYZ tile server the +//! settings name (`basemap_tiles_url`), fetched by this server for the browser. The //! page's content security policy stays `'self'`, browsers need no route to //! the tile server, and a key in its URL never leaves this server. Nothing //! is cached here: the browser keeps each tile for a day. @@ -8,13 +8,14 @@ use std::sync::OnceLock; use std::time::Duration; use axum::Router; +use axum::body::Body; use axum::extract::{Path, State}; -use axum::http::{HeaderValue, StatusCode, header}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; use axum::routing::get; use crate::control::{ApiError, AppState}; -use crate::settings_api::fill_tile_url; +use crate::settings_api::{BasemapTilesFormat, fill_tile_url}; pub fn routes() -> Router { Router::new().route("/basemap/{z}/{x}/{y}", get(tile)) @@ -28,6 +29,11 @@ pub const MAX_TILE_BYTES: usize = 4 * 1024 * 1024; pub const CACHE_CONTROL: &str = "private, max-age=86400"; const TIMEOUT: Duration = Duration::from_secs(10); const IMAGE_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/avif"]; +const VECTOR_TYPES: &[&str] = &[ + "application/x-protobuf", + "application/vnd.mapbox-vector-tile", + "application/protobuf", +]; /// One client for every tile: no redirects (a tile server that moves is /// set anew), a 10 s limit, and this build's name. @@ -68,16 +74,21 @@ fn coordinates(z: &str, x: &str, y: &str) -> Result<(u32, u64, u64), ApiError> { Ok((z, at(x, "x")?, at(y, "y")?)) } -/// The tile's media type, when it is an image type a map draws. -fn image_type(v: Option<&HeaderValue>) -> Option<&'static str> { +/// The tile's supported media type for the configured representation. +fn tile_type(v: Option<&HeaderValue>, format: BasemapTilesFormat) -> Option<&'static str> { let t = v?.to_str().ok()?; let t = t.split(';').next()?.trim().to_ascii_lowercase(); - IMAGE_TYPES.iter().copied().find(|i| *i == t) + let supported = match format { + BasemapTilesFormat::Raster => IMAGE_TYPES, + BasemapTilesFormat::Vector => VECTOR_TYPES, + }; + supported.iter().copied().find(|i| *i == t) } /// `GET /basemap/{z}/{x}/{y}`: the tile, from the tile server. 404 when no /// tile URL is set or the tile server has no such tile (open ocean, say); -/// 502 when it fails or answers with anything but an image. +/// 502 when it fails or answers with a media type that does not match the +/// configured raster or vector representation. async fn tile( State(s): State, Path((z, x, y)): Path<(String, String, String)>, @@ -88,6 +99,13 @@ async fn tile( if template.is_empty() { return Err(ApiError::not_found("no basemap tiles are set")); } + let format = serde_json::from_value( + saved + .get("basemap_tiles_format") + .cloned() + .unwrap_or_else(|| serde_json::json!("raster")), + ) + .unwrap_or_default(); let url = fill_tile_url(template, z, x, y); // Logged by host only: the URL may carry a key. let host = reqwest::Url::parse(&url) @@ -129,9 +147,21 @@ async fn tile( if !status.is_success() { return Ok(fail(&format!("answered {}", status.as_u16()), Some(status))); } - let Some(kind) = image_type(res.headers().get(header::CONTENT_TYPE)) else { - return Ok(fail("not a PNG, JPEG, WebP or AVIF image", Some(status))); + let Some(kind) = tile_type(res.headers().get(header::CONTENT_TYPE), format) else { + let wanted = match format { + BasemapTilesFormat::Raster => "not a PNG, JPEG, WebP or AVIF image", + BasemapTilesFormat::Vector => "not a Mapbox vector tile", + }; + return Ok(fail(wanted, Some(status))); }; + // PMTiles and most vector tile servers store MVT payloads gzipped. reqwest + // does not decompress them in this build, so preserve the encoding for + // MapLibre rather than handing it compressed bytes without the header. + let content_encoding = res + .headers() + .get(header::CONTENT_ENCODING) + .filter(|v| v.as_bytes().eq_ignore_ascii_case(b"gzip")) + .cloned(); if res .content_length() .is_some_and(|n| n > MAX_TILE_BYTES as u64) @@ -158,22 +188,20 @@ async fn tile( } } } - Ok(( - StatusCode::OK, - [ - (header::CONTENT_TYPE, HeaderValue::from_static(kind)), - ( - header::CACHE_CONTROL, - HeaderValue::from_static(CACHE_CONTROL), - ), - ( - header::X_CONTENT_TYPE_OPTIONS, - HeaderValue::from_static("nosniff"), - ), - ], - body, - ) - .into_response()) + let mut headers = HeaderMap::new(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(kind)); + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static(CACHE_CONTROL), + ); + headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + if let Some(encoding) = content_encoding { + headers.insert(header::CONTENT_ENCODING, encoding); + } + Ok((StatusCode::OK, headers, Body::from(body)).into_response()) } #[cfg(test)] @@ -201,14 +229,33 @@ mod tests { } #[test] - fn only_image_types_pass() { - let t = |s: &str| image_type(Some(&HeaderValue::from_str(s).unwrap())); - assert_eq!(t("image/png"), Some("image/png")); - assert_eq!(t("Image/JPEG; charset=binary"), Some("image/jpeg")); - assert_eq!(t("image/webp"), Some("image/webp")); - assert_eq!(t("image/avif"), Some("image/avif")); - assert_eq!(t("image/svg+xml"), None); - assert_eq!(t("text/html"), None); - assert_eq!(image_type(None), None); + fn only_configured_tile_types_pass() { + let t = |s: &str, format| tile_type(Some(&HeaderValue::from_str(s).unwrap()), format); + assert_eq!( + t("image/png", BasemapTilesFormat::Raster), + Some("image/png") + ); + assert_eq!( + t("Image/JPEG; charset=binary", BasemapTilesFormat::Raster), + Some("image/jpeg") + ); + assert_eq!( + t("application/x-protobuf", BasemapTilesFormat::Vector), + Some("application/x-protobuf") + ); + assert_eq!( + t( + "application/vnd.mapbox-vector-tile", + BasemapTilesFormat::Vector + ), + Some("application/vnd.mapbox-vector-tile") + ); + assert_eq!(t("image/png", BasemapTilesFormat::Vector), None); + assert_eq!( + t("application/x-protobuf", BasemapTilesFormat::Raster), + None + ); + assert_eq!(t("text/html", BasemapTilesFormat::Raster), None); + assert_eq!(tile_type(None, BasemapTilesFormat::Raster), None); } } diff --git a/crates/ot-server/src/settings_api.rs b/crates/ot-server/src/settings_api.rs index e899023..33a0468 100644 --- a/crates/ot-server/src/settings_api.rs +++ b/crates/ot-server/src/settings_api.rs @@ -43,14 +43,25 @@ pub struct AppSettings { pub history_interval_secs: Option, /// Sharing the picture with other OpenTrack nodes. pub sync: SyncSettings, - /// An XYZ raster tile URL template (`{z}`, `{x}`, `{y}`) for the maps' - /// basemap, fetched through this server (`crate::basemap`); empty: the - /// built-in country outlines. It may carry a key: only admins read it. + /// An XYZ tile URL template (`{z}`, `{x}`, `{y}`) for the maps' basemap, + /// fetched through this server (`crate::basemap`); empty: the built-in + /// country outlines. It may carry a key: only admins read it. pub basemap_tiles_url: String, + /// Whether the XYZ endpoint returns raster images or Mapbox vector tiles. + pub basemap_tiles_format: BasemapTilesFormat, /// Cursor-on-Target outputs to TAK (the `cot` role). pub tak: crate::cot::settings::TakSettings, } +/// The representation returned by the configured XYZ basemap endpoint. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BasemapTilesFormat { + #[default] + Raster, + Vector, +} + /// Sharing the picture with other nodes (see `docs/multi-node.md`). #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -599,6 +610,11 @@ mod tests { // Checked as part of the settings, and an old document loads. let old: AppSettings = serde_json::from_value(json!({"site_name": "x"})).unwrap(); assert_eq!(old.basemap_tiles_url, ""); + assert_eq!(old.basemap_tiles_format, BasemapTilesFormat::Raster); + assert_eq!( + serde_json::to_value(BasemapTilesFormat::Vector).unwrap(), + json!("vector") + ); let bad = AppSettings { basemap_tiles_url: "https://t.example/{z}".into(), ..AppSettings::default() diff --git a/docs/guides/admin.md b/docs/guides/admin.md index f718693..8addb19 100644 --- a/docs/guides/admin.md +++ b/docs/guides/admin.md @@ -909,12 +909,16 @@ them all. ### Basemap tiles The maps (Track Management and the source preview) draw the built-in country outlines, which need -nothing from outside. For a full map instead, give **Settings → General → Basemap tiles** the URL -of an XYZ raster tile server, such as `https://tiles.example/{z}/{x}/{y}.png`: +nothing from outside. For a full map instead, choose **Raster image** or **Vector (MVT/PBF)** in +**Settings → General → Basemap tiles** and give the URL of an XYZ tile server, such as +`https://tiles.example/{z}/{x}/{y}.png` or +`http://tiles.internal/map/{z}/{x}/{y}.mvt`: - An absolute `http` or `https` URL of up to 2048 characters with `{z}`, `{x}` and `{y}` in it. No other placeholders: `{s}` (a choice of subdomains) is refused, so give one host. No `user:pass@`; a key the tile server takes can go in the query, e.g. `?key=...`. -- The tiles are PNG, JPEG, WebP or AVIF, up to 4 MiB each. Empty turns tiles off. +- Raster tiles are PNG, JPEG, WebP or AVIF. Vector tiles use the Mapbox vector tile protobuf media + type and may be gzip encoded. Each tile may be up to 4 MiB. Empty turns tiles off. The built-in + vector style targets the OpenMapTiles layer schema. **OpenTrack fetches the tiles for the browser** (`GET /api/v1/basemap/{z}/{x}/{y}`, any signed-in account), so: @@ -924,8 +928,8 @@ account), so: else sees whether tiles are on, and the decision log records only that it was set. A tile the server doesn't have (open ocean, say) is left empty; a tile server that fails, is slow -(10 s), redirects or sends anything but an image gives that tile a 502, logged with the server's -host and status. +(10 s), redirects or sends a media type that does not match the chosen format gives that tile a +502, logged with the server's host and status. **Tiles are not cached on the OpenTrack server.** Each browser keeps a tile for a day, so a room of operators still makes one request per tile per browser. diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 6658c59..af995c3 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -2,7 +2,7 @@ import { lazy, Suspense, useCallback, useEffect, useState } from 'react' import { TbMoon, TbSun } from 'react-icons/tb' import { Badge, Button, DockProvider, PageHeader, Tabs, useTheme } from '@kineticlogic/staresdk' import { api, type Banner, type ServerStatus } from './api/client' -import { BasemapCtx } from './lib/basemap' +import { BasemapCtx, type BasemapTilesFormat } from './lib/basemap' import { useHashView } from './lib/hashView' import { OverviewPage } from './pages/OverviewPage' import { UserChip } from './auth/UserChip' @@ -52,7 +52,7 @@ export default function App() { }, []) // Site name, classification banner and whether the maps have basemap tiles (Settings), this instance's own. const [siteName, setSiteName] = useState('') - const [basemapTiles, setBasemapTiles] = useState(false) + const [basemapTiles, setBasemapTiles] = useState(null) const [banner, setBanner] = useState(null) const [settingsRev, setSettingsRev] = useState(0) useEffect(() => { @@ -60,7 +60,7 @@ export default function App() { api.appSettings().then( (r) => { setSiteName(r.settings.site_name) - setBasemapTiles(r.basemap_tiles === true) + setBasemapTiles(r.basemap_tiles === true ? (r.settings.basemap_tiles_format ?? 'raster') : null) }, () => {}, ) diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts index 18e1f64..1b2819b 100644 --- a/ui/src/api/client.ts +++ b/ui/src/api/client.ts @@ -473,8 +473,10 @@ export interface AppSettings { history_interval_secs?: number | null /** Sharing the picture with other OpenTrack nodes. */ sync?: SyncSettings - /** XYZ raster tile URL template for the maps' basemap (empty: the country outlines). Admins only: empty for anyone else. */ + /** XYZ tile URL template for the maps' basemap (empty: the country outlines). Admins only: empty for anyone else. */ basemap_tiles_url?: string + /** Representation returned by the XYZ endpoint (old settings default to raster). */ + basemap_tiles_format?: 'raster' | 'vector' /** Cursor-on-Target outputs to TAK (the cot role). */ tak?: TakSettings } diff --git a/ui/src/lib/basemap.ts b/ui/src/lib/basemap.ts index c83ac1e..38d9cc3 100644 --- a/ui/src/lib/basemap.ts +++ b/ui/src/lib/basemap.ts @@ -1,13 +1,17 @@ import { createContext, useContext } from 'react' import type { MapTiles } from '@kineticlogic/staresdk/map-view' +export type BasemapTilesFormat = 'raster' | 'vector' +export type BasemapTiles = MapTiles & { format: BasemapTilesFormat } + /** The maps' basemap tiles, fetched through OpenTrack (Settings → General: Basemap tiles). */ -export const BASEMAP_TILES: MapTiles = { url: '/api/v1/basemap/{z}/{x}/{y}', maxZoom: 19 } +const BASEMAP_TILES: MapTiles = { url: '/api/v1/basemap/{z}/{x}/{y}', maxZoom: 19 } -/** Whether basemap tiles are on, from the settings the header already loads. */ -export const BasemapCtx = createContext(false) +/** The active basemap representation, from the settings the header already loads. */ +export const BasemapCtx = createContext(null) /** The `tiles` prop for a MapView: the proxied tiles when they are on, else none (the outlines). */ -export function useBasemapTiles(): MapTiles | undefined { - return useContext(BasemapCtx) ? BASEMAP_TILES : undefined +export function useBasemapTiles(): BasemapTiles | undefined { + const format = useContext(BasemapCtx) + return format ? { ...BASEMAP_TILES, format } : undefined } diff --git a/ui/src/pages/settings/SettingsPage.tsx b/ui/src/pages/settings/SettingsPage.tsx index bca9cb9..d643457 100644 --- a/ui/src/pages/settings/SettingsPage.tsx +++ b/ui/src/pages/settings/SettingsPage.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react' import { TbDownload, TbTrash, TbUpload } from 'react-icons/tb' -import { Badge, Button, CollapsiblePanel, FileDropZone, Input, Label, Modal, SaveButton, Toggle, useToast } from '@kineticlogic/staresdk' +import { Badge, Button, CollapsiblePanel, FileDropZone, Input, Label, Modal, SaveButton, Select, Toggle, useToast } from '@kineticlogic/staresdk' import { api, type AppSettings, type AppSettingsResponse, type ConfigImportStatus } from '../../api/client' import { InfoTip } from '../../components/InfoTip' import { NodesPanel } from './NodesPanel' @@ -39,7 +39,12 @@ const CONFIG_IMPORT_INFO = 'imported accounts replace the first admin, so you sign in again with one of them.' const BASEMAP_HINT = - 'An XYZ tile URL, such as https://tiles.example/{z}/{x}/{y}.png. OpenTrack fetches the tiles for the browser. Empty: the built-in country outlines.' + 'An XYZ raster image or Mapbox vector tile URL. OpenTrack fetches the tiles for the browser. Empty: the built-in country outlines.' + +const BASEMAP_FORMATS = [ + { value: 'raster', label: 'Raster image' }, + { value: 'vector', label: 'Vector (MVT/PBF)' }, +] function Row({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) { return ( @@ -194,17 +199,32 @@ export default function SettingsPage({ onSaved }: { onSaved: () => void }) { {admin ? ( - setDraft({ ...draft, basemap_tiles_url: e.target.value })} - /> +
+ setDraft({ ...draft, basemap_tiles_url: e.target.value })} + /> +
) : ( - {loaded.basemap_tiles ? 'on' : 'off'} + {loaded.basemap_tiles ? `${loaded.settings.basemap_tiles_format ?? 'raster'} tiles` : 'off'} )}
diff --git a/ui/src/pages/trackdb/TrackMap.tsx b/ui/src/pages/trackdb/TrackMap.tsx index 5083bd5..bc03c20 100644 --- a/ui/src/pages/trackdb/TrackMap.tsx +++ b/ui/src/pages/trackdb/TrackMap.tsx @@ -1,8 +1,9 @@ import { useEffect, useEffectEvent, useRef, useState, type CSSProperties } from 'react' import { TbAdjustmentsHorizontal, TbMap, TbMapOff } from 'react-icons/tb' -import { AttributionControl, Map as MapLibreMap, Popup, type GeoJSONSource } from 'maplibre-gl' +import { AttributionControl, Map as MapLibreMap, Popup, type ExpressionSpecification, type GeoJSONSource, type LayerSpecification, type SymbolLayerSpecification } from 'maplibre-gl' import { Button, ButtonPalette, Label, Select, Slider, themeFor, Toggle, useTheme } from '@kineticlogic/staresdk' import { EVIDENCE_COLOR, UNCERTAINTY_COLOR } from '../../lib/palette' +import type { BasemapTiles } from '../../lib/basemap' import { coordinateBounds, linesToGeoJSON, @@ -11,7 +12,6 @@ import { type MapFitTo, type MapLine, type MapPoint, - type MapTiles, } from '@kineticlogic/staresdk/map-view' type MarkerSize = 'compact' | 'standard' | 'large' @@ -40,7 +40,7 @@ interface TrackMapProps { selectedId?: string | null onSelect?: (id: string | null) => void outlines?: Parameters[0] - tiles?: MapTiles + tiles?: BasemapTiles fitKey?: string | number fitTo?: MapFitTo height?: number | string @@ -86,6 +86,57 @@ const MARKER_SIZES = [ const pointRadius = (size: MarkerSize) => ({ compact: 4, standard: 6, large: 8 })[size] +const VECTOR_BASEMAP_LAYER_IDS = [ + 'basemap-landcover', + 'basemap-landuse', + 'basemap-park', + 'basemap-water', + 'basemap-waterway', + 'basemap-aeroway', + 'basemap-building', + 'basemap-boundary', + 'basemap-transportation', + 'basemap-water-name', + 'basemap-transportation-name', + 'basemap-place', + 'basemap-mountain-peak', +] + +/** A compact OpenMapTiles style suitable for an offline operational basemap. */ +function vectorBasemapLayers(palette: ReturnType): LayerSpecification[] { + const b = palette.offlineBasemap + const name = ['coalesce', ['get', 'name'], ['get', 'name:latin'], ['get', 'ref'], ''] as ExpressionSpecification + const labelLayout: SymbolLayerSpecification['layout'] = { + 'text-field': name, + 'text-font': [LABEL_FONT], + 'text-size': 11, + 'text-variable-anchor': ['center', 'top', 'bottom', 'left', 'right'], + 'text-radial-offset': 0.4, + 'text-justify': 'auto' as const, + 'text-optional': true, + } + const labelPaint: SymbolLayerSpecification['paint'] = { + 'text-color': palette.colorTextPrimary, + 'text-halo-color': palette.colorBgPrimary, + 'text-halo-width': 1.5, + } + return [ + { id: 'basemap-landcover', type: 'fill', source: 'basemap', 'source-layer': 'landcover', paint: { 'fill-color': b.landFill, 'fill-opacity': 0.65 } }, + { id: 'basemap-landuse', type: 'fill', source: 'basemap', 'source-layer': 'landuse', paint: { 'fill-color': b.landFill, 'fill-opacity': 0.45 } }, + { id: 'basemap-park', type: 'fill', source: 'basemap', 'source-layer': 'park', paint: { 'fill-color': '#6f9a68', 'fill-opacity': 0.5 } }, + { id: 'basemap-water', type: 'fill', source: 'basemap', 'source-layer': 'water', paint: { 'fill-color': b.ocean, 'fill-opacity': 1 } }, + { id: 'basemap-waterway', type: 'line', source: 'basemap', 'source-layer': 'waterway', paint: { 'line-color': b.ocean, 'line-width': 1.2 } }, + { id: 'basemap-aeroway', type: 'fill', source: 'basemap', 'source-layer': 'aeroway', paint: { 'fill-color': palette.colorTextPrimary, 'fill-opacity': 0.12 } }, + { id: 'basemap-building', type: 'fill', source: 'basemap', 'source-layer': 'building', minzoom: 12, paint: { 'fill-color': palette.colorTextPrimary, 'fill-opacity': 0.18 } }, + { id: 'basemap-boundary', type: 'line', source: 'basemap', 'source-layer': 'boundary', paint: { 'line-color': b.countryBorder, 'line-width': 0.8, 'line-dasharray': [3, 2] } }, + { id: 'basemap-transportation', type: 'line', source: 'basemap', 'source-layer': 'transportation', paint: { 'line-color': palette.colorTextPrimary, 'line-opacity': 0.45, 'line-width': 1.2 } }, + { id: 'basemap-water-name', type: 'symbol', source: 'basemap', 'source-layer': 'water_name', minzoom: 8, layout: labelLayout, paint: { ...labelPaint, 'text-color': b.ocean } }, + { id: 'basemap-transportation-name', type: 'symbol', source: 'basemap', 'source-layer': 'transportation_name', minzoom: 10, layout: labelLayout, paint: labelPaint }, + { id: 'basemap-place', type: 'symbol', source: 'basemap', 'source-layer': 'place', layout: { ...labelLayout, 'text-size': 12 }, paint: labelPaint }, + { id: 'basemap-mountain-peak', type: 'symbol', source: 'basemap', 'source-layer': 'mountain_peak', minzoom: 10, layout: labelLayout, paint: labelPaint }, + ] +} + export function TrackMap({ points, sensorPoints = [], @@ -292,20 +343,40 @@ export function TrackMap({ const tileAttribution = tiles?.attribution?.trim() || '' const tileSize = tiles?.tileSize ?? 256 const tileMaxZoom = tiles?.maxZoom ?? 19 + const tileFormat = tiles?.format ?? 'raster' useEffect(() => { const m = map.current if (!m || !ready || !tileUrl) return - m.addSource('basemap', { type: 'raster', tiles: [tileUrl], tileSize, maxzoom: tileMaxZoom, attribution: tileAttribution || undefined }) - m.addLayer({ id: 'basemap', type: 'raster', source: 'basemap' }, 'land') + const layerIds: string[] = [] + if (tileFormat === 'vector') { + m.addSource('basemap', { type: 'vector', tiles: [tileUrl], maxzoom: tileMaxZoom, attribution: tileAttribution || undefined }) + for (const layer of vectorBasemapLayers(palette)) { + m.addLayer(layer, 'land') + layerIds.push(layer.id) + } + m.addLayer( + { + id: 'basemap-vector-dim', + type: 'background', + paint: { 'background-color': palette.colorBgPrimary, 'background-opacity': 0 }, + }, + 'land', + ) + layerIds.push('basemap-vector-dim') + } else { + m.addSource('basemap', { type: 'raster', tiles: [tileUrl], tileSize, maxzoom: tileMaxZoom, attribution: tileAttribution || undefined }) + m.addLayer({ id: 'basemap', type: 'raster', source: 'basemap' }, 'land') + layerIds.push('basemap') + } const credit = tileAttribution ? new AttributionControl({ compact: true }) : null if (credit) m.addControl(credit, 'bottom-right') return () => { if (map.current !== m) return if (credit) m.removeControl(credit) - m.removeLayer('basemap') + for (const id of layerIds.reverse()) if (m.getLayer(id)) m.removeLayer(id) m.removeSource('basemap') } - }, [ready, tileUrl, tileAttribution, tileSize, tileMaxZoom]) + }, [ready, tileUrl, tileAttribution, tileSize, tileMaxZoom, tileFormat, palette]) useEffect(() => { const m = map.current @@ -318,6 +389,13 @@ export function TrackMap({ m.setPaintProperty('basemap', 'raster-brightness-max', 1 - display.dim / 100) m.setPaintProperty('basemap', 'raster-saturation', -display.dim / 100) } + for (const id of VECTOR_BASEMAP_LAYER_IDS) { + if (m.getLayer(id)) m.setLayoutProperty(id, 'visibility', display.basemap ? 'visible' : 'none') + } + if (m.getLayer('basemap-vector-dim')) { + m.setLayoutProperty('basemap-vector-dim', 'visibility', display.basemap ? 'visible' : 'none') + m.setPaintProperty('basemap-vector-dim', 'background-opacity', display.dim / 100) + } }, [ready, tileUrl, display.basemap, display.dim]) useEffect(() => {