Skip to content

armgit / TREK

Public Imported from GitHub
0

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.

fix(journey): draw lines across the antimeridian the short way on the Journey map (#3080)

Maurice535761dbd57f
diff --git a/client/src/components/Journey/JourneyMap.tsx b/client/src/components/Journey/JourneyMap.tsx
index dc85f653b..6119871a6 100644
--- a/client/src/components/Journey/JourneyMap.tsx
+++ b/client/src/components/Journey/JourneyMap.tsx
@@ -14,6 +14,8 @@ 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
@@ -286,8 +288,8 @@ 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): L.LatLngTuple[] {
- return (marks ?? []).map(mark => [mark.lat, mark.lng] as L.LatLngTuple)
+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 {
@@ -422,6 +424,9 @@ function JourneyMap(
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[]>([])
@@ -511,6 +516,11 @@ function JourneyMap(
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.
@@ -544,12 +554,14 @@ function JourneyMap(
const trackCoords: L.LatLngTuple[] = []
if (stableTrail.length > 1) {
- const coords = stableTrail.map(p => [p.lat, p.lng] as L.LatLngTuple)
- place('recorded', L.polyline(coords, {
- color: '#6366f1', weight: 3, opacity: 0.4,
- dashArray: '6 4', lineCap: 'round',
- }))
- coords.forEach(c => allCoords.push(c))
+ 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
@@ -558,22 +570,23 @@ function JourneyMap(
// 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 coords = track.points.map(([lat, lng]) => [lat, lng] as L.LatLngTuple)
const color = track.color || TRACK_FALLBACK_COLOR
const planned = isPlannedTrack(track)
const kind: LeafletLayerKind = planned ? 'plan' : 'recorded'
- 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)
- coords.forEach(c => trackCoords.push(c))
+ 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
@@ -586,12 +599,16 @@ function JourneyMap(
dashArray: '4 6',
lineCap: 'round', lineJoin: 'round',
}
- for (const line of connections.open) place('entries', L.polyline(line, connectionStyle))
- for (const line of connections.covered) place('coveredConnections', L.polyline(line, connectionStyle))
+ 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 = [item.lat, item.lng]
+ 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)) }))
@@ -617,7 +634,7 @@ function JourneyMap(
// 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)]
+ 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))
@@ -695,7 +712,7 @@ function JourneyMap(
const group = L.layerGroup()
for (const cluster of clusterPhotos(photos, leafletWorldPx(map))) {
- const marker = L.marker([cluster.lat, cluster.lng], {
+ const marker = L.marker(framePoint(frameRef.current, cluster.lat, cluster.lng), {
icon: L.divIcon({
className: '',
iconSize: [48, 48],
@@ -733,10 +750,10 @@ function JourneyMap(
const draw = () => {
markLayerRef.current?.remove()
- markLayerRef.current = drawLeafletMarks(map, marks, members => onMarksPickRef.current?.(members))
+ markLayerRef.current = drawLeafletMarks(map, marks, members => onMarksPickRef.current?.(members), frameRef.current)
}
- const coords = markCoords(marks)
+ 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))
diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx
index b1a76f931..72907cdb2 100644
--- a/client/src/components/Journey/JourneyMapGL.tsx
+++ b/client/src/components/Journey/JourneyMapGL.tsx
@@ -13,6 +13,8 @@ import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLay
import { MARK_CLUSTER_PX, PLANNED_BADGE_SVG, clusterPoints, glWorldPx, markHitSvg, type JourneyMapMark } from './journeyMapMarks'
import { isPlannedTrack, type JourneyMapLayerVisibility } from './journeyMapLayers'
import { coveredConnectionsShown, entryConnections } from './journeyMapConnections'
+import { journeyLines } from './journeyMapLines'
+import { alongShortestArc } from '../../utils/mapViewport'
export interface JourneyMapGLHandle {
highlightMarker: (id: string | null) => void
@@ -137,7 +139,12 @@ function addConnectionLayer(map: mapboxgl.Map, id: string, lines: [number, numbe
data: {
type: 'Feature',
properties: {},
- geometry: { type: 'MultiLineString', coordinates: lines.map(line => line.map(([lat, lng]) => [lng, lat])) },
+ // The short way across the antimeridian: the map repeats the world, so a
+ // continuous line is enough (#3080).
+ geometry: {
+ type: 'MultiLineString',
+ coordinates: lines.flatMap(line => journeyLines(null, line, false)).map(line => line.map(([lat, lng]) => [lng, lat])),
+ },
},
})
map.addLayer({
@@ -188,10 +195,18 @@ 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 box around `[lng, lat]` points and the marks, the short way across the
+ * antimeridian: a journey from Samoa to Fiji frames the few degrees between
+ * them, not the rest of the world (#3080).
+ */
function markBounds(gl: Props['gl'], marks: JourneyMapMark[], points: [number, number][] = []) {
const bounds = new gl.LngLatBounds()
- points.forEach(point => bounds.extend(point))
- marks.forEach(mark => bounds.extend([mark.lng, mark.lat]))
+ const latLngs = [
+ ...points.map(([lng, lat]) => [lat, lng] as [number, number]),
+ ...marks.map(mark => [mark.lat, mark.lng] as [number, number]),
+ ]
+ alongShortestArc(latLngs).forEach(([lat, lng]) => bounds.extend([lng, lat]))
return bounds
}
@@ -401,9 +416,8 @@ function JourneyMapGL(
const items = buildItems(entries)
itemsRef.current = items
- const bounds = new gl.LngLatBounds()
- items.forEach(i => bounds.extend([i.lng, i.lat]))
- stableTrail.forEach(p => bounds.extend([p.lng, p.lat]))
+ const entryPoints = [...items.map(i => [i.lng, i.lat] as [number, number]), ...stableTrail.map(p => [p.lng, p.lat] as [number, number])]
+ const bounds = markBounds(gl, [], entryPoints)
const hasPoints = items.length > 0 || stableTrail.length > 0
const mapOptions: Record<string, unknown> = {
@@ -431,7 +445,7 @@ function JourneyMapGL(
if (!map) return
mapRef.current = map
marksFramedRef.current = false
- entryPointsRef.current = [...items.map(i => [i.lng, i.lat] as [number, number]), ...stableTrail.map(p => [p.lng, p.lat] as [number, number])]
+ entryPointsRef.current = entryPoints
readerMovedRef.current = false
map.on('movestart', (ev: { originalEvent?: unknown }) => {
if (ev.originalEvent) readerMovedRef.current = true
@@ -482,7 +496,11 @@ function JourneyMapGL(
name: track.name,
planned: isPlannedTrack(track),
},
- geometry: { type: 'LineString' as const, coordinates: track.points.map(([lat, lng]) => [lng, lat]) },
+ // Continuous across the antimeridian, so a crossing is a short hop (#3080).
+ geometry: {
+ type: 'LineString' as const,
+ coordinates: journeyLines(null, track.points as [number, number][], false)[0].map(([lat, lng]) => [lng, lat]),
+ },
})),
}
if (featureCollection.features.length > 0) {
@@ -549,10 +567,9 @@ function JourneyMapGL(
// fit bounds to all points
const known = marksRef.current ?? []
marksFramedRef.current = known.length > 0
- known.forEach(mark => bounds.extend([mark.lng, mark.lat]))
if (hasPoints || known.length > 0) {
try {
- map.fitBounds(bounds, fitOptions(paddingBottom, enableMapbox3d && fullScreen, paddingStartRef.current))
+ map.fitBounds(known.length > 0 ? markBounds(gl, known, entryPoints) : bounds, fitOptions(paddingBottom, enableMapbox3d && fullScreen, paddingStartRef.current))
} catch { /* empty bounds */ }
}
})
diff --git a/client/src/components/Journey/journeyLeafletLayers.ts b/client/src/components/Journey/journeyLeafletLayers.ts
index e6d9754dc..61985d7e3 100644
--- a/client/src/components/Journey/journeyLeafletLayers.ts
+++ b/client/src/components/Journey/journeyLeafletLayers.ts
@@ -1,4 +1,5 @@
import L from 'leaflet';
+import { frameLng, type LngFrame } from '../../utils/lngFrame';
import { coveredConnectionsShown } from './journeyMapConnections';
import type { JourneyMapLayerVisibility } from './journeyMapLayers';
import { MARK_CLUSTER_PX, clusterPoints, markHitSvg, type JourneyMapMark, type WorldPx } from './journeyMapMarks';
@@ -51,12 +52,14 @@ export function leafletWorldPx(map: L.Map): WorldPx {
/**
* The plan's places and the stays as one layer: below the entry pins, above
* the photo thumbnails, joined only where they would overlap on screen.
- * Null while there is nothing to draw or the map has no view yet.
+ * Null while there is nothing to draw or the map has no view yet. `frame` is the
+ * map's longitude frame (#3080), so a mark lands on the world copy its pins are on.
*/
export function drawLeafletMarks(
map: L.Map,
marks: readonly JourneyMapMark[] | undefined,
- onPick: (members: JourneyMapMark[]) => void
+ onPick: (members: JourneyMapMark[]) => void,
+ frame: LngFrame | null = null
): L.LayerGroup | null {
if (!marks?.length) return null;
try {
@@ -68,7 +71,7 @@ export function drawLeafletMarks(
const group = L.layerGroup();
for (const hit of clusterPoints(marks, leafletWorldPx(map), MARK_CLUSTER_PX)) {
const look = markHitSvg(hit.members);
- const marker = L.marker([hit.lat, hit.lng], {
+ const marker = L.marker([hit.lat, frameLng(frame, hit.lng)], {
icon: L.divIcon({
className: '',
iconSize: [look.width, look.height],
diff --git a/client/src/components/Journey/journeyMapLines.test.ts b/client/src/components/Journey/journeyMapLines.test.ts
new file mode 100644
index 000000000..c75fa5a04
--- /dev/null
+++ b/client/src/components/Journey/journeyMapLines.test.ts
@@ -0,0 +1,69 @@
+// FE-JRN-LINES-001 to FE-JRN-LINES-005
+import type { JourneyTrack } from '@trek/shared';
+import { describe, expect, it } from 'vitest';
+import { framePoint, journeyLines, journeyLngFrame } from './journeyMapLines';
+
+type LatLng = [number, number];
+
+const SAMOA: LatLng = [-13.83, -171.76];
+const FIJI: LatLng = [-18.14, 178.44];
+// The ship from the report, a step across the date line between two Dawarich points.
+const SHIP: LatLng[] = [
+ [-17.0891, -179.9995],
+ [-17.0892, -179.9999],
+ [-17.0894, 179.9998],
+ [-17.0895, 179.9991],
+];
+
+const maxStep = (line: LatLng[]) =>
+ line.reduce((max, p, i) => (i === 0 ? 0 : Math.max(max, Math.abs(p[1] - line[i - 1][1]))), 0);
+
+function recorded(points: LatLng[]): JourneyTrack {
+ return { place_id: -1, trip_id: 0, name: 'Ship', color: null, points, kind: 'dawarich_live', date: '2026-10-09' };
+}
+
+describe('journeyLines (#3080)', () => {
+ it('FE-JRN-LINES-001: a GL map draws a recorded line across the antimeridian as a short hop, not round the world', () => {
+ const lines = journeyLines(null, SHIP, false);
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toHaveLength(SHIP.length);
+ expect(maxStep(lines[0])).toBeLessThan(0.01);
+ expect(lines[0][0]).toEqual(SHIP[0]);
+ });
+
+ it('FE-JRN-LINES-002: Leaflet draws the line and its pins on one world copy, in the journey frame', () => {
+ const frame = journeyLngFrame([{ lng: SAMOA[1] }, { lng: FIJI[1] }], [recorded(SHIP)]);
+ expect(frame).not.toBeNull();
+ const [line] = journeyLines(frame, SHIP, true);
+ expect(maxStep(line)).toBeLessThan(0.01);
+ const samoa = framePoint(frame, SAMOA[0], SAMOA[1])[1];
+ const fiji = framePoint(frame, FIJI[0], FIJI[1])[1];
+ // Fiji, the ship and Samoa sit within a few degrees of each other, on one copy.
+ expect(Math.abs(samoa - fiji)).toBeCloseTo(9.8, 1);
+ for (const [, lng] of line) {
+ expect(lng).toBeGreaterThanOrEqual(Math.min(samoa, fiji));
+ expect(lng).toBeLessThanOrEqual(Math.max(samoa, fiji));
+ }
+ });
+
+ it('FE-JRN-LINES-003: the faint line between two entries across the date line takes the short way', () => {
+ const [line] = journeyLines(null, [SAMOA, FIJI], false);
+ expect(Math.abs(line[1][1] - line[0][1])).toBeCloseTo(9.8, 1);
+ });
+
+ it('FE-JRN-LINES-004: a journey off the antimeridian keeps no frame and its lines as they were', () => {
+ const paris: LatLng = [48.85, 2.35];
+ const berlin: LatLng = [52.52, 13.4];
+ expect(journeyLngFrame([{ lng: paris[1] }, { lng: berlin[1] }], [])).toBeNull();
+ expect(journeyLines(null, [paris, berlin], true)).toEqual([[paris, berlin]]);
+ expect(framePoint(null, paris[0], paris[1])).toEqual(paris);
+ });
+
+ it('FE-JRN-LINES-005: without a frame Leaflet also gets the line shifted a world over, so the part past ±180 shows', () => {
+ const lines = journeyLines(null, [FIJI, SAMOA], true);
+ expect(lines).toHaveLength(2);
+ expect(lines[0][1][1]).toBeGreaterThan(180);
+ expect(lines[1][0][1]).toBeCloseTo(FIJI[1] - 360, 9);
+ expect(lines[1][1][1]).toBeCloseTo(lines[0][1][1] - 360, 9);
+ });
+});
diff --git a/client/src/components/Journey/journeyMapLines.ts b/client/src/components/Journey/journeyMapLines.ts
new file mode 100644
index 000000000..f0e1b6fa8
--- /dev/null
+++ b/client/src/components/Journey/journeyMapLines.ts
@@ -0,0 +1,64 @@
+// The lines of a journey map, laid the short way across the antimeridian (#3080).
+//
+// A recorded day, a trip's GPX and the faint line between entries all come as
+// points with longitudes in [-180, 180]. A ship from Samoa to Fiji therefore steps
+// from -179.9999 to 179.9998, and both renderers drew that step as a line across
+// the whole world. The trip's plan map solved this for its own layers (#2975,
+// #2977); the journey map draws with the same tools here.
+//
+// Leaflet draws every layer at its literal longitude on one copy of the world, so
+// it gets the trip's longitude frame: the seam moves into the widest stretch the
+// journey leaves empty, and pins and lines are drawn in it on one copy. A GL map
+// repeats the world itself and places each pin on the copy nearest the view, so
+// there a line only has to stay continuous.
+
+import type { JourneyTrack } from '@trek/shared';
+import { frameLine, frameLng, tripLngFrame, type LngFrame } from '../../utils/lngFrame';
+import { unwrapLngs } from '../Map/flightGeodesy';
+
+/** A point of a line, `[lat, lng]`. */
+type LatLng = [number, number];
+
+/**
+ * The frame the Leaflet journey map draws in, from everything it locates: the
+ * entries, the trail and every track. Null for a journey that stays off the
+ * antimeridian, which then draws exactly as before. `previous` is kept while it
+ * still fits, so a rebuild does not slide the map sideways.
+ */
+export function journeyLngFrame(
+ points: readonly { lng: number }[],
+ tracks: readonly JourneyTrack[],
+ previous: LngFrame | null = null
+): LngFrame | null {
+ const lngs: number[] = [];
+ for (const point of points) lngs.push(point.lng);
+ for (const track of tracks) for (const [, lng] of track.points) lngs.push(lng);
+ return tripLngFrame(lngs, previous);
+}
+
+/**
+ * The polylines to draw for one line of the journey map. Every step between two
+ * points takes the short way, so a crossing of the antimeridian stays a short hop.
+ *
+ * With a frame (Leaflet, a journey across the antimeridian) the line is drawn in
+ * it, beside the pins. Without one the line starts where its first point is and
+ * runs on past ±180 where it crosses; `wrapCopies` (Leaflet, whose vector layers
+ * do not repeat across world copies) then adds the same line shifted by 360
+ * degrees, so the part past the edge shows on the world the pins are on. A GL map
+ * repeats the line itself and needs no copy.
+ */
+export function journeyLines(frame: LngFrame | null, line: readonly LatLng[], wrapCopies: boolean): LatLng[][] {
+ if (frame) return [frameLine(frame, line)];
+ const unwrapped = unwrapLngs(line as LatLng[]);
+ if (!wrapCopies) return [unwrapped];
+ const west = unwrapped.some(([, lng]) => lng < -180);
+ const east = unwrapped.some(([, lng]) => lng > 180);
+ if (!west && !east) return [unwrapped];
+ const shift = west ? 360 : -360;
+ return [unwrapped, unwrapped.map(([lat, lng]) => [lat, lng + shift] as LatLng)];
+}
+
+/** A point as the frame draws it; without a frame it is drawn where it is. */
+export function framePoint(frame: LngFrame | null, lat: number, lng: number): LatLng {
+ return [lat, frameLng(frame, lng)];
+}