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 geometry?: { rings?: Ring[]; paths?: Ring[] } } interface QueryResult { features?: Feature[] exceededTransferLimit?: boolean error?: { message?: string } } type Settled = { ok: true; v: T } | { ok: false; e: unknown } async function query( url: string, fields: string, env: string, offset?: number, ): Promise { const p: Record = { 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 | undefined const timeout = new Promise((_, 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 { 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 | undefined): Record => 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(tasks: (() => Promise)[], n: number): Promise[]> { const out = Array.from({ length: tasks.length }) as Settled[] 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 { 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 { 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 } }