feat(tours): OpenHikingMap as a hiking base map of the tour planner (MAP-01)

While a hike is planned, the planner's map switch offers "Hiking" beside the
map, topo and satellite: OpenHikingMap, with marked trails over the terrain.
It is a choice of the planner's view alone, like topo: the global map
setting, the tour and its days stay as they are. With no tour open, over an
import viewed as it came in and for a paddle tour it is not offered, and a
choice made earlier falls back to the standard map there.

openmaps.fr's tile usage policy is followed: tiles load only as the map
shows them, with the browser's Referer, from the server's own caching; no
service worker rule keeps them and the 3D flyover's warm-up passes their
source by. Its credit and donation link are on the map; the 3D map, whose
attribution is folded away under the panel, shows them as a line of its own
above its controls.

The service is best effort. A run of failed tiles while it is shown marks
the switch, with a tooltip and a status for screen readers that say it is
not answering and that the tour is untouched; one tile arriving clears it.
The tile health the seamark overlay had is now useTileHealth, shared by both.

The source is free for non-commercial installs up to 500,000 tiles a month.
tours_hiking_map_enabled is an admin switch under Tours (admin tours-hiking-map,
audited), on by default, for an install that is commercial or larger to
switch off until it has an agreement with the operator. /api/addons carries
it as toursHikingMap, true only while Tours is on.

