|
| 1 | +//! Open-data portals: OpenStreetMap data for an area (through Overpass) and administrative |
| 2 | +//! boundaries for a country (from geoBoundaries). |
| 3 | +
|
| 4 | +use serde_json::{Value, json}; |
| 5 | + |
| 6 | +use super::{b, ps}; |
| 7 | +use crate::render::rustgis_tiles::{boundaries, overpass}; |
| 8 | +use crate::{CmdResult, CommandSpec as C, Session}; |
| 9 | + |
| 10 | +pub fn commands() -> Vec<C> { |
| 11 | + vec![ |
| 12 | + C::new("osm.download", "Download OpenStreetMap Data", "Home › Add › Add Data", osm_download).params( |
| 13 | + r#"{"bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "view"?: bool (false: a bbox must be given), "preset"?: "buildings"|"roads"|"railways"|"water"|"landuse"|"parks"|"pois"|"boundaries", "tags"?: "key=value, key" (any of them), "url"?: "an Overpass server (default https://overpass-api.de/api/interpreter)", "name"?: text, "answer"?: "the server's JSON answer, when already fetched (the app's background request)"}"#, |
| 14 | + ), |
| 15 | + C::new("boundaries.add", "Add Administrative Boundaries", "Home › Add › Add Data", boundaries_add).params( |
| 16 | + r#"{"country": "ISO 3166 alpha-3 code (CHE, KEN…)", "level"?: "ADM0" (the country, default) … "ADM5", "name"?: text, "text"?: "the boundaries' GeoJSON, when already fetched (the app's background request)"}"#, |
| 17 | + ), |
| 18 | + C::new("boundaries.countries", "List geoBoundaries Countries", "Home › Add › Add Data", boundaries_countries).view(), |
| 19 | + ] |
| 20 | +} |
| 21 | + |
| 22 | +/// The box a command names, the map's extent by default. |
| 23 | +fn bbox(s: &Session, p: &Value) -> Result<[f64; 4], String> { |
| 24 | + match p.get("bbox") { |
| 25 | + Some(v @ Value::Array(_)) => { |
| 26 | + // Every entry a number: one that isn't is an error, not dropped. |
| 27 | + let n: Option<Vec<f64>> = v.as_array().into_iter().flatten().map(Value::as_f64).collect(); |
| 28 | + match n.as_deref().unwrap_or_default() { |
| 29 | + [w, south, e, n] => Ok([*w, *south, *e, *n]), |
| 30 | + _ => Err("bbox is [west, south, east, north], or \"view\"".into()), |
| 31 | + } |
| 32 | + } |
| 33 | + Some(Value::String(v)) if v != "view" => Err("bbox is [west, south, east, north], or \"view\"".into()), |
| 34 | + _ if b(p, "view") == Some(false) => Err("give bbox".into()), |
| 35 | + _ => { |
| 36 | + let e = super::workspace::view_extent(s); |
| 37 | + if e.is_empty() { |
| 38 | + return Err("the map's extent isn't known; give bbox".into()); |
| 39 | + } |
| 40 | + Ok([e.min_x.max(-180.0), e.min_y.max(-90.0), e.max_x.min(180.0), e.max_y.min(90.0)]) |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/// The Overpass query a command describes (the app builds its request from it too). |
| 46 | +pub fn osm_query(s: &Session, p: &Value) -> Result<overpass::Query, String> { |
| 47 | + overpass::Query::new(bbox(s, p)?, ps(p, "preset"), ps(p, "tags")) |
| 48 | +} |
| 49 | + |
| 50 | +fn osm_download(s: &mut Session, p: &Value) -> CmdResult { |
| 51 | + let q = osm_query(s, p)?; |
| 52 | + let url = q.url(ps(p, "url"))?; |
| 53 | + let bytes = match ps(p, "answer") { |
| 54 | + Some(a) => a.as_bytes().to_vec(), |
| 55 | + None => fetch(&url)?, |
| 56 | + }; |
| 57 | + let answer = overpass::parse(&bytes)?; |
| 58 | + let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| q.title()); |
| 59 | + let mut layers = Vec::new(); |
| 60 | + let mut counts = serde_json::Map::new(); |
| 61 | + for (kind, fc) in answer.layers() { |
| 62 | + let (ds, _) = rustgis_data::io::read_geojson(&fc.to_string(), &format!("{name} ({kind})")).map_err(|e| e.to_string())?; |
| 63 | + counts.insert(kind.to_string(), json!(ds.features.len())); |
| 64 | + layers.push(super::layer::add_dataset(s, ds)); |
| 65 | + } |
| 66 | + for n in answer.notes { |
| 67 | + s.notify(format!("{name}: {n}"), false); |
| 68 | + } |
| 69 | + if layers.is_empty() { |
| 70 | + return Err(format!("{name}: nothing found in the area")); |
| 71 | + } |
| 72 | + Ok(json!({"layers": layers, "features": counts})) |
| 73 | +} |
| 74 | + |
| 75 | +fn boundaries_add(s: &mut Session, p: &Value) -> CmdResult { |
| 76 | + let country = boundaries::country(ps(p, "country").ok_or("country is required (such as CHE)")?)?; |
| 77 | + let level = match p.get("level") { |
| 78 | + Some(Value::Number(n)) => boundaries::level(&n.to_string())?, |
| 79 | + _ => boundaries::level(ps(p, "level").unwrap_or("ADM0"))?, |
| 80 | + }; |
| 81 | + let (text, title) = match ps(p, "text") { |
| 82 | + Some(t) => (t.to_string(), None), |
| 83 | + None => { |
| 84 | + let meta = boundaries::parse_meta(&fetch(&boundaries::meta_url(&country, &level))?)?; |
| 85 | + let bytes = fetch(&meta.geojson)?; |
| 86 | + (String::from_utf8(bytes).map_err(|_| "the boundaries aren't UTF-8 text".to_string())?, Some(meta.name)) |
| 87 | + } |
| 88 | + }; |
| 89 | + let name = ps(p, "name") |
| 90 | + .map(str::trim) |
| 91 | + .filter(|n| !n.is_empty()) |
| 92 | + .map(str::to_string) |
| 93 | + .unwrap_or_else(|| format!("{} {level}", title.unwrap_or_else(|| country.clone()))); |
| 94 | + let (ds, _) = rustgis_data::io::read_geojson(&text, &name).map_err(|e| format!("{name}: {e}"))?; |
| 95 | + let n = ds.features.len(); |
| 96 | + let id = super::layer::add_dataset(s, ds); |
| 97 | + if let Some(e) = s.map().layer(id).map(|l| l.extent()) { |
| 98 | + s.zoom_to(&e); |
| 99 | + } |
| 100 | + Ok(json!({"layer": id, "features": n})) |
| 101 | +} |
| 102 | + |
| 103 | +fn boundaries_countries(_s: &mut Session, _p: &Value) -> CmdResult { |
| 104 | + let list = boundaries::parse_countries(&fetch(&boundaries::countries_url())?)?; |
| 105 | + Ok(json!({"count": list.len(), "countries": list.iter().map(|(iso, name)| json!({"iso": iso, "name": name})).collect::<Vec<_>>()})) |
| 106 | +} |
| 107 | + |
| 108 | +/// A fetch the command waits for (the command line and the assistant; the app fetches off the |
| 109 | +/// frame and passes the answer). |
| 110 | +#[cfg(not(target_arch = "wasm32"))] |
| 111 | +fn fetch(url: &str) -> Result<Vec<u8>, String> { |
| 112 | + crate::render::rustgis_tiles::cache::download_blocking(url).map_err(|e| { |
| 113 | + if e.contains("timeout") || e.contains("timed out") { |
| 114 | + "the server didn't answer within a minute (it may be busy): try again later, or a smaller area".to_string() |
| 115 | + } else if e.contains("504") || e.contains("429") { |
| 116 | + format!("{e}: the server is busy, try again in a minute") |
| 117 | + } else { |
| 118 | + e |
| 119 | + } |
| 120 | + }) |
| 121 | +} |
| 122 | + |
| 123 | +#[cfg(target_arch = "wasm32")] |
| 124 | +fn fetch(_url: &str) -> Result<Vec<u8>, String> { |
| 125 | + Err("in the web app, use Home › Add Data › OpenStreetMap… or Boundaries…".into()) |
| 126 | +} |
0 commit comments