- 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>
186 lines
6 KiB
TypeScript
186 lines
6 KiB
TypeScript
import { ZAB_LAYERS, type BaseKey } from './basemap'
|
|
import { mkBuilding, mkParcel } from './building'
|
|
import { D2R } from './geo'
|
|
import type { AreaData, BaseData, Ring } from './types'
|
|
import { errMsg, sleep } from './util'
|
|
|
|
/* ================= fetching from ČÚZK ================= */
|
|
const RUIAN = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/3/query' // stavební objekty
|
|
const PARCELS = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/5/query' // parcely
|
|
const ZAB = 'https://ags.cuzk.cz/arcgis/rest/services/ZABAGED_POLOHOPIS/MapServer/'
|
|
|
|
interface Feature {
|
|
attributes?: Record<string, unknown>
|
|
geometry?: { rings?: Ring[]; paths?: Ring[] }
|
|
}
|
|
interface QueryResult {
|
|
features?: Feature[]
|
|
exceededTransferLimit?: boolean
|
|
error?: { message?: string }
|
|
}
|
|
type Settled<T> = { ok: true; v: T } | { ok: false; e: unknown }
|
|
|
|
async function query(
|
|
url: string,
|
|
fields: string,
|
|
env: string,
|
|
offset?: number,
|
|
): Promise<QueryResult> {
|
|
const p: Record<string, string> = {
|
|
geometry: env,
|
|
geometryType: 'esriGeometryEnvelope',
|
|
inSR: '4326',
|
|
outSR: '3857',
|
|
spatialRel: 'esriSpatialRelIntersects',
|
|
where: '1=1',
|
|
outFields: fields,
|
|
returnGeometry: 'true',
|
|
geometryPrecision: '1',
|
|
maxAllowableOffset: '0.3',
|
|
f: 'json',
|
|
}
|
|
if (offset) {
|
|
p.resultOffset = String(offset)
|
|
p.resultRecordCount = '1000'
|
|
}
|
|
// No AbortSignal / fetch options: some embedded viewers proxy fetch through postMessage and cannot clone them.
|
|
const url2 = url + '?' + new URLSearchParams(p)
|
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
const timeout = new Promise<never>((_, rej) => {
|
|
timer = setTimeout(() => rej(new Error('timed out after 45 s')), 45000)
|
|
})
|
|
try {
|
|
const res = await Promise.race([fetch(url2), timeout])
|
|
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
const j = (await Promise.race([res.json(), timeout])) as QueryResult
|
|
if (j.error) throw new Error(j.error.message || 'service error')
|
|
return j
|
|
} finally {
|
|
clearTimeout(timer)
|
|
}
|
|
}
|
|
async function queryAll(url: string, fields: string, env: string): Promise<Feature[]> {
|
|
let out: Feature[] = [],
|
|
off = 0
|
|
for (let page = 0; page < 12; page++) {
|
|
let j: QueryResult
|
|
try {
|
|
j = await query(url, fields, env, off)
|
|
} catch (e) {
|
|
if (off > 0) break
|
|
throw e
|
|
}
|
|
const f = j.features || []
|
|
out = out.concat(f)
|
|
if (!j.exceededTransferLimit || !f.length) break
|
|
off += f.length
|
|
}
|
|
return out
|
|
}
|
|
const lowerKeys = (o: Record<string, unknown> | undefined): Record<string, unknown> =>
|
|
Object.fromEntries(Object.entries(o || {}).map(([k, v]) => [k.toLowerCase(), v]))
|
|
const ringsOf = (f: Feature): Ring[] => (f.geometry && (f.geometry.rings || f.geometry.paths)) || []
|
|
|
|
/** Run async tasks, at most n at a time. */
|
|
async function pool<T>(tasks: (() => Promise<T>)[], n: number): Promise<Settled<T>[]> {
|
|
const out = Array.from({ length: tasks.length }) as Settled<T>[]
|
|
let i = 0
|
|
await Promise.all(
|
|
Array.from({ length: Math.min(n, tasks.length) }, async () => {
|
|
while (i < tasks.length) {
|
|
const k = i++
|
|
try {
|
|
out[k] = { ok: true, v: await tasks[k]() }
|
|
} catch (e) {
|
|
out[k] = { ok: false, e }
|
|
}
|
|
}
|
|
}),
|
|
)
|
|
return out
|
|
}
|
|
/** Retry, then try an explicit field instead of an empty field list. */
|
|
async function baseLayer(id: number, env: string): Promise<Feature[]> {
|
|
let last: unknown
|
|
for (const fields of ['', 'objectid', '']) {
|
|
try {
|
|
return await queryAll(ZAB + id + '/query', fields, env)
|
|
} catch (e) {
|
|
last = e
|
|
await sleep(500)
|
|
}
|
|
}
|
|
throw last
|
|
}
|
|
|
|
export async function fetchArea(
|
|
lon: number,
|
|
lat: number,
|
|
radius: number,
|
|
onProgress?: (done: number, total: number) => void,
|
|
): Promise<AreaData> {
|
|
const dLat = (radius * 1.1) / 111320,
|
|
dLon = (radius * 1.1) / (111320 * Math.cos(lat * D2R))
|
|
const env = [lon - dLon, lat - dLat, lon + dLon, lat + dLat].map((v) => v.toFixed(6)).join(',')
|
|
const bFields =
|
|
'kod,identifikacniparcela,cisladomovni,zpusobvyuzitikod,pocetbytu,pocetpodlazi,zastavenaplocha,dokonceni'
|
|
const pFields = 'id,cisloparcely,druhpozemkukod,zpusobyvyuzitipozemku,vymeraparcely'
|
|
const keys = Object.keys(ZAB_LAYERS) as BaseKey[]
|
|
const total = keys.length + 2
|
|
let done = 0
|
|
const tick = () => onProgress?.(++done, total)
|
|
// Buildings, parcels and basemap layers load in parallel (4 requests at a time overall).
|
|
// If the buildings query fails there is nothing to show, so fail right away instead of
|
|
// waiting for the other requests.
|
|
const buildingsP = queryAll(RUIAN, bFields, env).finally(tick)
|
|
const parcelsP = pool([() => queryAll(PARCELS, pFields, env).finally(tick)], 1)
|
|
const basesP = pool(
|
|
keys.map((k) => () => baseLayer(ZAB_LAYERS[k], env).finally(tick)),
|
|
2,
|
|
)
|
|
const features = await buildingsP
|
|
const [pRes] = await parcelsP
|
|
const res = await basesP
|
|
const base: BaseData = {},
|
|
fails: string[] = []
|
|
if (!pRes.ok) fails.push('parcely: ' + errMsg(pRes.e))
|
|
keys.forEach((k, i) => {
|
|
const r = res[i]
|
|
if (r.ok) base[k] = r.v.flatMap(ringsOf)
|
|
else {
|
|
base[k] = []
|
|
fails.push(k + ': ' + errMsg(r.e))
|
|
}
|
|
})
|
|
type N = number | null
|
|
const buildings = features
|
|
.map((f) => {
|
|
const a = lowerKeys(f.attributes)
|
|
return mkBuilding(
|
|
a.kod as N,
|
|
a.identifikacniparcela as N,
|
|
a.cisladomovni as string | null,
|
|
a.zpusobvyuzitikod as N,
|
|
a.pocetbytu as N,
|
|
a.pocetpodlazi as N,
|
|
a.zastavenaplocha as N,
|
|
a.dokonceni as N,
|
|
ringsOf(f),
|
|
)
|
|
})
|
|
.filter((b) => b.rings.length)
|
|
const parcels = (pRes.ok ? pRes.v : [])
|
|
.map((f) => {
|
|
const a = lowerKeys(f.attributes)
|
|
return mkParcel(
|
|
a.id as N,
|
|
a.cisloparcely as string | null,
|
|
a.druhpozemkukod as N,
|
|
a.zpusobyvyuzitipozemku as N,
|
|
a.vymeraparcely as N,
|
|
ringsOf(f),
|
|
)
|
|
})
|
|
.filter((p) => p.rings.length)
|
|
return { buildings, parcels, base, fails }
|
|
}
|