Leaflet, GL and the 3D map read one table of the planner's raster bases
(tourRasterBases), so topo and the hiking map are drawn the same way.
tile.openmaps.fr is on the CSP's connect-src for the GL maps.
This commit is contained in:
Maurice
2026-10-19 13:07:36 +02:00
parent d322363e53
commit 06e6e25b25
90 changed files with 839 additions and 117 deletions
@@ -108,6 +108,7 @@ export default function TourTerrainMap(props: TourTerrainMapProps) {
insetInlineEnd: rightWidth + MAP_LAYER_SWITCHER_INSET,
}}
>
{baseLayer === 'hiking' && <HikingMapCredit />}
{legendAbove && legend}
<div ref={attachRow} className="flex w-full items-end gap-3" data-fit={fit} data-testid="terrain-control-row">
<div className="flex-none">
@@ -142,6 +143,34 @@ export default function TourTerrainMap(props: TourTerrainMapProps) {
);
}
/**
* OpenHikingMap's credit and donation link, which its operator wants readable without a
* click (MAP-01). The 3D map's own attribution is folded away and sits under the panel,
* so it rides above the control row while that map is shown.
*/
function HikingMapCredit() {
const link = 'text-content-secondary underline-offset-2 hover:underline';
return (
<div
className="pointer-events-auto flex items-center gap-1.5 rounded-full px-3 py-1 text-content-faint"
style={{ ...GLASS, ...fs(10) }}
data-testid="hiking-map-credit"
>
<a className={link} href="https://wiki.openstreetmap.org/wiki/OpenHikingMap" target="_blank" rel="noreferrer">
&copy; OpenHikingMap
</a>
<span aria-hidden>|</span>
<a className={link} href="https://www.openstreetmap.org/copyright" target="_blank" rel="noreferrer">
&copy; OpenStreetMap
</a>
<span aria-hidden>|</span>
<a className={link} href="https://openmaps.fr/donate" target="_blank" rel="noreferrer">
{'❤️'} Donation
</a>
</div>
);
}
/** What a click on the terrain does now: plan, nothing until the tool is on, or nothing to plan. */
function PickHint({ editing, placeOff }: { editing: boolean; placeOff: boolean }) {
const { t } = useTranslation();
@@ -46,6 +46,22 @@ describe('styleFor', () => {
expect(JSON.stringify(topo)).not.toContain('{s}');
expect(satellite.sources.base).toMatchObject({ type: 'raster', maxzoom: 19 });
});
it('draws OpenHikingMap with its credit, from a source the flyover never warms up (MAP-01)', () => {
const hiking = styleFor('hiking');
if (typeof hiking === 'string') throw new Error('expected a raster style');
const [id, source] = Object.entries(hiking.sources)[0];
expect(source).toMatchObject({
type: 'raster',
tiles: ['https://tile.openmaps.fr/openhikingmap/{z}/{x}/{y}.png'],
maxzoom: 18,
});
expect(JSON.stringify(source)).toContain('openmaps.fr/donate');
expect(hiking.layers[0]).toMatchObject({ source: id });
const { gl } = fakeMap({ [id]: source });
expect(loadedTemplates(gl)).toEqual([]);
});
});
describe('trackData', () => {
@@ -1,9 +1,10 @@
import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
import { OPENTOPOMAP_TILE_URL, SATELLITE_TILE_URL } from '../../../constants/mapDefaults';
import { SATELLITE_TILE_URL } from '../../../constants/mapDefaults';
import type { DistanceIndexedProfileSample } from '../../../utils/routeGeometry';
import { OPENFREEMAP_DEFAULT_STYLE } from '../../Map/glProviders';
import type { TourBaseLayer } from '../../Map/MapLayerSwitcher';
import { plannerPinShape, type PlannerPinPoint } from '../../Map/plannerPinShape';
import { TOUR_RASTER_BASES } from '../../Map/tourRasterBases';
import type { TileTemplate } from './terrainPrefetch';
import { gradeBand, gradeSegments } from './tourTerrainModel';
@@ -49,22 +50,28 @@ export function sidePadding(panels: PanelWidths, margin: number) {
return { left, right };
}
function rasterStyle(tiles: string[], maxzoom: number): StyleSpecification {
/**
* The source of a base map whose operator forbids prefetching (OpenHikingMap, MAP-01): it
* loads only what the camera shows, and the flyover's warm-up passes it by.
*/
const VIEW_ONLY_SOURCE = 'base-view-only';
function rasterStyle(tiles: string[], maxzoom: number, sourceId = 'base', attribution?: string): StyleSpecification {
return {
version: 8,
sources: { base: { type: 'raster', tiles, tileSize: 256, maxzoom } },
layers: [{ id: 'base', type: 'raster', source: 'base' }],
sources: { [sourceId]: { type: 'raster', tiles, tileSize: 256, maxzoom, attribution } },
layers: [{ id: 'base', type: 'raster', source: sourceId }],
};
}
/** The same three looks as the flat planner map, draped over the terrain. */
/** The same looks as the flat planner map, draped over the terrain. */
export function styleFor(layer: TourBaseLayer): string | StyleSpecification {
if (layer === 'satellite') return rasterStyle([SATELLITE_TILE_URL], 19);
if (layer === 'topo')
return rasterStyle(
['a', 'b', 'c'].map((s) => OPENTOPOMAP_TILE_URL.replace('{s}', s)),
17
);
if (layer === 'topo') return rasterStyle(TOUR_RASTER_BASES.topo.tiles, TOUR_RASTER_BASES.topo.maxZoom);
if (layer === 'hiking') {
const { tiles, maxZoom, attribution } = TOUR_RASTER_BASES.hiking;
return rasterStyle(tiles, maxZoom, VIEW_ONLY_SOURCE, attribution);
}
return OPENFREEMAP_DEFAULT_STYLE;
}
@@ -165,11 +172,11 @@ export function addTerrainLayers(map: MapLibreMap, data: TrackData, exaggeration
map.setSky({ 'sky-color': '#9cc3f0', 'horizon-color': '#e8f0fb', 'fog-color': '#f4f7fb', 'sky-horizon-blend': 0.5 });
}
/** Every tiled source the loaded style draws from, the elevation model included. */
/** Every tiled source the loaded style draws from, the elevation model included, but no view-only one. */
export function loadedTemplates(map: MapLibreMap): TileTemplate[] {
const templates: TileTemplate[] = [];
for (const id of Object.keys(map.getStyle().sources)) {
if (id === HILLSHADE_SOURCE || id === TRACK_SOURCE) continue;
if (id === HILLSHADE_SOURCE || id === TRACK_SOURCE || id === VIEW_ONLY_SOURCE) continue;
const source = map.getSource(id) as { tiles?: string[]; minzoom?: number; maxzoom?: number } | undefined;
const url = source?.tiles?.[0];
if (url) templates.push({ url, minzoom: source.minzoom ?? 0, maxzoom: source.maxzoom ?? 22 });
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { baseLayerFor, tourMapLayersFor } from './tourMapLayers';
describe('tourMapLayersFor (MAP-01)', () => {
it('offers OpenHikingMap to a hike only while the admin allows it', () => {
expect(tourMapLayersFor('hike').bases).not.toContain('hiking');
expect(tourMapLayersFor('hike', { hikingMap: true }).bases).toEqual(['default', 'topo', 'hiking', 'satellite']);
expect(tourMapLayersFor('hike', { hikingMap: true }).overlays).toEqual(['ferratas']);
expect(tourMapLayersFor('kayak', { hikingMap: true }).bases).not.toContain('hiking');
expect(tourMapLayersFor(null, { hikingMap: true }).bases).not.toContain('hiking');
});
it('falls back to the standard map once the admin withdrew it, keeping the choice for later', () => {
expect(baseLayerFor(tourMapLayersFor('hike', { hikingMap: true }), 'hiking')).toBe('hiking');
expect(baseLayerFor(tourMapLayersFor('hike'), 'hiking')).toBe('default');
});
});
+11 -5
View File
@@ -9,10 +9,11 @@ import type { TourBaseLayer } from '../Map/MapLayerSwitcher';
* A base layer is the map itself (one at a time). An overlay is information
* laid over it and switched on its own; it is off until the user turns it on.
* Only sources TREK already ships or that a card cleared are listed: OpenTopoMap
* and the Esri imagery the planner had, the via ferrata layer (RC-10) and
* OpenSeaMap's seamarks (PAD-10).
* and the Esri imagery the planner had, OpenHikingMap (MAP-01), the via ferrata
* layer (RC-10) and OpenSeaMap's seamarks (PAD-10).
*
* - Hike: the standard map first, as before; topo and satellite beside it; via ferratas.
* - Hike: the standard map first, as before; topo, OpenHikingMap (MAP-01, while the admin
* allows it) and satellite beside it; via ferratas.
* - Paddle: the standard map, whose water reads clearly, and satellite. No topo and
* no ferratas, those are hiking maps. Seamarks as an overlay.
* - Any other type (switched off, or one this build does not plan): the standard map
@@ -33,11 +34,16 @@ const HIKE: TourMapLayerSet = {
defaultBase: 'default',
overlays: ['ferratas'],
};
const HIKE_WITH_HIKING_MAP: TourMapLayerSet = { ...HIKE, bases: ['default', 'topo', 'hiking', 'satellite'] };
const PADDLE: TourMapLayerSet = { bases: ['default', 'satellite'], defaultBase: 'default', overlays: ['seamarks'] };
const OTHER: TourMapLayerSet = { bases: ['default', 'satellite'], defaultBase: 'default', overlays: [] };
export function tourMapLayersFor(type: TourTypeKey | null | undefined): TourMapLayerSet {
if (type === 'hike') return HIKE;
/** `hikingMap`: the admin allows OpenHikingMap on this install (MAP-01). */
export function tourMapLayersFor(
type: TourTypeKey | null | undefined,
{ hikingMap = false }: { hikingMap?: boolean } = {}
): TourMapLayerSet {
if (type === 'hike') return hikingMap ? HIKE_WITH_HIKING_MAP : HIKE;
if (type === 'kayak') return PADDLE;
return OTHER;
}
@@ -0,0 +1,54 @@
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { useTileHealth, useTourRasterOverlay } from './useTourRasterOverlay';
const SEAMARKS = { id: 'seamarks', url: 'https://x/{z}/{x}/{y}.png', attribution: 'x', minZoom: 6, maxZoom: 18 };
describe('useTileHealth', () => {
it('counts a source down after a run of failures, never after a stray one, and up again on one tile', () => {
const { result } = renderHook(() => useTileHealth());
act(() => result.current.onTileError());
expect(result.current.down).toBe(false);
act(() => {
result.current.onTileError();
result.current.onTileError();
result.current.onTileError();
});
expect(result.current.down).toBe(true);
act(() => result.current.onTileLoad());
expect(result.current.down).toBe(false);
});
it('starts afresh on reset', () => {
const { result } = renderHook(() => useTileHealth());
act(() => {
for (let i = 0; i < 4; i++) result.current.onTileError();
});
act(() => result.current.reset());
expect(result.current.down).toBe(false);
act(() => result.current.onTileError());
expect(result.current.down).toBe(false);
});
});
describe('useTourRasterOverlay', () => {
it('is off unless offered and on, and down after a run of failures until switched again', () => {
const toggle = vi.fn();
const { result, rerender } = renderHook(
({ offered, active }) => useTourRasterOverlay(SEAMARKS, offered, active, toggle),
{
initialProps: { offered: false, active: true },
}
);
expect(result.current.status).toBe('off');
rerender({ offered: true, active: true });
expect(result.current.status).toBe('on');
act(() => {
for (let i = 0; i < 4; i++) result.current.onTileError();
});
expect(result.current.status).toBe('down');
act(() => result.current.onToggle());
expect(toggle).toHaveBeenCalledTimes(1);
expect(result.current.status).toBe('on');
});
});
@@ -1,15 +1,33 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import type { MapRasterOverlay, ToggleableRasterOverlay } from '../Map/mapRasterOverlay';
import type { TileHealth } from '../Map/tourRasterBases';
/** Failed tiles in a row, with none arriving between them, before the source counts as down. */
const FAILURES_UNTIL_DOWN = 4;
/**
* Whether a best-effort tile source answers. A run of failed tiles marks it
* down; one tile arriving clears that, and `reset` tries afresh. One stray
* failure alone never marks it down.
*/
export function useTileHealth(): TileHealth & { reset: () => void } {
const [down, setDown] = useState(false);
const failures = useRef(0);
const reset = useCallback(() => {
failures.current = 0;
setDown(false);
}, []);
const onTileError = useCallback(() => {
failures.current += 1;
if (failures.current >= FAILURES_UNTIL_DOWN) setDown(true);
}, []);
return useMemo(() => ({ down, onTileError, onTileLoad: reset, reset }), [down, onTileError, reset]);
}
/**
* An overlay the planner offers, off until switched on; whether it is on is
* the planner's (`active`, `onToggle`), so it outlasts the map. A run of failed
* tiles marks it down, which the switch shows; one tile arriving clears that,
* and switching it off and on again tries afresh. One stray failure alone
* never marks it down.
* the planner's (`active`, `onToggle`), so it outlasts the map. Its tile
* health shows on the switch, and switching it off and on again tries afresh.
*/
export function useTourRasterOverlay(
definition: Pick<MapRasterOverlay, 'id' | 'url' | 'attribution' | 'minZoom' | 'maxZoom'>,
@@ -17,23 +35,13 @@ export function useTourRasterOverlay(
active: boolean,
toggle: () => void
): ToggleableRasterOverlay {
const [down, setDown] = useState(false);
const failures = useRef(0);
const { down, onTileError, onTileLoad, reset } = useTileHealth();
const on = active && offered;
const onToggle = useCallback(() => {
failures.current = 0;
setDown(false);
reset();
toggle();
}, [toggle]);
const onTileError = useCallback(() => {
failures.current += 1;
if (failures.current >= FAILURES_UNTIL_DOWN) setDown(true);
}, []);
const onTileLoad = useCallback(() => {
failures.current = 0;
setDown(false);
}, []);
}, [reset, toggle]);
return useMemo(
() => ({