From 72f71777f8e7d16d10a1aad480a4b1477e299d00 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 09:51:13 +0100 Subject: [PATCH] feat(crs): write GeoJSON, CSV, KML and GPX in longitude/latitude from the system a layer holds (#2032 C1e part 2) The engine's direct writers (Convert/export workflow formats, packaged gp results, OGC collection and web layer zips, the plugin features call, the Python layer_geojson) convert the layer to longitude/latitude at the writer instead of assuming its coordinates are. Behaviour-neutral: every dataset holds longitude/latitude today. --- apps/rustgis-python/src/lib.rs | 15 +++++++++++---- crates/engine/src/cmd/items.rs | 4 +++- crates/engine/src/cmd/plugins.rs | 17 ++++++++++++++++- crates/engine/src/cmd/sharing.rs | 22 +++++++++++++--------- crates/engine/src/cmd/workflows.rs | 14 ++++++++------ xtask/row-uses.txt | 2 +- 6 files changed, 52 insertions(+), 22 deletions(-) diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 25962b8959..91d4e51c8f 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -188,10 +188,11 @@ impl Engine { if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{name} as GeoJSON")) { session.notify(note, false); } - return Ok(rustgis_engine::data::io::to_geojson(&ds).to_string()); + // GeoJSON is longitude/latitude, whatever system the source holds its coordinates in. + return Ok(rustgis_engine::data::io::to_geojson(&*ds.in_lonlat()?).to_string()); } if !selected { - let text = rustgis_engine::data::io::to_geojson(&found.dataset).to_string(); + let text = rustgis_engine::data::io::to_geojson(&*found.dataset.in_lonlat()?).to_string(); let note = rustgis_engine::data::zm_export_note([&found.dataset], &format!("{} as GeoJSON", found.name)); if let Some(note) = note { session.notify(note, false); @@ -200,8 +201,14 @@ impl Engine { } let mut ds = rustgis_engine::data::Dataset::new(found.name.clone(), found.geometry_type(), found.dataset.fields.clone()); ds.zm_dropped = found.dataset.zm_dropped; - for f in found.selection.iter().filter_map(|r| found.dataset.features.get(*r)) { - ds.push(f.geometry.clone(), f.attrs.clone()); + // Copied in longitude/latitude, the system a new dataset holds its coordinates in. + for r in found.selection.iter().filter_map(|&i| found.dataset.features.row(i)) { + let g = r + .geometry() + .map(|g| found.dataset.geometry_to_lonlat(g).map(std::borrow::Cow::into_owned)) + .transpose() + .map_err(|e| format!("{}: feature {}: {e}", found.name, r.id()))?; + ds.push(g, r.values().cloned().collect()); } let text = rustgis_engine::data::io::to_geojson(&ds).to_string(); if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{} as GeoJSON", ds.name)) { diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 83c8c4cfa8..98efbe6f43 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -878,7 +878,9 @@ fn package_gp(s: &mut Session) -> Result, String> { k += 1; file = format!("results/{base}_{k}.geojson"); } - entries.push((file, rustgis_data::io::to_geojson(&l.dataset).to_string().into_bytes())); + // GeoJSON is longitude/latitude, whatever system the result holds its coordinates in. + let ds = l.dataset.in_lonlat()?; + entries.push((file, rustgis_data::io::to_geojson(&ds).to_string().into_bytes())); } rustgis_data::zip::write(&entries) } diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index ba8684ebe2..7cde3a425b 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -587,11 +587,26 @@ impl Bridge<'_> { let target = asked_crs(self.s.map(), l, p)?; let limit = uint(p, "limit").and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX); let rows: Vec = if b(p, "selected") == Some(true) { l.selection.clone() } else { (0..l.dataset.features.len()).collect() }; + // In longitude/latitude, which a response holds unless `crs` asks for another system, + // whatever system the layer holds its coordinates in. + let mut features = rustgis_data::Features::default(); + for r in rows.iter().take(limit).filter_map(|&i| l.dataset.features.row(i)) { + let n = features.len(); + features.push_row(r.to_feature()); + if let Some(g) = r.geometry() + && let std::borrow::Cow::Owned(g) = + l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, r.id()))? + { + features.set_geometry(n, Some(g)); + } + } + // Its geometry is longitude/latitude (above); `crs` stays the layer's, as the system it + // was read in, which `export_error` reads. let ds = rustgis_data::Dataset { name: l.name.clone(), geometry_type: l.dataset.geometry_type, fields: l.dataset.fields.clone(), - features: rows.iter().take(limit).filter_map(|&i| l.dataset.features.get(i).cloned()).collect(), + features, source: None, crs: l.dataset.crs, crs_incomplete: false, diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 62dc35a020..9818083de6 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -506,33 +506,36 @@ fn css(c: Rgba) -> String { format!("rgba({},{},{},{:.3})", c.r(), c.g(), c.b(), f64::from(c.a()) / 255.0) } -/// A layer's visible features as GeoJSON, each with its drawn style. -fn styled_features(l: &Layer, budget: &mut usize) -> Vec { +/// A layer's visible features as GeoJSON, each with its drawn style: in longitude/latitude, +/// whatever system the layer holds its coordinates in; refused, naming the feature, when one of +/// its places can't be given there. +fn styled_features(l: &Layer, budget: &mut usize) -> Result, String> { let rows = l.visible_rows(); let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; let mut out = Vec::new(); // Its symbol by expression (no map scale: the page zooms on its own). let styler = l.styler(None); - for (row, ft) in l.dataset.features.iter().enumerate() { + for (row, ft) in l.dataset.features.rows().enumerate() { if *budget == 0 { break; } if rows.get(row) != Some(&true) { continue; } - let Some(g) = &ft.geometry else { continue }; + let Some(g) = ft.geometry() else { continue }; + let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; let sym = styler.symbol(row); let props: serde_json::Map = l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect(); out.push(json!({ "type": "Feature", - "geometry": rustgis_data::io::geometry_to_geojson(g), + "geometry": rustgis_data::io::geometry_to_geojson(&g), "properties": props, "style": {"fill": css(sym.fill), "stroke": css(sym.stroke), "width": sym.stroke_width, "size": sym.size, "opacity": opacity}, })); *budget -= 1; } - out + Ok(out) } /// A self-contained web map page: the map's layers (rasters as images) drawn on a canvas in Web @@ -571,7 +574,7 @@ fn web_map_html(m: &Map, title: &str) -> Result { json!({"name": l.name, "image": base64::engine::general_purpose::STANDARD.encode(png), "bounds": [a.x, a.y, b.x, b.y]}), ); } else { - layers.push(json!({"name": l.name, "features": styled_features(l, &mut budget)})); + layers.push(json!({"name": l.name, "features": styled_features(l, &mut budget)?})); } } let c = m.center_lonlat(); @@ -864,7 +867,8 @@ fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec)]) -> Res json!({"spatial": {"bbox": [[e.min_x, e.min_y, e.max_x, e.max_y]], "crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84"}}); } entries.push((format!("collections/{id}.json"), serde_json::to_vec_pretty(&col).map_err(|e| e.to_string())?)); - let mut fc = rustgis_data::io::to_geojson(ds); + // GeoJSON is longitude/latitude, whatever system the layer holds its coordinates in. + let mut fc = rustgis_data::io::to_geojson(&*ds.in_lonlat()?); fc["numberReturned"] = json!(ds.features.len()); entries.push((format!("collections/{id}/items.json"), serde_json::to_vec(&fc).map_err(|e| e.to_string())?)); cols.push(col); @@ -882,7 +886,7 @@ fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec)]) -> Res /// A web layer: the layer as an OGC API Features collection, its style, and a viewer page. fn web_layer_zip(s: &Session, l: &Layer) -> Result, String> { let style = serde_json::to_vec_pretty(&web_style(l)).map_err(|e| e.to_string())?; - let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&l.dataset)).map_err(|e| e.to_string())?; + let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&*l.dataset.in_lonlat()?)).map_err(|e| e.to_string())?; let mut m = s.map().clone(); m.layers = vec![l.clone()]; let e = l.extent(); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 856ea85976..39f9847732 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2089,14 +2089,16 @@ fn converted(ds: &Dataset, p: &Value) -> Result<(String, Vec), String> { let name_field = ps(p, "nameField").and_then(|n| ds.field_index(n)).or_else(|| ds.fields.iter().position(|f| f.name.eq_ignore_ascii_case("name"))); let format = conversion_format(p)?; + // Every format here is longitude/latitude, whatever system the layer holds its coordinates + // in; the notes below read the layer itself, converting as they need. + let lonlat = ds.in_lonlat()?; let text = match format { - "geojson" => rustgis_data::io::to_geojson_text(ds).map_err(|e| e.to_string())?, - "csv" => rustgis_data::io::to_csv(ds).map_err(|e| e.to_string())?, - "kml" => rustgis_data::interop::to_kml(ds, name_field).map_err(|e| e.to_string())?, - "gpx" => rustgis_data::interop::to_gpx(ds, name_field).map_err(|e| e.to_string())?, - _ => rustgis_data::interop::to_wkt_csv(ds).map_err(|e| e.to_string())?, + "geojson" => rustgis_data::io::to_geojson_text(&lonlat).map_err(|e| e.to_string())?, + "csv" => rustgis_data::io::to_csv(&lonlat).map_err(|e| e.to_string())?, + "kml" => rustgis_data::interop::to_kml(&lonlat, name_field).map_err(|e| e.to_string())?, + "gpx" => rustgis_data::interop::to_gpx(&lonlat, name_field).map_err(|e| e.to_string())?, + _ => rustgis_data::interop::to_wkt_csv(&lonlat).map_err(|e| e.to_string())?, }; - // Every format here is longitude/latitude. let target = ps(p, "path").unwrap_or(&ds.name); let mut notes = rustgis_data::export_notes([(ds, ds.lonlat_extent())], target, rustgis_data::raster::Crs::LonLat); notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target).map_err(|e| e.to_string())?); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index e6016f6342..322588ef3a 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 839 +count = 833