The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
import { useEffect, useLayoutEffect, useRef, useImperativeHandle, useCallback, type CSSProperties, type Ref, type RefObject } from 'react'
import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer'
import L from 'leaflet'
import { useSettingsStore } from '../../store/settingsStore'
import { useCartoApiKey } from '../../hooks/useTileUrl'
import { isGcj02Basemap, isVectorStyle, resolveTileUrl } from '../../utils/tileUrl'
import { AMAP_SATELLITE, OFM_DARK, OFM_POSITRON, SATELLITE_TILE_MAXZOOM, SATELLITE_TILE_URL, attributionForTile } from '../../constants/mapDefaults'
import { attachVectorBasemap, detachBasemapLayer, restyleBasemap, type BasemapLayer } from '../Map/VectorBasemap'
import { crsForBasemap } from '../Map/gcj02Crs'
import type { BaseLayer } from '../Map/MapLayerSwitcher'
import { escapeHtml, type JourneyTrack } from '@trek/shared'
import { ensureJourneyPopupStyle, formatMarkerDate, journeyPopupHtml } from './journeyMapPopup'
import { PLANNED_BADGE_SVG, type JourneyMapMark } from './journeyMapMarks'
import { isPlannedTrack, type JourneyMapLayerVisibility } from './journeyMapLayers'
import { NOTHING_DRAWN, drawLeafletMarks, isLeafletLayerShown, leafletWorldPx, switchLeafletLayers, type DrawnLayers, type LeafletLayerKind } from './journeyLeafletLayers'
import { entryConnections } from './journeyMapConnections'
import { framePoint, journeyLines, journeyLngFrame } from './journeyMapLines'
import type { LngFrame } from '../../utils/lngFrame'
export interface MapMarkerItem {
id: string
lat: number
lng: number
label: string
locationName: string
mood?: string | null
time: string
dayColor: string
dayLabel: number | null
photoUrls: string[]
}
export interface JourneyMapHandle {
highlightMarker: (id: string | null) => void
focusMarker: (id: string) => void
invalidateSize: () => void
}
export type { MapPhoto } from './journeyPhotoLayer'
interface MapEntry {
id: string
lat: number
lng: number
title?: string | null
location_name?: string | null
mood?: string | null
entry_date: string
dayColor?: string
dayLabel?: number | null
/** Thumbnails for the marker card, already resolved by the caller (the share view signs its own). */
photoUrls?: string[]
}
interface Props {
ref?: Ref<JourneyMapHandle>
checkins: any[]
entries: MapEntry[]
/** Photos placed by their own capture coordinates, clustered by proximity. */
photos?: MapPhoto[]
onPhotoClick?: (photoIds: string[]) => void
trail?: { lat: number; lng: number }[]
/** Routed GPX geometries from the journey's trips (#1260). */
tracks?: JourneyTrack[]
height?: number
dark?: boolean
activeMarkerId?: string | null
onMarkerClick?: (id: string, type?: string) => void
fullScreen?: boolean
/**
* Open the entry a marker card names when the card itself is tapped.
*
* On a phone the card is what a tap on a pin brings up, so it has to lead
* somewhere (#2885). Wiring it is what makes the card take the pointer, and the
* card then stands over the active pin, as the GL popup does; without
* it the card stays a label the map's drags pass through, as on desktop, where
* it is a hover card the mouse cannot reach.
*/
onMarkerCardClick?: (entryId: string) => void
paddingBottom?: number
/**
* How much of the map's leading edge a bar laid over it covers (the touch
* shell's rail), in px: framing keeps the journey clear of it. Read when the
* map frames, so a change alone does not rebuild the map.
*/
paddingStart?: number
/** CARTO key from the share payload: the public journey has no settings store to read. */
cartoApiKey?: string
/**
* Which drawn layers the reader shows (JRN-04). A hidden one is taken off the
* map and put back as it was, never rebuilt, so the view stays where it is.
*/
layerVisibility?: JourneyMapLayerVisibility
/** The plan's places and the stays of day reports, clustered where they meet. */
marks?: JourneyMapMark[]
onMarksPick?: (marks: JourneyMapMark[]) => void
/** Entry pins whose place the plan had too, marked with a check. */
plannedEntryIds?: ReadonlySet<string>
/** The reader's base layer (#2594): the basemap, or the satellite imagery in its place. */
baseLayer?: BaseLayer
}
/** The map's own zoom buttons, frosted so they hold on any tile. */
const zoomButtonStyle = (dark?: boolean): CSSProperties => ({
width: 32, height: 32, borderRadius: 8,
background: dark ? 'rgba(255,255,255,0.12)' : 'rgba(255,255,255,0.9)',
backdropFilter: 'blur(8px)',
border: `1px solid ${dark ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.1)'}`,
color: dark ? '#fff' : '#18181B',
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))', fontWeight: 700, lineHeight: 1,
})
const EVERY_LAYER: JourneyMapLayerVisibility = { plan: true, recorded: true, entries: true }
const NO_PLANNED: ReadonlySet<string> = new Set()
function buildMarkerItems(entries: MapEntry[]): MapMarkerItem[] {
const items: MapMarkerItem[] = []
for (const e of entries) {
if (e.lat && e.lng) {
items.push({
id: e.id,
lat: e.lat,
lng: e.lng,
label: e.title || 'Entry',
locationName: e.location_name || '',
mood: e.mood,
time: e.entry_date,
dayColor: e.dayColor || '#52525B',
dayLabel: e.dayLabel === undefined ? 1 : e.dayLabel,
photoUrls: e.photoUrls ?? [],
})
}
}
items.sort((a, b) => a.time.localeCompare(b.time))
return items
}
const MARKER_W = 28
const MARKER_H = 36
function markerSvg(dayColor: string, dayLabel: number | null, highlighted: boolean, planned = false): string {
const stroke = highlighted ? '#fff' : 'rgba(255,255,255,0.5)'
const shadow = highlighted
? 'filter:drop-shadow(0 0 10px rgba(0,0,0,0.4)) drop-shadow(0 2px 6px rgba(0,0,0,0.4))'
: 'filter:drop-shadow(0 2px 4px rgba(0,0,0,0.25))'
const label = dayLabel === null ? '' : String(dayLabel)
const scale = highlighted ? 1.2 : 1
return `<div style="transform:scale(${scale});transition:transform 0.2s ease;${shadow};transform-origin:bottom center">
<svg width="${MARKER_W}" height="${MARKER_H}" viewBox="0 0 28 36" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 34C14 34 26 22.36 26 13C26 6.37 20.63 1 14 1C7.37 1 2 6.37 2 13C2 22.36 14 34 14 34Z" fill="${dayColor}" stroke="${stroke}" stroke-width="1.5"/>
<circle cx="14" cy="13" r="8" fill="${dayColor}"/>
<text x="14" y="13" text-anchor="middle" dominant-baseline="central" fill="#fff" font-family="'Poppins',system-ui,sans-serif" font-size="11" font-weight="700">${label}</text>
${planned ? PLANNED_BADGE_SVG : ''}
</svg>
</div>`
}
function entryIcon(item: MapMarkerItem, highlighted: boolean, planned: boolean): L.DivIcon {
return L.divIcon({
className: '',
iconSize: [MARKER_W, MARKER_H],
iconAnchor: [MARKER_W / 2, MARKER_H],
html: markerSvg(item.dayColor, item.dayLabel, highlighted, planned),
})
}
function paintEntryMarker(
marker: L.Marker | undefined, item: MapMarkerItem | undefined, highlighted: boolean, planned: ReadonlySet<string>,
): void {
if (!marker || !item) return
marker.setIcon(entryIcon(item, highlighted, planned.has(item.id)))
marker.setZIndexOffset(highlighted ? 1000 : 0)
}
/**
* Pan, don't zoom: the initial fitBounds decides how far out the reader starts,
* and a focus keeps that (discussion #2299).
*
* Deferred until the map has its first view. That view is set on a rAF after
* the build, and the active entry asks for its pan on a 50 ms timer, so a tab
* in the background or a slow frame lets the pan come first. Leaflet does not
* refuse a pan on a viewless map, it takes it as the first view, with the zoom
* still undefined: the tile layer aborts its own add on that, the load event
* stops halfway, and every marker queued behind it never makes it onto the map.
* The next rebuild then tears down markers that were never added and dies in
* Leaflet's icon removal, which took the whole journey page with it after each
* save. whenReady runs the pan at once on a map with a view and otherwise right
* after the fit lands.
*/
function panToMarker(map: L.Map, marker: L.Marker): void {
map.whenReady(() => {
map.panTo(marker.getLatLng(), { animate: true, duration: 0.5 })
})
}
/**
* The same card the GL renderer shows, from the same builder: which map engine a
* reader happens to have selected should not change what a marker tells them
* (discussion #2299). The builder escapes everything that came from a person,
* which matters most here, since this map is what the public journey page renders.
*/
function entryCardHtml(item: MapMarkerItem): string {
return journeyPopupHtml({
title: item.label || item.locationName || 'Entry',
place: item.label ? item.locationName : '',
date: formatMarkerDate(item.time),
photoUrls: item.photoUrls,
})
}
const ENTRY_CARD_OPTIONS: L.TooltipOptions = { direction: 'top', offset: [0, -MARKER_H] }
/**
* The card that opens its entry when tapped (#2885), one per map like the GL
* popup, shown above the active pin.
*
* It is deliberately not bound to the pins. A bound tooltip is opened and closed
* by Leaflet on the pin's hover and focus, and a tap on the card is, to a phone,
* the pointer leaving the pin: the pin's mouseout closed the card between the
* tap and its click. Driven by the active pin alone, nothing but a change of
* entry takes it away.
*/
function createEntryCard(open: () => void): L.Tooltip {
const card = L.tooltip({ ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip is-openable' })
// The element is built on the first open and kept for every later one.
card.once('add', () => {
const el = card.getElement()
if (!el) return
// A press on the card is not the start of a drag or a tap on the map.
L.DomEvent.disableClickPropagation(el)
L.DomEvent.on(el, 'click', (ev) => {
L.DomEvent.stopPropagation(ev)
open()
})
})
return card
}
interface PinRefs {
onCardClickRef: RefObject<((entryId: string) => void) | undefined>
mapRef: RefObject<L.Map | null>
markersRef: RefObject<Map<string, L.Marker>>
itemsRef: RefObject<MapMarkerItem[]>
highlightedRef: RefObject<string | null>
}
/**
* The openable card of a host that wires onMarkerCardClick. The returned sync puts
* it over the active pin while that pin is on the map and takes it off otherwise.
*/
function useEntryCardSync({ onCardClickRef, mapRef, markersRef, itemsRef, highlightedRef }: PinRefs): () => void {
const cardRef = useRef<L.Tooltip | null>(null)
const cardEntryIdRef = useRef<string | null>(null)
const sync = useCallback(() => {
const map = mapRef.current
const id = highlightedRef.current
const marker = id ? markersRef.current.get(id) : undefined
const item = id ? itemsRef.current.find(i => i.id === id) : undefined
if (!onCardClickRef.current || !map || !marker || !item || !map.hasLayer(marker)) {
cardRef.current?.remove()
cardEntryIdRef.current = null
return
}
ensureJourneyPopupStyle()
let card = cardRef.current
if (!card) {
card = createEntryCard(() => {
if (cardEntryIdRef.current) onCardClickRef.current?.(cardEntryIdRef.current)
})
cardRef.current = card
}
cardEntryIdRef.current = item.id
card.setLatLng(marker.getLatLng()).setContent(entryCardHtml(item))
if (!map.hasLayer(card)) card.addTo(map)
}, [onCardClickRef, mapRef, markersRef, itemsRef, highlightedRef])
return sync
}
const EMPTY_TRAIL: { lat: number; lng: number }[] = []
const EMPTY_TRACKS: JourneyTrack[] = []
/** Fallback when a track carries no colour of its own, matching the planner's default. */
const TRACK_FALLBACK_COLOR = '#4f46e5'
/** The dash of a planned track; wide enough not to pass for the faint line between entries. */
const PLANNED_DASH = '8 7'
function markCoords(marks: JourneyMapMark[] | undefined, frame: LngFrame | null): L.LatLngTuple[] {
return (marks ?? []).map(mark => framePoint(frame, mark.lat, mark.lng))
}
function fitOptions(paddingBottom: number | undefined, paddingStart = 0): L.FitBoundsOptions {
const rtl = typeof document !== 'undefined' && document.documentElement.dir === 'rtl'
return {
paddingTopLeft: [50 + (rtl ? 0 : paddingStart), 50],
paddingBottomRight: [50 + (rtl ? paddingStart : 0), paddingBottom || 50],
maxZoom: 16,
}
}
/**
* The tile layer that draws a raster base: the user's own template, or the
* satellite imagery. The imagery follows the basemap's datum, as on the planner
* map: Esri's is WGS-84 and Amap's GCJ-02, and the other one on this map's
* projection would sit a few hundred metres off.
*/
function rasterBase(url: string, satellite: boolean, gcj: boolean): L.TileLayer {
const tileUrl = satellite ? (gcj ? AMAP_SATELLITE : SATELLITE_TILE_URL) : url
const options: L.TileLayerOptions & { referrerPolicy: ReferrerPolicy } = {
maxZoom: satellite ? SATELLITE_TILE_MAXZOOM : 18,
attribution: attributionForTile(tileUrl),
referrerPolicy: 'strict-origin-when-cross-origin',
// Leaflet defaults updateWhenIdle:true on mobile (waits for pan to settle
// before loading tiles). On the journey mobile combined view we flyTo
// constantly when switching cards, so tiles lag visibly — force eager
// updates and keep a larger ring of off-screen tiles ready.
updateWhenIdle: false,
keepBuffer: 4,
}
return L.tileLayer(tileUrl, options)
}
interface BaseRefs {
mapRef: RefObject<L.Map | null>
tileUrlRef: RefObject<string>
tileLayerRef: RefObject<L.TileLayer | null>
glLayerRef: RefObject<BasemapLayer | null>
}
/**
* The map's base and the reader's switch between it and the satellite imagery
* (#2594). The map effect draws it through drawBase; the switch redraws it in
* place, since a rebuild would drop every marker and track for a new backdrop.
*/
function useJourneyBase(satellite: boolean, { mapRef, tileUrlRef, tileLayerRef, glLayerRef }: BaseRefs) {
const satelliteRef = useRef(satellite)
useLayoutEffect(() => {
satelliteRef.current = satellite
})
// Bumped by every base drawn, so a vector style still loading for a base the
// reader has already switched away from never lands on the map.
const baseDrawRef = useRef(0)
// Which base the map carries now, so the switch redraws only on a change.
const drawnSatelliteRef = useRef(satellite)
/**
* Draws the base: the satellite imagery while the reader asked for it,
* otherwise the basemap, which is a vector style unless the user brought their
* own raster template. Whatever drew it before is taken off first. A vector
* style is a GL canvas of its own, so leaving it under the imagery would keep
* a WebGL context busy drawing what nobody can see.
*/
const drawBase = useCallback((map: L.Map, torn: () => boolean) => {
const draw = ++baseDrawRef.current
drawnSatelliteRef.current = satelliteRef.current
tileLayerRef.current?.remove()
tileLayerRef.current = null
detachBasemapLayer(glLayerRef.current)
glLayerRef.current = null
const url = tileUrlRef.current
if (!satelliteRef.current && isVectorStyle(url)) {
void attachVectorBasemap(map, url, glLayerRef, () => torn() || draw !== baseDrawRef.current)
return
}
const tiles = rasterBase(url, satelliteRef.current, !isVectorStyle(url) && isGcj02Basemap(url))
tiles.addTo(map)
tileLayerRef.current = tiles
}, [tileUrlRef, tileLayerRef, glLayerRef])
// Nothing to do when the map effect has just drawn the base the switch asks for.
useEffect(() => {
const map = mapRef.current
if (!map || drawnSatelliteRef.current === satellite) return
drawBase(map, () => mapRef.current !== map)
}, [satellite, drawBase, mapRef])
return { drawBase, satelliteRef }
}
function JourneyMap(
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, paddingStart = 0, cartoApiKey, onMarkerCardClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, baseLayer = 'default', ref }: Props,
) {
// The leading inset is read when the map frames, not a reason to rebuild it.
const paddingStartRef = useRef(paddingStart)
useLayoutEffect(() => {
paddingStartRef.current = paddingStart
})
// Read through a ref: the handler is fixed per surface, and putting it in the
// marker effect's deps would rebuild every marker for nothing.
const onMarkerCardClickRef = useRef(onMarkerCardClick)
onMarkerCardClickRef.current = onMarkerCardClick
const stableTrail = trail || EMPTY_TRAIL
const stableTracks = tracks || EMPTY_TRACKS
const mapTileUrl = useSettingsStore(s => s.settings.map_tile_url)
const storedCartoKey = useCartoApiKey()
const cartoKey = cartoApiKey || storedCartoKey
const tileUrl = resolveTileUrl(mapTileUrl, dark ? OFM_DARK : OFM_POSITRON, cartoKey)
// Amap's tiles are GCJ-02 (see gcj02Crs.ts), the same shift the planner map
// applies. Leaflet fixes a map's CRS at construction, so this one value is
// allowed to rebuild the map where a template change only retiles it.
const isGcjBasemap = !isVectorStyle(tileUrl) && isGcj02Basemap(tileUrl)
// Read through a ref by the map effect, retiled in place by its own effect below:
// the CARTO key reaches the store after the first render, and rebuilding the map
// for that raced with the markers and layers already on it (#2097).
const tileUrlRef = useRef(tileUrl)
tileUrlRef.current = tileUrl
const tileLayerRef = useRef<L.TileLayer | null>(null)
// GL layer or the raster stand-in a browser without WebGL gets instead (#2288).
const glLayerRef = useRef<BasemapLayer | null>(null)
const containerRef = useRef<HTMLDivElement>(null)
const mapRef = useRef<L.Map | null>(null)
const { drawBase, satelliteRef } = useJourneyBase(baseLayer === 'satellite', { mapRef, tileUrlRef, tileLayerRef, glLayerRef })
const markersRef = useRef<Map<string, L.Marker>>(new Map())
const itemsRef = useRef<MapMarkerItem[]>([])
const highlightedRef = useRef<string | null>(null)
const onMarkerClickRef = useRef(onMarkerClick)
onMarkerClickRef.current = onMarkerClick
const photoLayerRef = useRef<L.LayerGroup | null>(null)
const onPhotoClickRef = useRef(onPhotoClick)
onPhotoClickRef.current = onPhotoClick
const markLayerRef = useRef<L.LayerGroup | null>(null)
const onMarksPickRef = useRef(onMarksPick)
const marksRef = useRef(marks)
// The longitude frame of a journey across the antimeridian (#3080), set on each
// build and read by the photo and mark layers so they land on the same world copy.
const frameRef = useRef<LngFrame | null>(null)
// The plan and the stays load after the entries, so the first view is framed
// again once they arrive, around both, unless the reader has moved it by then.
const entryCoordsRef = useRef<L.LatLngTuple[]>([])
const marksFramedRef = useRef(false)
const readerMovedRef = useRef(false)
// What each switchable layer drew, and which of them are on the map right now.
const drawnRef = useRef<DrawnLayers>(NOTHING_DRAWN())
const shownRef = useRef<JourneyMapLayerVisibility>(layerVisibility)
const visibilityRef = useRef(layerVisibility)
const plannedRef = useRef(plannedEntryIds)
const iconPlannedRef = useRef<ReadonlySet<string>>(plannedEntryIds)
// Before the map effects below, so a rebuild draws with what the reader shows now.
useEffect(() => {
onMarksPickRef.current = onMarksPick
marksRef.current = marks
visibilityRef.current = layerVisibility
plannedRef.current = plannedEntryIds
})
const syncEntryCard = useEntryCardSync({ onCardClickRef: onMarkerCardClickRef, mapRef, markersRef, itemsRef, highlightedRef })
const highlightMarker = useCallback((id: string | null) => {
const prev = highlightedRef.current
highlightedRef.current = id
const paint = (target: string, highlighted: boolean) => paintEntryMarker(
markersRef.current.get(target), itemsRef.current.find(i => i.id === target), highlighted, plannedRef.current,
)
if (prev && prev !== id) paint(prev, false)
if (id) paint(id, true)
syncEntryCard()
}, [syncEntryCard])
/**
* Bring an entry's marker under the reader without changing how far out they are.
*
* This fires on every step through the timeline, and it used to force zoom 12.
* Reading a journey from a country view therefore yanked the map to street level
* on the first scroll and kept it there: every marker filled the screen, and the
* one thing a map is for — where is this, relative to everything else — was gone
* (discussion #2299). Panning keeps the frame the reader chose; the initial
* fitBounds is what decides how close the journey starts out.
*/
const focusMarker = useCallback((id: string) => {
highlightMarker(id)
const marker = markersRef.current.get(id)
if (marker && mapRef.current) panToMarker(mapRef.current, marker)
}, [])
const invalidateSize = useCallback(() => {
try { mapRef.current?.invalidateSize() } catch { /* map not yet initialized */ }
}, [])
useImperativeHandle(ref, () => ({ highlightMarker, focusMarker, invalidateSize }), [])
useEffect(() => {
if (!containerRef.current) return
markersRef.current.clear()
const crs = crsForBasemap(isGcjBasemap)
const map = L.map(containerRef.current, {
...(crs ? { crs } : {}),
zoomControl: false,
// Added below with `prefix: false` so it collapses to the credit alone; see
// the GL twin for why it is not a strip of text across the bottom.
attributionControl: false,
scrollWheelZoom: fullScreen ? true : false,
dragging: true,
touchZoom: true,
})
L.control.attribution({ position: 'bottomright', prefix: false }).addTo(map)
mapRef.current = map
// The vector basemap loads async; a map torn down before it lands must not get
// one. Per build, not a shared ref: the next build would reset a shared flag and
// hand the old map, already removed, the layer it was still waiting for.
let cancelled = false
marksFramedRef.current = false
readerMovedRef.current = false
const readerMoved = () => { readerMovedRef.current = true }
map.on('dragstart', readerMoved)
containerRef.current.addEventListener('wheel', readerMoved, { passive: true })
// Which layer draws the base is decided per template and per the reader's
// switch rather than once; see drawBase.
drawBase(map, () => cancelled)
const items = buildMarkerItems(entries)
itemsRef.current = items
// Leaflet draws each layer at its literal longitude, so a journey across the
// antimeridian is drawn in one frame: pins and lines on one copy, every line
// the short way across the date line (#3080). Every other journey has none.
const frame = journeyLngFrame([...items, ...stableTrail], stableTracks, frameRef.current)
frameRef.current = frame
// Each switchable layer is drawn whatever its switch says and only put on
// the map while it is shown, so switching it later needs no rebuild.
const drawn = NOTHING_DRAWN()
drawnRef.current = drawn
shownRef.current = visibilityRef.current
iconPlannedRef.current = plannedRef.current
const place = <T extends L.Layer>(kind: LeafletLayerKind, layer: T): T => {
drawn[kind].push(layer)
if (isLeafletLayerShown(kind, visibilityRef.current)) layer.addTo(map)
return layer
}
const allCoords: L.LatLngTuple[] = []
/**
* Track geometry is kept OUT of the fit set (#2194) and used only when there
* is nothing else to frame.
*
* A journey's opening viewport should show the journey — its entries and the
* trail between them. Letting a recorded GPX into the bounds meant one drive
* across a country zoomed the map out until the entries were specks, which
* is what the reporter's screenshot shows. JourneyMapGL already fits on
* entries + trail alone, so for every journey that has entries the two
* renderers now agree where they used to differ.
*
* They still differ for a journey with tracks and nothing else: this one
* frames the tracks, JourneyMapGL falls back to the world view. Framing the
* only thing on the map is the better of the two, and converging the GL side
* is a change to a renderer this issue is not about.
*/
const trackCoords: L.LatLngTuple[] = []
if (stableTrail.length > 1) {
const coords = stableTrail.map(p => [p.lat, p.lng] as [number, number])
for (const line of journeyLines(frame, coords, true)) {
place('recorded', L.polyline(line, {
color: '#6366f1', weight: 3, opacity: 0.4,
dashArray: '6 4', lineCap: 'round',
}))
}
coords.forEach(([lat, lng]) => allCoords.push(framePoint(frame, lat, lng)))
}
// Tracks, in their own colour over a white casing that keeps them legible on
// satellite tiles, same as the planner map. What was recorded (a day the journey
// keeps, the live Dawarich trail) is drawn solid; a trip's GPX track is the plan
// and drawn dashed, so the two never read as the same thing (JRN-01).
for (const track of stableTracks) {
if (track.points.length < 2) continue
const color = track.color || TRACK_FALLBACK_COLOR
const planned = isPlannedTrack(track)
const kind: LeafletLayerKind = planned ? 'plan' : 'recorded'
for (const coords of journeyLines(frame, track.points as [number, number][], true)) {
place(kind, L.polyline(coords, { color: '#ffffff', weight: 6, opacity: 0.75, lineCap: 'round', lineJoin: 'round' }))
const line = L.polyline(coords, {
color, weight: 3.5, opacity: 0.95, lineCap: 'round', lineJoin: 'round',
...(planned ? { dashArray: PLANNED_DASH } : {}),
})
// Same tooltip the markers on this map use, rather than Leaflet's default box:
// it follows the appearance tokens, so it lands right in dark mode and with
// transparency switched off. Escaped because a string handed to bindTooltip
// becomes innerHTML, and a track name is a place name off a shared trip.
if (track.name) line.bindTooltip(escapeHtml(track.name), { sticky: true, direction: 'top', className: 'map-tooltip' })
place(kind, line)
}
track.points.forEach(([lat, lng]) => trackCoords.push(framePoint(frame, lat, lng)))
}
// The faint line between the entries in their order, same as JourneyMapGL, left
// off the stretches a recorded day already draws as travelled (#2888).
const connections = entryConnections(items.map(i => ({ lat: i.lat, lng: i.lng, date: i.time })), stableTracks)
const connectionStyle: L.PolylineOptions = {
color: dark ? '#71717A' : '#A1A1AA',
weight: 1.5,
opacity: 0.5,
dashArray: '4 6',
lineCap: 'round', lineJoin: 'round',
}
for (const open of connections.open) {
for (const line of journeyLines(frame, open, true)) place('entries', L.polyline(line, connectionStyle))
}
for (const covered of connections.covered) {
for (const line of journeyLines(frame, covered, true)) place('coveredConnections', L.polyline(line, connectionStyle))
}
// place markers
items.forEach((item, i) => {
const pos: L.LatLngTuple = framePoint(frame, item.lat, item.lng)
allCoords.push(pos)
const marker = place('entries', L.marker(pos, { icon: entryIcon(item, false, plannedRef.current.has(item.id)) }))
// A host that opens the entry from its card gets the one card that follows
// the active pin instead (see syncEntryCard).
if (!onMarkerCardClickRef.current) {
ensureJourneyPopupStyle()
marker.bindTooltip(entryCardHtml(item), { ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip' })
}
marker.on('click', () => {
onMarkerClickRef.current?.(item.id)
})
markersRef.current.set(item.id, marker)
})
// fit bounds
requestAnimationFrame(() => {
if (!mapRef.current) return
try {
map.invalidateSize()
// Tracks only get a say when the journey has nothing located of its own —
// a world view would be worse than framing the one thing on the map.
entryCoordsRef.current = allCoords
const pointCoords = [...allCoords, ...markCoords(marksRef.current, frame)]
const fitCoords = pointCoords.length > 0 ? pointCoords : trackCoords
marksFramedRef.current = (marksRef.current?.length ?? 0) > 0
if (fitCoords.length > 0) map.fitBounds(L.latLngBounds(fitCoords), fitOptions(paddingBottom, paddingStartRef.current))
else map.setView([30, 0], 2)
} catch {}
})
setTimeout(() => {
if (mapRef.current) map.invalidateSize()
}, 200)
const container = containerRef.current
return () => {
cancelled = true
container.removeEventListener('wheel', readerMoved)
map.remove()
mapRef.current = null
tileLayerRef.current = null
detachBasemapLayer(glLayerRef.current)
glLayerRef.current = null
markersRef.current.clear()
drawnRef.current = NOTHING_DRAWN()
}
}, [entries, stableTrail, stableTracks, dark, fullScreen, paddingBottom, isGcjBasemap, drawBase])
// A switch puts its layer back on the map or takes it off, exactly as drawn.
useEffect(() => {
shownRef.current = switchLeafletLayers(mapRef.current, drawnRef.current, shownRef.current, layerVisibility)
syncEntryCard()
}, [layerVisibility, syncEntryCard])
// The plan's check on an entry pin follows the plan layer without redrawing the map.
useEffect(() => {
const before = iconPlannedRef.current
if (before === plannedEntryIds) return
for (const item of itemsRef.current) {
if (before.has(item.id) === plannedEntryIds.has(item.id)) continue
markersRef.current.get(item.id)?.setIcon(entryIcon(item, highlightedRef.current === item.id, plannedEntryIds.has(item.id)))
}
iconPlannedRef.current = plannedEntryIds
}, [plannedEntryIds])
// Retile in place rather than through the effect above, which would drop every
// marker and track it just drew. A vector basemap restyles instead, which also
// avoids spending a WebGL context on every theme toggle.
// Under the imagery the basemap is not drawn at all, and the switch back draws
// it from the current template.
useEffect(() => {
if (satelliteRef.current) return
if (isVectorStyle(tileUrl)) restyleBasemap(glLayerRef.current, tileUrl)
else tileLayerRef.current?.setUrl(tileUrl)
}, [tileUrl, satelliteRef])
// Photo layer (#1614). Its own effect on purpose: photos arriving must not tear
// down and rebuild the map the way the entry effect does. Redrawn after every
// move, but the clusters sit on a world grid, so only a zoom regroups them.
useEffect(() => {
const map = mapRef.current
if (!map) return
const draw = () => {
photoLayerRef.current?.remove()
photoLayerRef.current = null
if (!photos?.length) return
// The initial view (setView/fitBounds) is set on a deferred rAF in the
// map-build effect above, so this can run before the map has a center/zoom
// and nothing can be projected in that window. Skip; the moveend/zoomend
// listener below redraws once the deferred view lands.
try {
map.getCenter()
} catch {
return
}
const group = L.layerGroup()
for (const cluster of clusterPhotos(photos, leafletWorldPx(map))) {
const marker = L.marker(framePoint(frameRef.current, cluster.lat, cluster.lng), {
icon: L.divIcon({
className: '',
iconSize: [48, 48],
iconAnchor: [24, 24],
html: photoMarkerHtml(cluster.members[0].thumbUrl, cluster.members.length),
}),
// Below the entry pins: the itinerary is the point of the map, the photos
// are context.
zIndexOffset: -500,
})
marker.on('click', () => onPhotoClickRef.current?.(cluster.members.map(m => m.id)))
group.addLayer(marker)
}
group.addTo(map)
photoLayerRef.current = group
}
draw()
map.on('zoomend', draw)
map.on('moveend', draw)
return () => {
map.off('zoomend', draw)
map.off('moveend', draw)
photoLayerRef.current?.remove()
photoLayerRef.current = null
}
}, [photos, entries, stableTrail, stableTracks, dark, fullScreen, paddingBottom])
// The plan's places and the stays of day reports (JRN-04), in their own layer
// like the photos: below the entry pins and above the thumbnails, regrouped
// on zoom because marks are only joined where they would overlap.
useEffect(() => {
const map = mapRef.current
if (!map) return
const draw = () => {
markLayerRef.current?.remove()
markLayerRef.current = drawLeafletMarks(map, marks, members => onMarksPickRef.current?.(members), frameRef.current)
}
const coords = markCoords(marks, frameRef.current)
if (!marksFramedRef.current && coords.length > 0) {
marksFramedRef.current = true
if (!readerMovedRef.current) map.fitBounds(L.latLngBounds([...entryCoordsRef.current, ...coords]), fitOptions(paddingBottom, paddingStartRef.current))
}
draw()
map.on('zoomend', draw)
map.on('moveend', draw)
return () => {
map.off('zoomend', draw)
map.off('moveend', draw)
markLayerRef.current?.remove()
markLayerRef.current = null
}
}, [marks, entries, stableTrail, stableTracks, dark, fullScreen, paddingBottom])
// react to activeMarkerId prop changes — runs after map is built
useEffect(() => {
if (!activeMarkerId || !mapRef.current) return
// small delay to ensure markers are rendered after map build
const timer = setTimeout(() => {
highlightMarker(activeMarkerId)
const marker = markersRef.current.get(activeMarkerId)
if (!marker || !mapRef.current) return
panToMarker(mapRef.current, marker)
}, 50)
return () => clearTimeout(timer)
}, [activeMarkerId])
const zoom = (closer: boolean) => {
readerMovedRef.current = true
if (closer) mapRef.current?.zoomIn()
else mapRef.current?.zoomOut()
}
return (
<div style={{ position: 'relative', height: height === 9999 ? '100%' : height, width: '100%', borderRadius: 'inherit', overflow: 'hidden' }}>
<div
ref={containerRef}
style={{ width: '100%', height: '100%' }}
/>
{/* A finger zooms with a pinch, and on a phone these sat under the bottom bar (#3001). */}
<div
// The display lives in the classes, not the style: an inline display beat the
// hidden class and left the buttons on phones.
className="flex flex-col gap-1 [@media(pointer:coarse)]:hidden"
style={{ position: 'absolute', bottom: 12, right: 12, zIndex: 400 }}
>
<button type="button" onClick={() => zoom(true)} style={zoomButtonStyle(dark)}>+</button>
<button type="button" onClick={() => zoom(false)} style={zoomButtonStyle(dark)}>−</button>
</div>
</div>
)
}
export default JourneyMap