203 lines
10 KiB
TypeScript
203 lines
10 KiB
TypeScript
// 단풍 지도 데이터·계산 (웹 frontend/src/b/foliage.ts 와 앱 mobile/src/components/foliage 가 같이 쓴다). 화면 그리기는 각자
|
|
import data from '../../frontend/seo/foliage_2026.json'
|
|
import { kst } from '.'
|
|
|
|
export type Kind = 'maple' | 'ginkgo'
|
|
export type Stage = 'before' | 'first' | 'peak' | 'gone'
|
|
type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
|
|
/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */
|
|
export type Spot = Omit<Raw, 'basis' | 'lat' | 'lon'> & { stage: Stage; d: number; x: number; y: number; own: boolean }
|
|
|
|
// 지도 그림(frontend/public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
|
|
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
|
|
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
|
|
const FIRST_DAYS = 14
|
|
const PEAK_DAYS = 3
|
|
const PEAK_AFTER = 5
|
|
|
|
export const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
|
|
export const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
|
|
/** 절정 잎 아이콘 반지름(점끼리 밀어 낼 때) */
|
|
export const ICON_R = 10
|
|
|
|
const DAY = 86_400_000
|
|
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
|
|
|
|
function stage(peak: string, today: string): Stage {
|
|
const d = days(today, peak)
|
|
if (d < -PEAK_AFTER) return 'gone'
|
|
if (d <= PEAK_DAYS) return 'peak'
|
|
return d <= FIRST_DAYS ? 'first' : 'before'
|
|
}
|
|
|
|
/** 위경도 → 지도 그림 안 위치(0~1). 해돋이 지도(shared/lib/sunrise.ts)도 같은 그림을 쓴다 */
|
|
export const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
|
|
// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김
|
|
export const LAND_CX = toXY(36, 127.65).x
|
|
|
|
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
|
|
export const PROVINCES = (
|
|
[
|
|
['서울', 37.56, 126.98],
|
|
['경기', 37.95, 127.05],
|
|
['강원', 37.65, 128.35],
|
|
['충북', 36.8, 127.75],
|
|
['충남', 36.45, 126.85],
|
|
['전북', 35.72, 127.1],
|
|
['전남', 34.85, 126.9],
|
|
['경북', 36.3, 128.75],
|
|
['경남', 35.3, 128.2],
|
|
['제주', 33.38, 126.55],
|
|
] as const
|
|
).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) }))
|
|
|
|
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
|
|
const province = (m: Spot) => m.region.split(' ')[0].split('·')
|
|
|
|
/** 오늘(한국 시각) 날짜 'YYYY-MM-DD' */
|
|
export function foliageToday(now: Date = new Date()) {
|
|
const t = kst(now)
|
|
return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
|
|
}
|
|
|
|
/** today 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */
|
|
export function foliageOn(today: string) {
|
|
const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({
|
|
...m,
|
|
stage: stage(m.peak, today),
|
|
d: days(today, m.peak),
|
|
...toXY(lat, lon),
|
|
own: basis.startsWith('산림청'),
|
|
}))
|
|
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
|
|
const peaks = spots.map((m) => m.peak).sort()
|
|
const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER
|
|
return { today, spots, inSeason }
|
|
}
|
|
|
|
/** 오늘이 단풍철인지 (오늘 아이콘 줄의 단풍 지도 칸·피드 단풍 카드를 보일지) */
|
|
export const foliageInSeason = (today: string = foliageToday()) => foliageOn(today).inSeason
|
|
|
|
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
|
|
export function headline(spots: Spot[]) {
|
|
const peak = spots.filter((m) => m.stage === 'peak')
|
|
if (peak.length) {
|
|
const count = new Map<string, number>()
|
|
for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1)
|
|
return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
|
|
}
|
|
if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요'
|
|
const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a))
|
|
return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤`
|
|
}
|
|
|
|
/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */
|
|
export const rankNow = (spots: Spot[]) =>
|
|
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
|
|
|
|
export type Pt<M extends { name: string } = Spot> = { m: M; x: number; y: number; r: number }
|
|
export type Box = { l: number; t: number; r: number; b: number }
|
|
export type LabelSize = Record<string, { w: number; h: number }>
|
|
const LABEL_GAP = 4
|
|
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
|
|
|
|
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
|
|
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: { x: number; y: number; r: number }[], labels: Box[] = [], R = 90) {
|
|
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
|
|
const placed: Box[] = []
|
|
const free = (x: number, y: number) =>
|
|
pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b))
|
|
return provs.map((v) => {
|
|
const at = pick(v)
|
|
placed.push(provinceBox(at.x, at.y))
|
|
return at
|
|
})
|
|
function pick(v: { name: string; x: number; y: number }) {
|
|
if (free(v.x, v.y)) return v
|
|
for (let d = 5; d <= R; d += 5)
|
|
for (let a = 0; a < 24; a++) {
|
|
const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d
|
|
const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d
|
|
if (free(x, y)) return { ...v, x, y }
|
|
}
|
|
return v
|
|
}
|
|
}
|
|
export function provinceBox(x: number, y: number): Box {
|
|
return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 }
|
|
}
|
|
|
|
/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */
|
|
export const labelBoxes = (at: Record<string, { left: number; top: number }>, size: LabelSize) =>
|
|
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
|
|
|
|
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
|
|
export function spread<P extends { x: number; y: number; r: number }>(pts: P[], gap = 1.5) {
|
|
for (let it = 0; it < 60; it++) {
|
|
let moved = false
|
|
for (let i = 0; i < pts.length; i++)
|
|
for (let j = i + 1; j < pts.length; j++) {
|
|
const a = pts[i]
|
|
const b = pts[j]
|
|
let dx = b.x - a.x
|
|
let dy = b.y - a.y
|
|
let d = Math.hypot(dx, dy)
|
|
const need = a.r + b.r + gap
|
|
if (d >= need) continue
|
|
if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1]
|
|
const push = (need - d) / 2
|
|
a.x -= (dx / d) * push
|
|
a.y -= (dy / d) * push
|
|
b.x += (dx / d) * push
|
|
b.y += (dy / d) * push
|
|
moved = true
|
|
}
|
|
if (!moved) break
|
|
}
|
|
return pts
|
|
}
|
|
|
|
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
|
|
export function placeLabels<M extends { name: string }>(order: Pt<M>[], all: Pt<M>[], size: LabelSize, area: Box, blocked: Box[] = [], vertical: (p: Pt<M>) => boolean = () => false) {
|
|
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
|
|
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
|
|
const out: Record<string, { left: number; top: number }> = {}
|
|
for (const p of order) {
|
|
const s = size[p.m.name]
|
|
if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue
|
|
// 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다
|
|
const tries = [
|
|
[p.r + 2, -s.h / 2],
|
|
[-s.w - p.r - 2, -s.h / 2],
|
|
...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []),
|
|
]
|
|
for (const [dx, dy] of tries) {
|
|
const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h }
|
|
if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue
|
|
// 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게
|
|
const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP }
|
|
if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue
|
|
// 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다
|
|
const cx = (r.l + r.r) / 2
|
|
const cy = (r.t + r.b) / 2
|
|
const mine = Math.hypot(cx - p.x, cy - p.y)
|
|
if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue
|
|
taken.push({ name: '', box: r })
|
|
out[p.m.name] = { left: r.l, top: r.t }
|
|
break
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
/** 누른 자리에서 가장 가까운 명소 (잎이 작아 손가락으로 겨냥하기 어려워서). 반경 r 안에 없으면 null */
|
|
export function nearest(pts: Pt<{ name: string }>[], x: number, y: number, r = 24) {
|
|
let best: string | null = null
|
|
let bestD = r
|
|
for (const p of pts) {
|
|
const d = Math.hypot(p.x - x, p.y - y)
|
|
if (d < bestD) [best, bestD] = [p.m.name, d]
|
|
}
|
|
return best
|
|
}
|