fix(map): draw points of interest on the world copy the view is on

POIs fetched for a view west of the trip frame's seam were drawn one world
away, off screen.
This commit is contained in:
Maurice
2026-11-05 13:02:29 +01:00
parent 13376d560f
commit b9c53d692b
6 changed files with 103 additions and 11 deletions
+5 -5
View File
@@ -4,14 +4,14 @@ import L from 'leaflet'
import { useTranslation } from '../../i18n/TranslationContext'
import type { Poi } from './poiCategories'
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
import { useLngFrame } from './lngFrameContext'
import { frameLng } from '../../utils/lngFrame'
import { frameLng, type LngFrame } from '../../utils/lngFrame'
export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
export default function ClusteredPois({ pois, frame, enabled, onPoiClick, children }: {
pois: Poi[]; enabled: boolean; onPoiClick?: (poi: Poi) => void; children: ReactNode[]
/** The frame the markers in `children` are drawn in: the view's, not the trip's (see MapView). */
frame: LngFrame | null
}) {
const map = useMap()
const frame = useLngFrame()
const { t } = useTranslation()
const [zoom, setZoom] = useState(() => map.getZoom())
const popup = useRef<L.Popup | null>(null)
@@ -21,7 +21,7 @@ export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
map.on('zoomend', update)
return () => { map.off('zoomend', update) }
}, [map])
// Measured and placed where the map draws them, in its longitude frame (#2975).
// Measured and placed where the markers are drawn, on the world copy in view (#2975).
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, frameLng(frame, poi.lng)]), zoom) : [], [pois, enabled, map, zoom, frame])
const markers = new Map(pois.map((poi, index) => [poi.osm_id, children[index]]))
if (!enabled) return <>{children}</>
@@ -43,6 +43,7 @@ import { MapView } from './MapView'
import { ContextMenu } from '../shared/ContextMenu'
import type { Ferrata } from '@trek/shared'
import { groupFerratas } from '../Ferratas/ferrataGroups'
import type { Poi } from './poiCategories'
// Every map this file builds, newest last, for the tests that reach past the component.
const maps: L.Map[] = []
@@ -483,4 +484,28 @@ describe('MapView on a real Leaflet map', () => {
expect(view.getByRole('button', { name: 'Via ferratas' })).toHaveAttribute('aria-pressed', 'true')
expect(view.getByTestId('ferrata-count-badge')).toHaveTextContent('1')
})
it('draws POIs found outside the trip frame where the user is looking, not one world away (#2975)', async () => {
// Seattle and Los Angeles to Auckland: the trip is drawn in a frame seamed near 28 degrees east.
const pacific = [
{ ...buildPlace({ id: 11, name: 'Seattle', lat: 47.6, lng: -122.3 }), category_name: null, category_color: null, category_icon: null },
{ ...buildPlace({ id: 12, name: 'Los Angeles', lat: 34.05, lng: -118.2 }), category_name: null, category_color: null, category_icon: null },
{ ...buildPlace({ id: 13, name: 'Auckland', lat: -36.85, lng: 174.8 }), category_name: null, category_color: null, category_icon: null },
]
const acropolis = {
osm_id: 'node/1', name: 'Acropolis', lat: 37.97, lng: 23.73, category: 'sights', poi_type: 'attraction',
address: null, website: null, phone: null, opening_hours: null, cuisine: null,
} as Poi
render(<MapView places={pacific} center={[38, 10]} zoom={5} tileUrl={RASTER} pois={[acropolis]} />)
const map = maps[maps.length - 1]
// The user pans west past the seam to look at the Mediterranean on the real world.
act(() => { map.setView([38, 10], 5, { animate: false }) })
const marker = () => {
let found: L.Marker | null = null
map.eachLayer(layer => { if (layer instanceof L.Marker && layer.options.alt === 'Acropolis') found = layer })
return found as L.Marker | null
}
await waitFor(() => expect(marker()?.getLatLng().lng).toBeCloseTo(23.73, 6))
expect(map.getBounds().contains(marker()!.getLatLng())).toBe(true)
})
})
+10 -5
View File
@@ -523,8 +523,8 @@ import { useIsPhone } from '../../mobile/useIsPhone'
import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation'
import { selectedPlaceTarget } from './selectedPlaceTarget'
import { LngFrameProvider, useLngFrame, useTripLngFrame } from './lngFrameContext'
import { frameLine, frameLng } from '../../utils/lngFrame'
import { LngFrameFollower, MapClickHandler, MapContextMenuHandler, PoiDropTarget, ViewportController } from './leafletMapBridges'
import { frameLine, frameLng, viewLngFrame, type LngFrame } from '../../utils/lngFrame'
import { LngFrameFollower, MapClickHandler, MapContextMenuHandler, PoiDropTarget, ViewCenterTracker, ViewportController } from './leafletMapBridges'
function LeafletLocationLayer({ position: fix, mode }: { position: GeoPosition | null; mode: TrackingMode }) {
const map = useMap()
@@ -774,11 +774,15 @@ export const MapView = memo(function MapView({
// drawn in a longitude frame that keeps it on one copy (#2975). Null for every other
// trip, and then each layer below draws exactly what it always drew.
const lngFrame = useTripLngFrame(places, dayPlaces, reservations)
// The POIs are fetched for the visible area, which can lie outside the trip's frame
// or on another world copy, so they are drawn on the copy in view instead.
const [poiFrame, setPoiFrame] = useState<LngFrame | null>(null)
const followView = useCallback((centerLng: number) => setPoiFrame(current => viewLngFrame(current, centerLng)), [])
const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => (
<Marker
key={`poi-${poi.osm_id}`}
alt={poi.name}
position={[poi.lat, frameLng(lngFrame, poi.lng)]}
position={[poi.lat, frameLng(poiFrame, poi.lng)]}
icon={createPoiIcon(poi, poi.brand_wikidata)}
zIndexOffset={500}
eventHandlers={{
@@ -797,7 +801,7 @@ export const MapView = memo(function MapView({
>
<Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip"><PoiTooltipBody poi={poi} /></Tooltip>
</Marker>
)), [pois, onPoiClick, onPoiDropOnRoute, lngFrame])
)), [pois, onPoiClick, onPoiDropOnRoute, poiFrame])
const visibleReservations = useMemo(() => (
visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay })
), [reservations, visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay])
@@ -1079,6 +1083,7 @@ export const MapView = memo(function MapView({
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
<ViewportController onViewportChange={onViewportChange} />
<ViewCenterTracker onChange={followView} />
<PoiDropTarget onPoiDropOnRoute={onPoiDropOnRoute} />
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
@@ -1223,7 +1228,7 @@ export const MapView = memo(function MapView({
hiddenDates={dawarichHiddenDates}
casingPane={hasCasingPane ? TRACK_CASING_PANE : undefined}
/>
<ClusteredPois pois={pois} enabled={clusterLoosely} onPoiClick={onPoiClick}>{poiMarkers}</ClusteredPois>
<ClusteredPois pois={pois} frame={poiFrame} enabled={clusterLoosely} onPoiClick={onPoiClick}>{poiMarkers}</ClusteredPois>
{/* Charging stops / rest areas a plugin route places on the drawn day route.
Host-vetted data (server-normalized), rendered as plain tone dots. */}
{(routeVias as RouteVia[]).filter(v => !v.nightPause || mapZoom >= NIGHT_PAUSE_MIN_ZOOM).map((v, i) => (
@@ -57,6 +57,23 @@ export function ViewportController({ onViewportChange }: { onViewportChange?: Ma
return null;
}
/**
* Reports the longitude of the view's centre once the map is laid out and after every
* move, for the layers drawn on the world copy in view rather than in the trip's frame.
*/
export function ViewCenterTracker({ onChange }: { onChange: (centerLng: number) => void }) {
const map = useMap();
useEffect(() => {
const emit = () => onChange(map.getCenter().lng);
map.whenReady(emit);
map.on('moveend', emit);
return () => {
map.off('moveend', emit);
};
}, [map, onChange]);
return null;
}
/**
* Moves the view along when the longitude frame changes under it (#2975): the trip
* is then drawn one world further east or west, and a view left where it was would
+30 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { frameLine, frameLng, tripLngFrame } from './lngFrame';
import { frameLine, frameLng, tripLngFrame, viewLngFrame } from './lngFrame';
const LA = -118.4;
const AUCKLAND = 174.8;
@@ -83,3 +83,32 @@ describe('frameLine', () => {
expect(drawn.map(([, lng]) => lng)).toEqual([30, 20]);
});
});
describe('viewLngFrame', () => {
it('keeps the plain world while the view looks at the real world', () => {
expect(viewLngFrame(null, 0)).toBeNull();
expect(viewLngFrame(null, 10)).toBeNull();
expect(viewLngFrame(null, -90)).toBeNull();
});
it('keeps the frame in use while the view stays near its middle, so a pan redraws nothing', () => {
const frame = { seam: 28.4 };
expect(viewLngFrame(frame, 208.4)).toBe(frame);
expect(viewLngFrame(frame, 130)).toBe(frame);
});
it('centres the frame on a view outside the trip frame, so places found there are drawn there', () => {
// A trip from Los Angeles to Auckland, seamed at 28.4, with the user looking at Europe.
const frame = viewLngFrame({ seam: 28.4 }, 10);
expect(frame).toEqual({ seam: -170 });
expect(frameLng(frame, 12)).toBeCloseTo(12, 6);
expect(frameLng(frame, 23.7)).toBeCloseTo(23.7, 6);
expect(frameLng(frame, -5)).toBeCloseTo(-5, 6);
});
it('centres the frame on a view of a world copy', () => {
const frame = viewLngFrame(null, 495);
expect(frame).toEqual({ seam: 315 });
expect(frameLng(frame, 139.7)).toBeCloseTo(499.7, 6);
});
});
+16
View File
@@ -106,3 +106,19 @@ export function frameLine<T extends readonly [number, number]>(
}
return out;
}
/**
* A frame for layers fetched for the visible area rather than drawn with the trip,
* such as the POIs the explore pill finds: those come back at their real longitudes
* and belong on the copy the user is looking at, even outside the trip's frame.
*
* The frame in use is kept while the view's centre stays within a quarter world of
* its middle, so a pan does not redraw every marker; past that it is centred on the
* view. Either way a view up to half a world wide lies inside it. `null` is the
* plain world, whose middle is 0, and is kept as null while it fits.
*/
export function viewLngFrame(current: LngFrame | null, centerLng: number): LngFrame | null {
const middle = current ? current.seam + 180 : 0;
if (Math.abs(centerLng - middle) <= 90) return current;
return { seam: centerLng - 180 };
}