mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
* fix(map): fit MapLibre routes reliably * fix(map): default planner map to world view * fix(map): only await route geometry when a route is actually pending The fit armed a pending route-refit slot on every fitKey change, even with no route drawn, and only ever cleared it when a route arrived. So a route toggled on much later — after the user had panned elsewhere — was mistaken for the awaited geometry and yanked the camera back, and only on the first toggle. Arm the slot only when a route is already on screen: updateRouteForDay lays down straight lines in the same batch as the fit and upgrades them to real geometry a moment later, so an empty route at fit time means none is coming. * fix(collections): open the empty collection map on the world view A collection with no mappable places centred on Paris, the same hardcoded default this branch removes everywhere else. * feat(map): open the map framed on its places A trip in Japan opened on the world view at 0,0 and only then animated a fitBounds flight across the planet — the hardcoded default was the map's answer to a question its own places already answer. Each renderer now derives its opening camera from the places it receives, at construction: MapView for Leaflet, MapViewGL for MapLibre and Mapbox (whose zoom runs one level below Leaflet's, measuring against a 512px world tile rather than 256px). Doing it at construction is what confines it to load — the map is built once, and by then the trip's places are in hand. Nothing recomputes it afterwards, so the camera stays where the user leaves it, and the opening fit stands down rather than overruling the gentler zoom a lone place opens at. A trip with no coordinates still falls back to the world view. Collections and the public shared-trip page frame themselves the same way. * refactor(settings): drop the default map centre and zoom Nothing reads them now that every map frames itself on its own places, and a home-city default was the wrong answer for the next trip on the other side of the world. The style preview keeps a fixed location of its own: it needs a city to show label density and 3D buildings, which open ocean cannot. * fix(map): frame the map the way each renderer can actually draw Two defects the unit tests missed and running the app exposed. MapLibre and Mapbox opened on Null Island at zoom 2 regardless of the places: the effect that mirrors an external centre prop onto the camera also ran on mount, so it jumped straight to the default nobody passed and threw away the camera the map had just been built with. It now only responds to actual changes, which is what it was for. Leaflet was unaffected — its controller already guarded on the centre changing. A trip spanning Sydney, Reykjavik and Santiago lost Sydney's marker entirely. The narrowest arc containing all three crosses the antimeridian, and framing there is only sound on a renderer that repeats the world: MapLibre and Mapbox draw a marker on whichever copy is nearest the camera, Leaflet draws one world and puts the marker at its absolute position — off-screen. Leaflet now spans the long way round, as L.latLngBounds would. The test that should have caught this wrapped the x-offset in its own projection helper, quietly assuming behaviour Leaflet does not have; it now models each renderer's real wrapping. --------- Co-authored-by: Azalea <noreply@aza.moe>
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
computeMapViewport,
|
||||
MAX_ZOOM_GL,
|
||||
MAX_ZOOM_RASTER,
|
||||
SINGLE_PLACE_ZOOM_RASTER,
|
||||
TILE_SIZE_GL,
|
||||
TILE_SIZE_RASTER,
|
||||
} from './mapViewport'
|
||||
|
||||
// Pin the container size so no assertion depends on jsdom's window dimensions.
|
||||
const VIEW = { width: 1000, height: 800 } as const
|
||||
|
||||
const PARIS = { lat: 48.8566, lng: 2.3522 }
|
||||
const LYON = { lat: 45.764, lng: 4.8357 }
|
||||
|
||||
/**
|
||||
* The invariant that actually matters: every place must land inside the container at the
|
||||
* returned camera. Mirrors the Mercator projection the map uses.
|
||||
*/
|
||||
function screenPosition(
|
||||
point: { lat: number; lng: number },
|
||||
viewport: { center: [number, number]; zoom: number },
|
||||
tileSize: number,
|
||||
size = VIEW,
|
||||
// Only MapLibre/Mapbox redraw a marker on the nearest copy of the world. Leaflet places it
|
||||
// at its absolute projected position, so assuming a wrap here would hide exactly the bug
|
||||
// that puts a marker off-screen in the real app.
|
||||
wrapsWorld = false,
|
||||
): { x: number; y: number } {
|
||||
const project = (lat: number, lng: number) => {
|
||||
const scale = tileSize * Math.pow(2, viewport.zoom)
|
||||
const sin = Math.sin((lat * Math.PI) / 180)
|
||||
return {
|
||||
x: scale * (lng / 360 + 0.5),
|
||||
y: scale * (0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)),
|
||||
}
|
||||
}
|
||||
const p = project(point.lat, point.lng)
|
||||
const c = project(viewport.center[0], viewport.center[1])
|
||||
|
||||
const worldWidth = tileSize * Math.pow(2, viewport.zoom)
|
||||
const raw = p.x - c.x
|
||||
const dx = wrapsWorld
|
||||
? ((raw + worldWidth / 2) % worldWidth + worldWidth) % worldWidth - worldWidth / 2
|
||||
: raw
|
||||
|
||||
return { x: dx + size.width / 2, y: p.y - c.y + size.height / 2 }
|
||||
}
|
||||
|
||||
describe('computeMapViewport', () => {
|
||||
it('frames a set of places so all of them are on screen', () => {
|
||||
const viewport = computeMapViewport([PARIS, LYON], { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
|
||||
// Latitude is the midpoint in projected space, so it sits near — but not exactly on —
|
||||
// the arithmetic mean; Mercator stretches towards the poles. Longitude is linear.
|
||||
expect(viewport.center[0]).toBeCloseTo((PARIS.lat + LYON.lat) / 2, 1)
|
||||
expect(viewport.center[1]).toBeCloseTo((PARIS.lng + LYON.lng) / 2, 6)
|
||||
|
||||
for (const place of [PARIS, LYON]) {
|
||||
const { x, y } = screenPosition(place, viewport, TILE_SIZE_RASTER)
|
||||
expect(x).toBeGreaterThanOrEqual(0)
|
||||
expect(x).toBeLessThanOrEqual(VIEW.width)
|
||||
expect(y).toBeGreaterThanOrEqual(0)
|
||||
expect(y).toBeLessThanOrEqual(VIEW.height)
|
||||
}
|
||||
})
|
||||
|
||||
it('opens at city level for a single place', () => {
|
||||
const viewport = computeMapViewport([PARIS], { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
|
||||
expect(viewport.center[0]).toBeCloseTo(PARIS.lat, 6)
|
||||
expect(viewport.center[1]).toBeCloseTo(PARIS.lng, 6)
|
||||
expect(viewport.zoom).toBe(SINGLE_PLACE_ZOOM_RASTER)
|
||||
})
|
||||
|
||||
it('treats several places stacked on one spot as a single place, without dividing by zero', () => {
|
||||
const viewport = computeMapViewport([PARIS, { ...PARIS }, { ...PARIS }], {
|
||||
...VIEW,
|
||||
tileSize: TILE_SIZE_RASTER,
|
||||
})!
|
||||
|
||||
expect(Number.isFinite(viewport.zoom)).toBe(true)
|
||||
expect(viewport.zoom).toBe(SINGLE_PLACE_ZOOM_RASTER)
|
||||
})
|
||||
|
||||
it('frames places sharing a latitude, using the longitude span alone', () => {
|
||||
const viewport = computeMapViewport(
|
||||
[{ lat: 48.8566, lng: 2.0 }, { lat: 48.8566, lng: 4.0 }],
|
||||
{ ...VIEW, tileSize: TILE_SIZE_RASTER },
|
||||
)!
|
||||
|
||||
expect(Number.isFinite(viewport.zoom)).toBe(true)
|
||||
expect(viewport.zoom).toBeLessThan(MAX_ZOOM_RASTER)
|
||||
expect(viewport.center[1]).toBeCloseTo(3.0, 3)
|
||||
})
|
||||
|
||||
it('returns null when nothing has usable coordinates', () => {
|
||||
expect(computeMapViewport([], VIEW)).toBeNull()
|
||||
expect(computeMapViewport([{ lat: null, lng: null }], VIEW)).toBeNull()
|
||||
expect(computeMapViewport([{ lat: 48.85, lng: null }], VIEW)).toBeNull()
|
||||
expect(computeMapViewport([{ lat: NaN, lng: 2.35 }], VIEW)).toBeNull()
|
||||
expect(computeMapViewport([{ lat: 200, lng: 2.35 }], VIEW)).toBeNull()
|
||||
expect(computeMapViewport([{ lat: 48.85, lng: 999 }], VIEW)).toBeNull()
|
||||
})
|
||||
|
||||
it('treats 0,0 as a real coordinate rather than a missing one', () => {
|
||||
const viewport = computeMapViewport([{ lat: 0, lng: 0 }], { ...VIEW, tileSize: TILE_SIZE_RASTER })
|
||||
|
||||
expect(viewport).not.toBeNull()
|
||||
expect(viewport!.center[0]).toBeCloseTo(0, 6)
|
||||
expect(viewport!.center[1]).toBeCloseTo(0, 6)
|
||||
})
|
||||
|
||||
const FIJI = { lat: -18.14, lng: 178.44 }
|
||||
const SAMOA = { lat: -13.76, lng: -172.1 }
|
||||
|
||||
it('takes the short way round the antimeridian on a renderer that wraps the world', () => {
|
||||
// Fiji and Samoa are 10 degrees apart, not 350 — MapLibre/Mapbox draw each marker on the
|
||||
// copy of the world nearest the camera, so this centre is safe there.
|
||||
const viewport = computeMapViewport([FIJI, SAMOA], { ...VIEW, tileSize: TILE_SIZE_GL })!
|
||||
|
||||
expect(viewport.center[1]).toBeCloseTo(-176.83, 1)
|
||||
// A 350-degree span would have collapsed the zoom to the world view.
|
||||
expect(viewport.zoom).toBeGreaterThan(3)
|
||||
})
|
||||
|
||||
it('goes the long way round on Leaflet, which does not wrap markers', () => {
|
||||
// Leaflet draws a single world and places markers at their absolute position. Centring on
|
||||
// the antimeridian would leave one of these two outside it entirely — so span the 350
|
||||
// degrees instead, as L.latLngBounds would.
|
||||
const viewport = computeMapViewport([FIJI, SAMOA], { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
|
||||
expect(viewport.center[1]).toBeCloseTo(3.17, 1)
|
||||
// Nearly the whole globe: zoomed right out, not framed tight on the Pacific.
|
||||
expect(viewport.zoom).toBeLessThanOrEqual(2)
|
||||
|
||||
for (const place of [FIJI, SAMOA]) {
|
||||
const { x } = screenPosition(place, viewport, TILE_SIZE_RASTER)
|
||||
expect(x).toBeGreaterThanOrEqual(0)
|
||||
expect(x).toBeLessThanOrEqual(VIEW.width)
|
||||
}
|
||||
})
|
||||
|
||||
it('clamps latitude at the poles instead of projecting to infinity', () => {
|
||||
const viewport = computeMapViewport(
|
||||
[{ lat: 90, lng: 0 }, { lat: 80, lng: 10 }],
|
||||
{ ...VIEW, tileSize: TILE_SIZE_RASTER },
|
||||
)!
|
||||
|
||||
expect(Number.isFinite(viewport.zoom)).toBe(true)
|
||||
expect(viewport.center[0]).toBeLessThanOrEqual(85.0511)
|
||||
})
|
||||
|
||||
it('returns a GL zoom exactly one level below the raster zoom for the same view', () => {
|
||||
const raster = computeMapViewport([PARIS, LYON], { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
const gl = computeMapViewport([PARIS, LYON], { ...VIEW, tileSize: TILE_SIZE_GL })!
|
||||
|
||||
expect(gl.zoom).toBeCloseTo(raster.zoom - 1, 6)
|
||||
expect(gl.center).toEqual(raster.center)
|
||||
})
|
||||
|
||||
it('never zooms past the renderer maxZoom for two nearly identical places', () => {
|
||||
const almost = { lat: PARIS.lat + 0.00001, lng: PARIS.lng + 0.00001 }
|
||||
|
||||
expect(computeMapViewport([PARIS, almost], { ...VIEW, tileSize: TILE_SIZE_RASTER })!.zoom)
|
||||
.toBe(MAX_ZOOM_RASTER)
|
||||
expect(computeMapViewport([PARIS, almost], { ...VIEW, tileSize: TILE_SIZE_GL })!.zoom)
|
||||
.toBe(MAX_ZOOM_GL)
|
||||
})
|
||||
|
||||
// Sydney, Reykjavik and Santiago: the narrowest arc containing all three crosses the
|
||||
// antimeridian. On Leaflet that centre put Sydney outside the one world it draws — the
|
||||
// marker simply vanished. Assert against each renderer's real wrapping behaviour.
|
||||
const GLOBE = [
|
||||
{ lat: -33.87, lng: 151.21 }, // Sydney
|
||||
{ lat: 64.15, lng: -21.94 }, // Reykjavik
|
||||
{ lat: -33.45, lng: -70.67 }, // Santiago
|
||||
]
|
||||
|
||||
it('keeps a globe-spanning trip on screen in Leaflet, which does not wrap', () => {
|
||||
const viewport = computeMapViewport(GLOBE, { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
|
||||
expect(viewport.zoom).toBeGreaterThanOrEqual(0)
|
||||
expect(viewport.zoom).toBeLessThan(5)
|
||||
|
||||
for (const place of GLOBE) {
|
||||
const { x, y } = screenPosition(place, viewport, TILE_SIZE_RASTER)
|
||||
expect(x).toBeGreaterThanOrEqual(0)
|
||||
expect(x).toBeLessThanOrEqual(VIEW.width)
|
||||
expect(y).toBeGreaterThanOrEqual(0)
|
||||
expect(y).toBeLessThanOrEqual(VIEW.height)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a globe-spanning trip on screen in GL, which does wrap', () => {
|
||||
const viewport = computeMapViewport(GLOBE, { ...VIEW, tileSize: TILE_SIZE_GL })!
|
||||
|
||||
for (const place of GLOBE) {
|
||||
const { x, y } = screenPosition(place, viewport, TILE_SIZE_GL, VIEW, true)
|
||||
expect(x).toBeGreaterThanOrEqual(0)
|
||||
expect(x).toBeLessThanOrEqual(VIEW.width)
|
||||
expect(y).toBeGreaterThanOrEqual(0)
|
||||
expect(y).toBeLessThanOrEqual(VIEW.height)
|
||||
}
|
||||
})
|
||||
|
||||
it('shifts the center so places clear a left-hand panel', () => {
|
||||
const unpadded = computeMapViewport([PARIS, LYON], { ...VIEW, tileSize: TILE_SIZE_RASTER })!
|
||||
const padded = computeMapViewport([PARIS, LYON], {
|
||||
...VIEW,
|
||||
tileSize: TILE_SIZE_RASTER,
|
||||
padding: { left: 400 },
|
||||
})!
|
||||
|
||||
// The camera pulls west so the places sit right of the panel, in the visible area.
|
||||
expect(padded.center[1]).toBeLessThan(unpadded.center[1])
|
||||
|
||||
// And they still fit: the panel eats 400px, so check against the visible width.
|
||||
for (const place of [PARIS, LYON]) {
|
||||
const { x } = screenPosition(place, padded, TILE_SIZE_RASTER)
|
||||
expect(x).toBeGreaterThanOrEqual(400)
|
||||
expect(x).toBeLessThanOrEqual(VIEW.width)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Frames a set of places: turns their coordinates into the camera (center + zoom) a map
|
||||
* should open at, so a trip in Japan opens on Japan instead of on the world view followed
|
||||
* by a fitBounds flight across the planet.
|
||||
*
|
||||
* Renderers call this once, at construction — see MapView.tsx / MapViewGL.tsx. Returns
|
||||
* null when no point has usable coordinates (a brand-new trip), leaving the caller to fall
|
||||
* back to DEFAULT_MAP_CENTER / DEFAULT_MAP_ZOOM.
|
||||
*
|
||||
* The bbox min/max here deliberately duplicates the few lines in sync/tilePrefetcher.ts
|
||||
* rather than importing them: that module pulls in Dexie at import time, which has no place
|
||||
* in a map's render path or in a pure-math unit test, and its padding + minimum-span rules
|
||||
* are tuned for enumerating tiles, not for framing a camera.
|
||||
*/
|
||||
|
||||
/** Web Mercator diverges at the poles — projections clamp latitude to this. */
|
||||
const MERCATOR_MAX_LAT = 85.0511
|
||||
|
||||
/** Leaflet measures zoom against a 256px world tile; MapLibre/Mapbox against 512px. */
|
||||
export const TILE_SIZE_RASTER = 256
|
||||
export const TILE_SIZE_GL = 512
|
||||
|
||||
/**
|
||||
* Match the maxZoom the fitBounds in each renderer already clamps to (MapView 16,
|
||||
* MapViewGL 15), so the opening camera and any later fit agree instead of fighting.
|
||||
*/
|
||||
export const MAX_ZOOM_RASTER = 16
|
||||
export const MAX_ZOOM_GL = 15
|
||||
|
||||
/**
|
||||
* One place (or several at the same spot) has no extent to fit, so zoom is a choice rather
|
||||
* than a calculation: city level, showing the surroundings rather than just the pin.
|
||||
* Expressed in the raster scheme; the GL scheme is one level lower for the same scale.
|
||||
*/
|
||||
export const SINGLE_PLACE_ZOOM_RASTER = 12
|
||||
|
||||
export interface MapViewport {
|
||||
/** [lat, lng] — the order both renderers take as a prop (MapViewGL swaps it internally). */
|
||||
center: [number, number]
|
||||
zoom: number
|
||||
}
|
||||
|
||||
/** Anything with coordinates: a Place, a CollectionPlace, a bare {lat, lng}. */
|
||||
export interface GeoPointish {
|
||||
lat?: number | null
|
||||
lng?: number | null
|
||||
}
|
||||
|
||||
export interface ViewportPadding {
|
||||
top: number
|
||||
right: number
|
||||
bottom: number
|
||||
left: number
|
||||
}
|
||||
|
||||
export interface ViewportOptions {
|
||||
/** 256 for Leaflet, 512 for MapLibre/Mapbox. Drives both the zoom scale and maxZoom. */
|
||||
tileSize?: number
|
||||
/** Map container size in CSS px. Defaults to the window, then to 1024x768 (SSR/jsdom). */
|
||||
width?: number
|
||||
height?: number
|
||||
/** Chrome overlaying the map (side panels). Shifts the center so places stay visible. */
|
||||
padding?: Partial<ViewportPadding>
|
||||
maxZoom?: number
|
||||
singlePlaceZoom?: number
|
||||
/**
|
||||
* Does the renderer draw markers on the nearest copy of a repeating world? MapLibre/Mapbox
|
||||
* do; Leaflet does not. Only a wrapping renderer can be framed across the antimeridian.
|
||||
* Defaults to true for the GL tile scheme, false for the raster one.
|
||||
*/
|
||||
wrapsWorld?: boolean
|
||||
}
|
||||
|
||||
const NO_PADDING: ViewportPadding = { top: 0, right: 0, bottom: 0, left: 0 }
|
||||
|
||||
const clampLat = (lat: number): number =>
|
||||
Math.max(-MERCATOR_MAX_LAT, Math.min(MERCATOR_MAX_LAT, lat))
|
||||
|
||||
/** Wrap into [-180, 180) so a center computed across the antimeridian stays a real longitude. */
|
||||
const normalizeLng = (lng: number): number => ((((lng + 180) % 360) + 360) % 360) - 180
|
||||
|
||||
/**
|
||||
* Keep only points we can actually project. Note the Number.isFinite test: `lat && lng`
|
||||
* would silently drop Null Island, the equator and the prime meridian — 0 is a coordinate.
|
||||
*/
|
||||
function usablePoints(points: readonly GeoPointish[]): Array<[number, number]> {
|
||||
const out: Array<[number, number]> = []
|
||||
for (const point of points || []) {
|
||||
const lat = point?.lat
|
||||
const lng = point?.lng
|
||||
if (typeof lat !== 'number' || typeof lng !== 'number') continue
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue
|
||||
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) continue
|
||||
out.push([clampLat(lat), lng])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Mercator y as a fraction of the world, in the [-π, π] convention the zoom math expects. */
|
||||
function latRad(lat: number): number {
|
||||
const sin = Math.sin((clampLat(lat) * Math.PI) / 180)
|
||||
const rad = Math.log((1 + sin) / (1 - sin)) / 2
|
||||
return Math.max(-Math.PI, Math.min(Math.PI, rad)) / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* The narrowest arc of longitude containing every point, which may cross the antimeridian:
|
||||
* a trip spanning Fiji (178) and Samoa (-172) is 10° wide, not 350°.
|
||||
*
|
||||
* Found by locating the widest *gap* between neighbouring longitudes — the places occupy
|
||||
* everything the gap doesn't. Comparing plain min/max against its complement instead would
|
||||
* be right for two points but wrong for three or more, where the complement of the min-max
|
||||
* span can exclude a point sitting inside it.
|
||||
*
|
||||
* `east` may exceed 180 when the arc wraps; callers project it and let unproject wrap back.
|
||||
*
|
||||
* Only sound when the renderer wraps the world. MapLibre/Mapbox draw a marker on whichever
|
||||
* copy of the world is nearest the camera; Leaflet does not, so a centre reached "the short
|
||||
* way" across the antimeridian leaves markers on the far side of the single world it drew,
|
||||
* off-screen entirely. For those, take the plain min..max arc — the long way round — which is
|
||||
* also what L.latLngBounds would do.
|
||||
*/
|
||||
function lngExtent(lngs: number[], wrapsWorld: boolean): { west: number; east: number; span: number } {
|
||||
const sorted = [...lngs].sort((a, b) => a - b)
|
||||
const last = sorted.length - 1
|
||||
|
||||
if (!wrapsWorld) {
|
||||
return { west: sorted[0], east: sorted[last], span: sorted[last] - sorted[0] }
|
||||
}
|
||||
|
||||
// The gap that wraps past the antimeridian, from the easternmost point back to the westernmost.
|
||||
let widestGap = sorted[0] + 360 - sorted[last]
|
||||
let west = sorted[0]
|
||||
let east = sorted[last]
|
||||
|
||||
for (let i = 0; i < last; i++) {
|
||||
const gap = sorted[i + 1] - sorted[i]
|
||||
if (gap > widestGap) {
|
||||
widestGap = gap
|
||||
// The arc resumes on the far side of the gap and runs east, across the antimeridian.
|
||||
west = sorted[i + 1]
|
||||
east = sorted[i] + 360
|
||||
}
|
||||
}
|
||||
|
||||
return { west, east, span: east - west }
|
||||
}
|
||||
|
||||
/** Zoom at which a span covering `fraction` of the world fills `px` pixels. */
|
||||
function zoomForFraction(px: number, tileSize: number, fraction: number, maxZoom: number): number {
|
||||
// A zero fraction (identical coordinates) would divide by zero and yield Infinity.
|
||||
if (!(fraction > 0)) return maxZoom
|
||||
const zoom = Math.log2(px / tileSize / fraction)
|
||||
return Number.isFinite(zoom) ? zoom : maxZoom
|
||||
}
|
||||
|
||||
function project(lat: number, lng: number, zoom: number, tileSize: number): { x: number; y: number } {
|
||||
const scale = tileSize * Math.pow(2, zoom)
|
||||
const sin = Math.sin((clampLat(lat) * Math.PI) / 180)
|
||||
return {
|
||||
x: scale * (lng / 360 + 0.5),
|
||||
y: scale * (0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)),
|
||||
}
|
||||
}
|
||||
|
||||
function unproject(x: number, y: number, zoom: number, tileSize: number): [number, number] {
|
||||
const scale = tileSize * Math.pow(2, zoom)
|
||||
const lng = (x / scale - 0.5) * 360
|
||||
const n = Math.PI * (1 - 2 * (y / scale))
|
||||
const lat = (180 / Math.PI) * Math.atan(Math.sinh(n))
|
||||
return [lat, normalizeLng(lng)]
|
||||
}
|
||||
|
||||
/**
|
||||
* The map renders its center at the middle of the container, but padding (side panels)
|
||||
* means the *visible* middle sits elsewhere. Pull the center back by half the padding
|
||||
* delta so the places land in the part of the map the user can actually see — the same
|
||||
* thing fitBounds' padding option does.
|
||||
*/
|
||||
function offsetForPadding(
|
||||
center: [number, number],
|
||||
zoom: number,
|
||||
tileSize: number,
|
||||
padding: ViewportPadding,
|
||||
): [number, number] {
|
||||
const { top, right, bottom, left } = padding
|
||||
if (!top && !right && !bottom && !left) return center
|
||||
const { x, y } = project(center[0], center[1], zoom, tileSize)
|
||||
return unproject(x - (left - right) / 2, y - (top - bottom) / 2, zoom, tileSize)
|
||||
}
|
||||
|
||||
function defaultWidth(): number {
|
||||
return typeof window !== 'undefined' && window.innerWidth > 0 ? window.innerWidth : 1024
|
||||
}
|
||||
|
||||
function defaultHeight(): number {
|
||||
return typeof window !== 'undefined' && window.innerHeight > 0 ? window.innerHeight : 768
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera that frames `points`, or null when none of them have coordinates.
|
||||
*/
|
||||
export function computeMapViewport(
|
||||
points: readonly GeoPointish[],
|
||||
options: ViewportOptions = {},
|
||||
): MapViewport | null {
|
||||
const pts = usablePoints(points)
|
||||
if (pts.length === 0) return null
|
||||
|
||||
const tileSize = options.tileSize ?? TILE_SIZE_RASTER
|
||||
const isGl = tileSize === TILE_SIZE_GL
|
||||
const maxZoom = options.maxZoom ?? (isGl ? MAX_ZOOM_GL : MAX_ZOOM_RASTER)
|
||||
const singlePlaceZoom = options.singlePlaceZoom
|
||||
?? (isGl ? SINGLE_PLACE_ZOOM_RASTER - 1 : SINGLE_PLACE_ZOOM_RASTER)
|
||||
const wrapsWorld = options.wrapsWorld ?? isGl
|
||||
|
||||
const padding: ViewportPadding = { ...NO_PADDING, ...options.padding }
|
||||
const width = Math.max(1, (options.width ?? defaultWidth()) - padding.left - padding.right)
|
||||
const height = Math.max(1, (options.height ?? defaultHeight()) - padding.top - padding.bottom)
|
||||
|
||||
const lats = pts.map(p => p[0])
|
||||
const south = Math.min(...lats)
|
||||
const north = Math.max(...lats)
|
||||
const { west, east, span } = lngExtent(pts.map(p => p[1]), wrapsWorld)
|
||||
|
||||
const latFraction = (latRad(north) - latRad(south)) / Math.PI
|
||||
const lngFraction = span / 360
|
||||
|
||||
// No extent in either axis: one place, or several stacked on the same spot.
|
||||
const zoom = latFraction <= 0 && lngFraction <= 0
|
||||
? Math.min(singlePlaceZoom, maxZoom)
|
||||
: Math.min(
|
||||
zoomForFraction(height, tileSize, latFraction, maxZoom),
|
||||
zoomForFraction(width, tileSize, lngFraction, maxZoom),
|
||||
maxZoom,
|
||||
)
|
||||
|
||||
// Floor rather than round: Leaflet snaps zoom to integers, and rounding up would crop
|
||||
// the very places we are framing.
|
||||
const safeZoom = Number.isFinite(zoom) ? Math.max(0, Math.floor(zoom * 100) / 100) : maxZoom
|
||||
|
||||
// Take the midpoint in *projected* space, not the average of the latitudes: Mercator
|
||||
// stretches towards the poles, so a geographic mid-latitude sits off-centre on screen and
|
||||
// pushes the northernmost place out of frame. Projecting also carries the antimeridian
|
||||
// handling for free — `east` may exceed 180, and unproject wraps it back.
|
||||
const northWest = project(north, west, safeZoom, tileSize)
|
||||
const southEast = project(south, east, safeZoom, tileSize)
|
||||
const center = unproject(
|
||||
(northWest.x + southEast.x) / 2,
|
||||
(northWest.y + southEast.y) / 2,
|
||||
safeZoom,
|
||||
tileSize,
|
||||
)
|
||||
|
||||
return { center: offsetForPadding(center, safeZoom, tileSize, padding), zoom: safeZoom }
|
||||
}
|
||||
Reference in New Issue
Block a user