- Default "Zadání HG3" mode with exactly the 16 categories of the assignment (9 built-up, 7 undeveloped) and its legend colours; replaces the old simple mode - Whole map coloured: RÚIAN cadastral parcels are fetched and classified from land type / land use; built-up parcels take the category of their building - Field corrections per building or parcel (info panel), saved locally and in a project file (save/open JSON) to move between devices - A4 frame at 1 : 3 780 (300 dpi, landscape/portrait) shown on the map; data loading covers the frame - Built-up territory meter against the 66 % rule (built-up areas + gardens + maintained greenery; strict legend share shown too) and area statistics per category with CSV export - Submission print/PDF: 1 map (title, author, scale, source), 2 legend (only categories present), 3-4 commentary - Commentary editor with the assignment's questions and a 3 600-character counter - Field worksheet: blank A4 base map with house numbers and an empty legend to colour with crayons - Buildings CSV gains HG3 category, correction flag and parcels Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
254 lines
7.8 KiB
TypeScript
254 lines
7.8 KiB
TypeScript
import { batch } from '@preact/signals'
|
|
import { fetchArea } from './fetch'
|
|
import { bboxOf } from './building'
|
|
import { D2R, ll2m, m2ll } from './geo'
|
|
import { t } from './i18n'
|
|
import { writeHash } from './persist'
|
|
import { frameCovered, frameRadius } from './page'
|
|
import { renderPrintMap } from './print'
|
|
import { fitView } from './render'
|
|
import {
|
|
base,
|
|
busy,
|
|
hidden,
|
|
lastLoc,
|
|
locating,
|
|
locText,
|
|
progress,
|
|
radius,
|
|
rawBuildings,
|
|
rawParcels,
|
|
answered,
|
|
commentary,
|
|
mapAuthor,
|
|
mapTitle,
|
|
mixMin,
|
|
mode,
|
|
orientation,
|
|
overrides,
|
|
printJob,
|
|
showFrame,
|
|
S,
|
|
sel,
|
|
status,
|
|
toast,
|
|
type Status,
|
|
} from './state'
|
|
import type { AreaData, LatLon } from './types'
|
|
import { errMsg } from './util'
|
|
|
|
export function setStatus(fn: () => string, cls?: Status['cls'], details?: string[]) {
|
|
status.value = { fn, cls, details }
|
|
}
|
|
|
|
let toastTimer: ReturnType<typeof setTimeout> | undefined
|
|
export function showToast(fn: () => string) {
|
|
clearTimeout(toastTimer)
|
|
toast.value = { fn, id: Date.now() }
|
|
toastTimer = setTimeout(() => (toast.value = null), 2400)
|
|
}
|
|
|
|
/**
|
|
* Show loaded data. r: the load radius (to know which area is covered);
|
|
* keepView: centre the view on (lon, lat) and keep the zoom, instead of fitting to the data.
|
|
*/
|
|
export function applyData(d: AreaData, lon: number, lat: number, r?: number, keepView = false) {
|
|
S.center = [lon, lat]
|
|
S.K = Math.cos(lat * D2R)
|
|
S.loaded = true
|
|
if (r) {
|
|
const [cx, cy] = ll2m(lon, lat),
|
|
h = (1.1 * r * 0.995) / S.K
|
|
S.loadedBB = [cx - h, cy - h, cx + h, cy + h]
|
|
} else S.loadedBB = bboxOf(d.buildings.flatMap((b) => b.rings))
|
|
// fitView inside the batch so the map redraw triggered by the new data uses the new view
|
|
batch(() => {
|
|
rawBuildings.value = d.buildings
|
|
rawParcels.value = d.parcels
|
|
base.value = d.base
|
|
sel.value = null
|
|
hidden.value = new Set()
|
|
if (!keepView) fitView()
|
|
else {
|
|
const [cx, cy] = ll2m(lon, lat)
|
|
S.view = { ...S.view, cx, cy }
|
|
}
|
|
})
|
|
}
|
|
|
|
/** Radius to load: in the HG3 mode with the frame on, at least enough for the A4 frame. */
|
|
const loadRadius = () =>
|
|
mode.value === 'hg3' && showFrame.value ? Math.max(radius.value, frameRadius()) : radius.value
|
|
|
|
let loadSeq = 0
|
|
/** Load an area from ČÚZK. A newer call supersedes one still in flight. */
|
|
export async function liveLoad(
|
|
p: LatLon,
|
|
quietFallback: boolean,
|
|
keepView = false,
|
|
): Promise<boolean> {
|
|
const my = ++loadSeq
|
|
const current = () => my === loadSeq
|
|
batch(() => {
|
|
busy.value = true
|
|
progress.value = { done: 0, total: 0 }
|
|
setStatus(() => t('st_loading'))
|
|
})
|
|
try {
|
|
const r = loadRadius()
|
|
const d = await fetchArea(p.lon, p.lat, r, (done, total) => {
|
|
if (current()) progress.value = { done, total }
|
|
})
|
|
if (!current()) return false
|
|
if (!d.buildings.length) {
|
|
setStatus(() => t('st_none'), 'err')
|
|
return false
|
|
}
|
|
applyData(d, p.lon, p.lat, r, keepView)
|
|
writeHash(p, r)
|
|
lastLoc.value = { lat: p.lat, lon: p.lon }
|
|
const loc = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`,
|
|
n = d.buildings.length,
|
|
fails = d.fails
|
|
if (fails.length)
|
|
setStatus(() => t('st_loaded', loc, n) + ' ' + t('st_baseFail', fails.length), 'warn', fails)
|
|
else setStatus(() => t('st_loaded', loc, n), 'ok')
|
|
return true
|
|
} catch (e) {
|
|
if (!current()) return false
|
|
const msg = errMsg(e)
|
|
setStatus(() => (quietFallback ? t('st_fallback', msg) : t('st_err', msg)), 'err')
|
|
return false
|
|
} finally {
|
|
if (current())
|
|
batch(() => {
|
|
busy.value = false
|
|
progress.value = null
|
|
})
|
|
}
|
|
}
|
|
|
|
const inCzechia = (p: LatLon) => p.lat >= 48 && p.lat <= 52 && p.lon >= 12 && p.lon <= 19
|
|
|
|
/** Load the area around the device's position. */
|
|
export function locate() {
|
|
if (!('geolocation' in navigator)) {
|
|
setStatus(() => t('geo_unavailable'), 'err')
|
|
return
|
|
}
|
|
locating.value = true
|
|
setStatus(() => t('locating'))
|
|
navigator.geolocation.getCurrentPosition(
|
|
(pos) => {
|
|
locating.value = false
|
|
const p = { lat: pos.coords.latitude, lon: pos.coords.longitude }
|
|
if (!inCzechia(p)) {
|
|
setStatus(() => t('geo_outside'), 'err')
|
|
return
|
|
}
|
|
locText.value = `${p.lat.toFixed(6)}, ${p.lon.toFixed(6)}`
|
|
liveLoad(p, false)
|
|
},
|
|
(err) => {
|
|
locating.value = false
|
|
setStatus(
|
|
() => t(err.code === err.PERMISSION_DENIED ? 'geo_denied' : 'geo_unavailable'),
|
|
'err',
|
|
)
|
|
},
|
|
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 },
|
|
)
|
|
}
|
|
|
|
export async function copyLink() {
|
|
try {
|
|
await navigator.clipboard.writeText(location.href)
|
|
showToast(() => t('linkCopied'))
|
|
} catch {
|
|
// clipboard blocked (e.g. insecure context): let the user copy it manually
|
|
window.prompt(t('copyLink'), location.href)
|
|
}
|
|
}
|
|
|
|
/** Load data for the A4 frame around the current view centre, keeping the view. */
|
|
export function loadFrame() {
|
|
const [lon, lat] = m2ll(S.view.cx, S.view.cy)
|
|
locText.value = `${lat.toFixed(6)}, ${lon.toFixed(6)}`
|
|
return liveLoad({ lat, lon }, false, true)
|
|
}
|
|
|
|
/* ================= printing ================= */
|
|
/** Render the A4 map and open the print dialog for the submission PDF or the field worksheet. */
|
|
export async function preparePrint(kind: 'submission' | 'worksheet') {
|
|
if (!frameCovered()) {
|
|
setStatus(() => t('needData'), 'err')
|
|
return
|
|
}
|
|
showToast(() => t('preparing'))
|
|
await new Promise((r) => setTimeout(r, 30)) // let the toast paint before the heavy render
|
|
const mapUrl = await renderPrintMap(kind === 'worksheet')
|
|
printJob.value = { kind, mapUrl }
|
|
// wait for PrintView to render and the map image to decode
|
|
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))
|
|
await document
|
|
.querySelector<HTMLImageElement>('.print-root img')
|
|
?.decode()
|
|
.catch(() => {})
|
|
window.print()
|
|
}
|
|
|
|
/* ================= project file ================= */
|
|
const PROJECT_APP = 'building-use-map/hg3'
|
|
|
|
export function projectData() {
|
|
return {
|
|
app: PROJECT_APP,
|
|
version: 1,
|
|
savedAt: new Date().toISOString(),
|
|
location: lastLoc.value,
|
|
radius: radius.value,
|
|
view: lastLoc.value ? m2ll(S.view.cx, S.view.cy) : null,
|
|
orientation: orientation.value,
|
|
title: mapTitle.value,
|
|
author: mapAuthor.value,
|
|
mixMin: mixMin.value,
|
|
overrides: overrides.value,
|
|
commentary: commentary.value,
|
|
answered: answered.value,
|
|
}
|
|
}
|
|
|
|
/** Restore a project saved with "Save project" and load its area. */
|
|
export async function openProject(file: File) {
|
|
let d: Partial<ReturnType<typeof projectData>>
|
|
try {
|
|
d = JSON.parse(await file.text())
|
|
} catch {
|
|
d = {}
|
|
}
|
|
if (d.app !== PROJECT_APP) {
|
|
setStatus(() => t('projectBad'), 'err')
|
|
return
|
|
}
|
|
batch(() => {
|
|
if (d.overrides && typeof d.overrides === 'object') overrides.value = { ...d.overrides }
|
|
if (typeof d.commentary === 'string') commentary.value = d.commentary
|
|
if (Array.isArray(d.answered)) answered.value = d.answered.filter((n) => typeof n === 'number')
|
|
if (typeof d.title === 'string') mapTitle.value = d.title
|
|
if (typeof d.author === 'string') mapAuthor.value = d.author
|
|
if (d.orientation === 'landscape' || d.orientation === 'portrait')
|
|
orientation.value = d.orientation
|
|
if (d.mixMin === 0 || d.mixMin === 1 || d.mixMin === 2) mixMin.value = d.mixMin
|
|
if (typeof d.radius === 'number' && d.radius >= 100 && d.radius <= 700) radius.value = d.radius
|
|
mode.value = 'hg3'
|
|
})
|
|
showToast(() => t('projectLoaded'))
|
|
// load the saved frame position (view centre), else the saved location
|
|
const v =
|
|
Array.isArray(d.view) && d.view.length === 2 ? { lon: +d.view[0], lat: +d.view[1] } : null
|
|
const p = v ?? d.location
|
|
if (p && typeof p.lat === 'number' && typeof p.lon === 'number') {
|
|
locText.value = `${p.lat.toFixed(6)}, ${p.lon.toFixed(6)}`
|
|
await liveLoad(p, false, !!v)
|
|
}
|
|
}
|