Skip to content

Commit e9d7194

Browse files
authored
Open data: OpenStreetMap by area (Overpass) and geoBoundaries (#139)
* Open data: OpenStreetMap by area and geoBoundaries - tiles::overpass builds Overpass QL for a box (presets or tag filters, quoted) and reads the JSON answer into points, lines and polygons: closed ways that are areas, multipolygon and boundary relations joined from their members; the 25 most common tags as fields, the rest in other_tags. Areas up to 0.25 square degrees and answers up to 50,000 elements. - tiles::boundaries reads geoBoundaries' API (a country's level, the country list); GitHub raw links go straight to the large-file host, since downloads follow no redirects. - osm.download, boundaries.add and boundaries.countries (network commands); the app passes its fetched answers, so layers are added through the commands. - Add Data › OpenStreetMap… and Boundaries… fetch off the frame, on the desktop and the web. * Address review feedback - The country list is asked for once: an empty or failed answer leaves the code to be typed and says why, apart from the dialog's actions, instead of being asked again every frame. - other_tags escapes backslashes before quotes. - Tags named osm_type or osm_id stay in other_tags, not over the columns RustGIS adds. - An inner ring no outer ring holds is counted and said; a hole is placed by the first of a few vertices inside an outer ring. - A bbox with an entry that isn't a number is refused, not shortened; the "view" parameter is documented.
1 parent 334363d commit e9d7194

13 files changed

Lines changed: 1109 additions & 0 deletions

File tree

‎crates/engine/src/cmd/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ pub mod layout;
1616
pub mod navigate;
1717
pub mod notebook;
1818
pub mod plugins;
19+
pub mod portals;
1920
pub mod presentation;
2021
pub mod project;
2122
pub mod raster;
@@ -67,6 +68,7 @@ pub fn all() -> Vec<CommandSpec> {
6768
v.extend(plugins::commands());
6869
v.extend(sharing::commands());
6970
v.extend(stac::commands());
71+
v.extend(portals::commands());
7072
v
7173
}
7274

‎crates/engine/src/cmd/portals.rs‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
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+
}

‎crates/engine/src/cmd/tiles.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ pub const NETWORK: &[&str] = &[
1919
"stac.addAsset",
2020
"map.findPlace",
2121
"layer.geocode",
22+
"osm.download",
23+
"boundaries.add",
24+
"boundaries.countries",
2225
];
2326

2427
pub fn commands() -> Vec<C> {

‎crates/engine/src/tests.rs‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,8 @@ fn hostile_params_never_panic() {
411411
// Ask Earth Search when no API is given.
412412
| "stac.collections"
413413
| "stac.search"
414+
// Asks geoBoundaries for its list.
415+
| "boundaries.countries"
414416
) {
415417
continue;
416418
}
@@ -3479,3 +3481,52 @@ fn cloud_optimised_geotiffs_are_read_in_place() {
34793481
let id = r["layer"].as_u64().unwrap() as u32;
34803482
assert!(s.map().layer(id).is_some_and(|l| l.is_raster()), "{r}");
34813483
}
3484+
3485+
/// OpenStreetMap data for an area through an Overpass server (a local one): a layer per geometry
3486+
/// kind; geoBoundaries' GeoJSON given as text; bad requests refused.
3487+
#[test]
3488+
fn osm_and_boundaries() {
3489+
const ANSWER: &[u8] = br#"{"elements": [
3490+
{"type": "node", "id": 1, "lat": 46.945, "lon": 7.445, "tags": {"amenity": "cafe", "name": "Kaffee"}},
3491+
{"type": "way", "id": 2, "tags": {"building": "yes"}, "geometry": [{"lat": 46.94, "lon": 7.44}, {"lat": 46.94, "lon": 7.441}, {"lat": 46.941, "lon": 7.441}, {"lat": 46.94, "lon": 7.44}]},
3492+
{"type": "way", "id": 3, "tags": {"highway": "residential", "name": "Gasse"}, "geometry": [{"lat": 46.94, "lon": 7.44}, {"lat": 46.945, "lon": 7.445}]}
3493+
]}"#;
3494+
let base = serve(ANSWER, 1);
3495+
let mut s = Session::new(Project::default());
3496+
let r = s.run("osm.download", &json!({"bbox": [7.44, 46.94, 7.45, 46.95], "tags": "amenity, building, highway", "url": base})).unwrap();
3497+
assert_eq!(r["layers"].as_array().map(Vec::len), Some(3), "{r}");
3498+
let names: Vec<String> = s.map().layers.iter().map(|l| l.name.clone()).collect();
3499+
assert!(names.iter().any(|n| n == "OSM amenity, building, highway (polygons)"), "{names:?}");
3500+
// The app's answer, passed in.
3501+
let r = s
3502+
.run(
3503+
"osm.download",
3504+
&json!({"bbox": [7.44, 46.94, 7.45, 46.95], "preset": "pois", "name": "Cafés", "answer": std::str::from_utf8(ANSWER).unwrap()}),
3505+
)
3506+
.unwrap();
3507+
assert_eq!(r["features"]["points"], 1);
3508+
for bad in [
3509+
json!({"bbox": [7.0, 46.0, 8.0, 47.0], "preset": "roads"}),
3510+
json!({"bbox": [7.44, 46.94, 7.45, 46.95]}),
3511+
json!({"bbox": [7.44, 46.94, 7.45, 46.95], "preset": "x"}),
3512+
json!({"bbox": [7.44, 46.94, 7.45, 46.95], "preset": "roads", "answer": "<html>busy</html>"}),
3513+
json!({"bbox": "here", "preset": "roads"}),
3514+
// An entry that isn't a number isn't dropped: the box is refused.
3515+
json!({"bbox": [7.44, "x", 46.94, 7.45, 46.95], "preset": "roads"}),
3516+
json!({"preset": "roads", "view": false}),
3517+
] {
3518+
assert!(s.run("osm.download", &bad).is_err(), "{bad}");
3519+
}
3520+
let gj = r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"shapeName": "Bern"}, "geometry": {"type": "Polygon", "coordinates": [[[7, 46], [8, 46], [8, 47], [7, 46]]]}}]}"#;
3521+
let r = s.run("boundaries.add", &json!({"country": "che", "level": 1, "text": gj})).unwrap();
3522+
assert_eq!(r["features"], 1);
3523+
assert!(s.map().layer_by_name("CHE ADM1").is_some());
3524+
for bad in [
3525+
json!({}),
3526+
json!({"country": "CH", "text": gj}),
3527+
json!({"country": "CHE", "level": "ADM9", "text": gj}),
3528+
json!({"country": "CHE", "text": "{"}),
3529+
] {
3530+
assert!(s.run("boundaries.add", &bad).is_err(), "{bad}");
3531+
}
3532+
}

‎crates/tiles/src/boundaries.rs‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
//! geoBoundaries: open administrative boundaries for every country (ADM0 to ADM5), from the
2+
//! geoBoundaries API (https://www.geoboundaries.org). The API's answer names the GeoJSON file
3+
//! (on GitHub's large-file storage); requests are built and answers read here, the fetching is the
4+
//! caller's.
5+
6+
use serde_json::Value;
7+
8+
/// The geoBoundaries API (its open release).
9+
pub const API: &str = "https://www.geoboundaries.org/api/current/gbOpen";
10+
11+
/// A country's ISO 3166-1 alpha-3 code, upper case.
12+
pub fn country(code: &str) -> Result<String, String> {
13+
let c = code.trim().to_ascii_uppercase();
14+
if c.len() == 3 && c.chars().all(|ch| ch.is_ascii_uppercase()) {
15+
Ok(c)
16+
} else {
17+
Err(format!("'{}': a country is its three-letter ISO code (such as CHE or KEN)", code.trim()))
18+
}
19+
}
20+
21+
/// A level, `ADM0` to `ADM5` (a number 0–5 too).
22+
pub fn level(l: &str) -> Result<String, String> {
23+
let t = l.trim().to_ascii_uppercase();
24+
let n = t.strip_prefix("ADM").unwrap_or(&t);
25+
match n.parse::<u8>() {
26+
Ok(n) if n <= 5 => Ok(format!("ADM{n}")),
27+
_ => Err(format!("'{}': a level is ADM0 (the country) to ADM5", l.trim())),
28+
}
29+
}
30+
31+
/// The API's address for a country's level.
32+
pub fn meta_url(country: &str, level: &str) -> String {
33+
format!("{API}/{country}/{level}/")
34+
}
35+
36+
/// The address of every country's ADM0 entry (a list of countries).
37+
pub fn countries_url() -> String {
38+
format!("{API}/ALL/ADM0/")
39+
}
40+
41+
/// A country's level, as the API describes it.
42+
#[derive(Clone, Debug, PartialEq)]
43+
pub struct Boundary {
44+
pub iso: String,
45+
pub name: String,
46+
pub level: String,
47+
/// The simplified GeoJSON's address.
48+
pub geojson: String,
49+
}
50+
51+
/// Reads the API's answer for one country's level.
52+
pub fn parse_meta(bytes: &[u8]) -> Result<Boundary, String> {
53+
let v: Value = serde_json::from_slice(bytes).map_err(|_| "geoBoundaries has no such country or level".to_string())?;
54+
// An unknown country or level is answered as an error text or an empty list.
55+
let v = match &v {
56+
Value::Array(a) => a.first().ok_or("geoBoundaries has no such country or level")?,
57+
v => v,
58+
};
59+
let text = |k: &str| v.get(k).and_then(Value::as_str).map(|s| s.chars().take(300).collect::<String>());
60+
let geojson =
61+
text("simplifiedGeometryGeoJSON").or_else(|| text("gjDownloadURL")).ok_or("geoBoundaries has no such country or level")?;
62+
Ok(Boundary {
63+
iso: text("boundaryISO").unwrap_or_default(),
64+
name: text("boundaryName").unwrap_or_default(),
65+
level: text("boundaryType").unwrap_or_default(),
66+
geojson: direct(&geojson),
67+
})
68+
}
69+
70+
/// The countries the API lists: code and name, sorted by name.
71+
pub fn parse_countries(bytes: &[u8]) -> Result<Vec<(String, String)>, String> {
72+
let v: Value = serde_json::from_slice(bytes).map_err(|_| "the geoBoundaries list isn't JSON".to_string())?;
73+
let mut out: Vec<(String, String)> = v
74+
.as_array()
75+
.ok_or("the geoBoundaries list isn't a list")?
76+
.iter()
77+
.take(1000)
78+
.filter_map(|c| {
79+
let iso = country(c.get("boundaryISO")?.as_str()?).ok()?;
80+
Some((iso, c.get("boundaryName")?.as_str()?.chars().take(100).collect()))
81+
})
82+
.collect();
83+
out.sort_by(|a, b| a.1.cmp(&b.1));
84+
out.dedup();
85+
Ok(out)
86+
}
87+
88+
/// GitHub's `…/raw/…` addresses redirect to the large-file host; the downloads follow no
89+
/// redirects, so the file is asked for there directly.
90+
fn direct(url: &str) -> String {
91+
if let Some(rest) = url.strip_prefix("https://github.com/")
92+
&& let [owner, repo, "raw", reference, path @ ..] = rest.split('/').collect::<Vec<_>>().as_slice()
93+
&& !path.is_empty()
94+
{
95+
return format!("https://media.githubusercontent.com/media/{owner}/{repo}/{reference}/{}", path.join("/"));
96+
}
97+
url.to_string()
98+
}
99+
100+
#[cfg(test)]
101+
mod tests {
102+
use super::*;
103+
104+
#[test]
105+
fn requests_and_answers() {
106+
assert_eq!(country(" che ").unwrap(), "CHE");
107+
assert!(country("CH").is_err() && country("C1E").is_err());
108+
assert_eq!(level("1").unwrap(), "ADM1");
109+
assert_eq!(level("adm0").unwrap(), "ADM0");
110+
assert!(level("ADM6").is_err() && level("x").is_err());
111+
assert_eq!(meta_url("CHE", "ADM1"), "https://www.geoboundaries.org/api/current/gbOpen/CHE/ADM1/");
112+
let meta = br#"{"boundaryISO": "CHE", "boundaryName": "Switzerland", "boundaryType": "ADM1", "simplifiedGeometryGeoJSON": "https://github.com/wmgeolab/geoBoundaries/raw/9469f09/releaseData/gbOpen/CHE/ADM1/x_simplified.geojson"}"#;
113+
let b = parse_meta(meta).unwrap();
114+
assert_eq!((b.iso.as_str(), b.name.as_str(), b.level.as_str()), ("CHE", "Switzerland", "ADM1"));
115+
assert_eq!(
116+
b.geojson,
117+
"https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/9469f09/releaseData/gbOpen/CHE/ADM1/x_simplified.geojson"
118+
);
119+
assert!(parse_meta(b"Not found").is_err() && parse_meta(b"[]").is_err() && parse_meta(b"{}").is_err());
120+
let list = br#"[{"boundaryISO": "KEN", "boundaryName": "Kenya"}, {"boundaryISO": "ABW", "boundaryName": "Aruba"}, {"boundaryISO": "bad!"}]"#;
121+
assert_eq!(parse_countries(list).unwrap(), vec![("ABW".into(), "Aruba".into()), ("KEN".into(), "Kenya".into())]);
122+
assert_eq!(direct("https://example.org/a.geojson"), "https://example.org/a.geojson");
123+
}
124+
}

‎crates/tiles/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
99

1010
pub mod address;
11+
pub mod boundaries;
1112
pub mod cache;
1213
pub mod cog;
1314
pub mod draw;
1415
pub mod geocode;
1516
pub mod mbtiles;
1617
pub mod mvt;
18+
pub mod overpass;
1719
pub mod pmtiles;
1820
pub mod source;
1921
pub mod sprite;

0 commit comments

Comments
 (0)