Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,7 @@ impl Agent {
/// Commands worth knowing without a search: their parameters come from the registry.
const COMMON: &[&str] = &[
"map.goToXY",
"map.convertPosition",
"map.setScale",
"map.zoomFull",
"map.basemap",
Expand Down
106 changes: 99 additions & 7 deletions crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub fn commands() -> Vec<C> {
C::new("map.goToXY", "By Coordinates…", "Home › Navigate › Locate", go_to_xy).roles(&[]).effects(crate::policy::Effects::NONE)
.view()
.params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350), "scale"?: number, "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85)}"#),
C::new("map.convertPosition", "Convert Position", "Home › Navigate › Locate", convert_position).roles(&[]).effects(crate::policy::Effects::NONE)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reach (AGENTS.md "Reach every surface"). map.goToXY has a dialog on the desktop (chrome.rs search_action, "map.goToXY" => Dialog("goToXY")). map.convertPosition has no entry there, so the desktop has no form to take its input and no place that shows its answer, since the returned JSON is only visible to scripts, Python and the Assistant. The PR description covers those surfaces but says nothing about the desktop ribbon and command search, the browser, the phone (ui-touch), MCP or plugins, or why each doesn't apply. Please either state that in the PR or show how the desktop reaches the result. Confidence: medium (about 55%). I did not verify how command search treats a command with required parameters that has no dialog route.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a Surfaces section to the description. Short version: CLI, Python, MCP, the Assistant, the web app and plugins all reach it as a command. On the desktop and phone there's no dialog on purpose, since the status-bar readout and the right-click menu already show and copy each form. It's read-only, so there's nothing to undo.

.view()
.params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; Z AC 77146 62481), "digits"?: MGRS digits per axis, 0 (100 km) to 5 (1 m, the default)}"#),
C::new("map.goToLink", "Go To Map Link", "Home › Navigate", go_to_link).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
.params(r#"{"url": a map link ending in #zoom/lat/lon[/bearing[/pitch]] (as MapLibre writes them; also #map=…), or just zoom/lat/lon[/bearing[/pitch]]}"#),
Expand Down Expand Up @@ -527,19 +530,23 @@ fn degrees_text(v: f64) -> String {
if v == 0.0 { "0".into() } else { format!("{v}") }
}

pub(crate) fn go_to_xy(s: &mut Session, p: &Value) -> CmdResult {
/// The place a command's parameters give, as `map.goToXY` and `map.convertPosition` take it: a
/// `position` written as the search box reads one, or `lon` and `lat` (or `x` and `y`), each a
/// number or text in degrees, minutes and seconds. With it, what the reading assumed, for a
/// notice: two bare numbers taken in an order, or an MGRS square taken at its center (`moving`
/// says whether the map goes there, which the notice's wording follows).
fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option<crate::notice_text::NoticeText>), String> {
let position = match p.get("position") {
None | Some(Value::Null) => None,
Some(Value::String(t)) => Some(t.as_str()),
Some(_) => return Err("position must be text, such as \"40.7128, -74.006\" or \"18TWL8395907350\"".into()),
};
let given = |k: &str| !matches!(p.get(k), None | Some(Value::Null));
// What the reading assumed is said once the map has moved there, not before a refusal.
let (lon, lat, notice) = if let Some(text) = position {
if ["lon", "lat", "x", "y"].iter().any(|k| given(k)) {
return Err("give a position or lon and lat, not both".into());
}
let (c, read) = read_position(s.map(), text)?;
let (c, read) = read_position(map, text)?;
let reference = || text.trim().to_string().into();
let said = match read {
PositionRead::AsWritten => None,
Expand All @@ -549,10 +556,13 @@ pub(crate) fn go_to_xy(s: &mut Session, p: &Value) -> CmdResult {
)),
PositionRead::Square(side) => {
let side = if side >= 1000.0 { format!("{} km", side / 1000.0) } else { format!("{side} m") };
Some(crate::notice_text::NoticeText::format(
"{reference} names a {side} square, not a point: went to its center",
[("reference", reference()), ("side", side.into())],
))
// Both whole, as the translation catalogs take them.
let template = if moving {
"{reference} names a {side} square, not a point: went to its center"
} else {
"{reference} names a {side} square, not a point: gave its center"
};
Some(crate::notice_text::NoticeText::format(template, [("reference", reference()), ("side", side.into())]))
}
};
(c.x, c.y, said)
Expand All @@ -570,6 +580,88 @@ pub(crate) fn go_to_xy(s: &mut Session, p: &Value) -> CmdResult {
if !(-180.0..=180.0).contains(&lon) || !(-90.0..=90.0).contains(&lat) {
return Err("longitude must be within ±180 and latitude within ±90".into());
}
Ok((Coord::new(lon, lat), notice))
}

/// A place in every form RustGIS writes one (#1042): longitude and latitude, in decimal degrees
/// and in degrees, minutes and seconds as the status bar shows them; UTM, or UPS from 84° N
/// and south of 80° S, with the easting and northing (`grid` says which: `utm` and `ups` each hold
/// only their own); and MGRS spaced as the readout writes it and in one word, to `digits` digits
/// (5 by default: 1 m). The place is read as `map.goToXY` reads it, and what the reading assumed
/// is said the same way. The map doesn't move. Every key is always there, `null` where it has no
/// value; on another body's map the Earth's grids are `null` and `note` says why.
fn convert_position(s: &mut Session, p: &Value) -> CmdResult {
let digits = match p.get("digits") {
None | Some(Value::Null) => 5,
// A whole number sent as 2.0 (as Python or JavaScript may) is as good as 2.
Some(v) => v
.as_f64()
.filter(|d| d.fract() == 0.0 && (0.0..=5.0).contains(d))
.ok_or("digits must be a whole number from 0 (100 km) to 5 (1 m)")? as u8,
};
let (c, notice) = typed_place(s.map(), p, false)?;
// Degrees to 1e-9 (under a millimeter), so text in degrees, minutes and seconds doesn't come
// back as -74.00600000000001; adding 0.0 turns a -0.0 from a tiny negative into 0. Every form
// below is made from this one place, so they all agree on its hemisphere.
let nano = |v: f64| (v * 1e9).round() / 1e9 + 0.0;
let c = Coord::new(nano(c.x), nano(c.y));
// Grid meters truncated to the millimeter, as MGRS truncates: rounding could lift a southern
// northing a hair short of the equator to 10,000,000 m, the equator itself.
let mm = |v: f64| (v * 1000.0).floor() / 1000.0;
let mut out = json!({
"lon": c.x,
"lat": c.y,
"decimal": rustgis_geom::format_lonlat(c),
"dms": rustgis_geom::format_dms(c),
"grid": null,
"utm": null,
"ups": null,
"zone": null,
"band": null,
"hemisphere": null,
"easting": null,
"northing": null,
"mgrs": null,
"mgrsCompact": null,
"note": null,
});
if !s.map().body().is_earth() {
out["note"] = json!("UTM, UPS and MGRS are the Earth's grids and name no place on this map");
} else {
if let Some(u) = rustgis_geom::to_utm(c) {
out["grid"] = json!("utm");
out["utm"] = json!(u.to_string());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible inconsistency within one answer. The utm string comes from Utm's Display, which rounds easting and northing to whole meters (utm.rs:265, .round()). The mgrs field comes from to_mgrs, which floors them (utm.rs:404, .floor()). A point with easting 583959.7 therefore returns easting: 583959.7, utm: "18north 583960 …" and mgrs: "18T WL 83959 …" in the same object. The existing test point (New York) has a fractional part under 0.5, so it hides this. Confidence: low to medium (about 40%). The Display rounding predates this PR, but this command now puts both forms side by side. Either format utm from the floored values, or say in the doc that the two can differ by one meter. I did not check whether the coordinate readout relies on the rounded form.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, that's how the readouts behave too: the UTM text rounds to the meter as GeoConvert writes it, and MGRS truncates by definition. I kept both and said so in the user guide in 9784702, with easting and northing there for the exact place. That commit also makes every field come from the same rounded place, so they agree on the hemisphere right at the equator.

out["zone"] = json!(u.zone);
out["band"] = json!(u.band.to_string());
out["hemisphere"] = json!(u.hemisphere());
out["easting"] = json!(mm(u.easting));
out["northing"] = json!(mm(u.northing));
} else if let Some(u) = rustgis_geom::to_ups(c) {
out["grid"] = json!("ups");
out["ups"] = json!(u.to_string());
out["hemisphere"] = json!(u.hemisphere());
out["easting"] = json!(mm(u.easting));
out["northing"] = json!(mm(u.northing));
}
match rustgis_geom::to_mgrs(c, digits) {
Some(m) => {
out["mgrs"] = json!(m.to_string());
out["mgrsCompact"] = json!(m.compact());
}
// Not reached by any place on the Earth today, but said rather than left a bare null.
None => out["note"] = json!("no MGRS reference names this place"),
}
}
if let Some(said) = notice {
s.notify_text(said, false);
}
Ok(out)
}

pub(crate) fn go_to_xy(s: &mut Session, p: &Value) -> CmdResult {
// What the reading assumed is said once the map has moved there, not before a refusal.
let (c, notice) = typed_place(s.map(), p, true)?;
let (lon, lat) = (c.x, c.y);
// A scale that can't be used is refused, not dropped.
let scale = match p.get("scale") {
None | Some(Value::Null) => None,
Expand Down
106 changes: 106 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51356,6 +51356,112 @@ fn go_to_xy_reads_a_position_as_the_search_box_does() {
assert!(e.contains("write a position as") && !e.contains("UTM"), "{e}");
}

/// `map.convertPosition` gives a place in every form RustGIS writes one (#1042), read as
/// `map.goToXY` reads it, without moving the map: each form converts to the others, UPS in the
/// polar areas, MGRS to fewer digits, what the reading assumed said, and on another body only
/// degrees. Expected grids: GeographicLib's `GeoConvert` for New York (as above); PROJ 9 (WGS 84 /
/// UPS North, EPSG:32661, and UTM zone 33N, EPSG:32633) for the polar and Svalbard places.
#[test]
fn convert_position_gives_every_form() {
let mut s = world();
s.run("map.goToXY", &json!({"lon": 10, "lat": 50})).unwrap();
let center = s.map().center_lonlat();
let convert = |s: &mut Session, p: Value| s.run("map.convertPosition", &p).unwrap();
// New York, written five ways: the same place every time.
for p in [
json!({"position": "40.7128, -74.006"}),
json!({"position": "40°42′46.08″N 74°0′21.6″W"}),
json!({"position": "18TWL8395907350"}),
json!({"lon": -74.006, "lat": 40.7128}),
json!({"lon": "74°0′21.6″W", "lat": "40°42′46.08″N"}),
] {
let v = convert(&mut s, p.clone());
assert!((v["lon"].as_f64().unwrap() + 74.006).abs() < 1e-5 && (v["lat"].as_f64().unwrap() - 40.7128).abs() < 1e-5, "{p}: {v}");
assert_eq!(v["grid"], "utm", "{p}");
if p["position"] == "18TWL8395907350" {
// A 1 m square, read at its center, 583959.5 4507350.5: rounding that to the meter
// can go either way, so the center itself is checked.
let (e, n) = (v["easting"].as_f64().unwrap(), v["northing"].as_f64().unwrap());
assert!((e - 583_959.5).abs() < 0.01 && (n - 4_507_350.5).abs() < 0.01, "{v}");
} else {
assert_eq!(v["utm"], "18north 583959 4507351", "{p}");
}
assert_eq!((v["zone"].as_u64(), v["band"].as_str(), v["hemisphere"].as_str()), (Some(18), Some("T"), Some("north")), "{p}");
assert_eq!(v["mgrs"], "18T WL 83959 07350", "{p}");
assert_eq!(v["mgrsCompact"], "18TWL8395907350", "{p}");
assert_eq!(v["decimal"], "74.0060° W 40.7128° N", "{p}");
assert!(v["ups"].is_null() && v["note"].is_null(), "{p}: {v}");
}
// Degrees from degrees, minutes and seconds come back without float noise.
let v = convert(&mut s, json!({"lon": "74°0′21.6″W", "lat": "40°42′46.08″N"}));
assert_eq!((v["lon"].as_f64(), v["lat"].as_f64()), (Some(-74.006), Some(40.7128)), "{v}");
let v = convert(&mut s, json!({"lon": -74.006, "lat": 40.7128}));
assert!((v["easting"].as_f64().unwrap() - 583_959.0).abs() < 1.0 && (v["northing"].as_f64().unwrap() - 4_507_351.0).abs() < 1.0, "{v}");
assert_eq!(v["dms"], rustgis_geom::format_dms(rustgis_geom::Coord::new(-74.006, 40.7128)));
// Fewer MGRS digits truncate, as MGRS does: 1 km here.
// Fewer digits as a whole number sent as 2.0 too, as Python or JavaScript may send it.
for digits in [json!(2), json!(2.0)] {
let v = convert(&mut s, json!({"lon": -74.006, "lat": 40.7128, "digits": digits}));
assert_eq!((v["mgrs"].as_str(), v["mgrsCompact"].as_str()), (Some("18T WL 83 07"), Some("18TWL8307")), "{digits}");
}
// A tiny negative comes back as 0, not -0, and every form agrees it is on the equator, in the
// north: the same place throughout.
let v = convert(&mut s, json!({"lon": -1e-12, "lat": -1e-12}));
assert!(v["lon"].as_f64().unwrap().is_sign_positive() && v["lat"].as_f64().unwrap().is_sign_positive(), "{v}");
assert_eq!((v["hemisphere"].as_str(), v["band"].as_str(), v["northing"].as_f64()), (Some("north"), Some("N"), Some(0.0)), "{v}");
assert_eq!(v["decimal"], "0.0000° E 0.0000° N", "{v}");
// Just south of the equator the northing stays short of 10,000,000 m (the equator), as MGRS
// does, so the two forms of one answer name the same side.
let v = convert(&mut s, json!({"lon": 3, "lat": -3e-9}));
assert_eq!((v["hemisphere"].as_str(), v["band"].as_str()), (Some("south"), Some("M")), "{v}");
assert!(v["northing"].as_f64().unwrap() < 10_000_000.0, "{v}");
// North of 84° N it is UPS, in `ups` not `utm`, with no zone or UTM band; polar MGRS has no
// zone number. Svalbard takes its own zone, 33, at 10° E.
let v = convert(&mut s, json!({"lon": 30, "lat": 85}));
assert_eq!(
(v["grid"].as_str(), v["ups"].as_str(), v["hemisphere"].as_str()),
(Some("ups"), Some("north 2277729 1518960"), Some("north"))
);
assert!(v["utm"].is_null() && v["zone"].is_null() && v["band"].is_null(), "{v}");
assert_eq!(v["mgrs"], "Z CC 77728 18959");
let v = convert(&mut s, json!({"position": "north 2277729 1518960"}));
assert!((v["lat"].as_f64().unwrap() - 85.0).abs() < 1e-5 && (v["lon"].as_f64().unwrap() - 30.0).abs() < 1e-4, "{v}");
assert_eq!(convert(&mut s, json!({"lon": 10, "lat": 83.9}))["utm"], "33north 440754 9319502");
// What the reading assumed is said, once; a reference to the meter or lettered degrees say
// nothing.
for (p, said) in [
(json!({"position": "18TWL"}), Some("names a 100 km square, not a point: gave its center")),
(json!({"position": "2.35, 48.85"}), Some("Read 2.35, 48.85 as latitude 2.35, longitude 48.85")),
(json!({"position": "18TWL8395907350"}), None),
(json!({"lon": 2.35, "lat": 48.85}), None),
] {
let mark = s.notice_mark();
convert(&mut s, p.clone());
let notices: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
match said {
Some(t) => assert!(notices.len() == 1 && notices[0].contains(t), "{p}: {notices:?}"),
None => assert!(notices.is_empty(), "{p}: {notices:?}"),
}
}
// Refused as goToXY refuses, and for digits that MGRS has no such precision for.
let refused = |s: &mut Session, p: Value| s.run("map.convertPosition", &p).unwrap_err();
assert!(refused(&mut s, json!({"position": "33UZZ1234512345"})).starts_with("no place at this grid reference"));
assert!(refused(&mut s, json!({"position": "40.7, -74", "lon": 1})).contains("not both"));
assert!(refused(&mut s, json!({"lon": 200, "lat": 0})).contains("within ±180"));
for d in [json!(6), json!(-1), json!(2.5), json!("5")] {
assert!(refused(&mut s, json!({"lon": 0, "lat": 0, "digits": d})).contains("digits must be"), "{d}");
}
// The map hasn't moved.
assert_eq!(s.map().center_lonlat(), center);
// On another body degrees convert; the Earth's grids name no place, and the note says so.
s.run("map.body", &json!({"name": "Mars", "basemap": false})).unwrap();
let v = convert(&mut s, json!({"lon": 77.5, "lat": 18.4}));
assert_eq!(v["decimal"], "77.5000° E 18.4000° N");
assert!(v["utm"].is_null() && v["mgrs"].is_null() && v["grid"].is_null(), "{v}");
assert!(v["note"].as_str().unwrap().contains("Earth's grids"), "{v}");
assert!(refused(&mut s, json!({"position": "18TWL8395907350"})).contains("Earth's grids"));
}

/// A mobile map package says what simplifying its layers changed or left alone (#1811): a line
/// reaching 95° (bad data) has its vertex taken as the pole, and a part of one vertex left out;
/// lines with a longitude too far out are left as they were; one notice per kind. A clean layer,
Expand Down
21 changes: 21 additions & 0 deletions docs/user-guide/maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,27 @@ itself is UTM. On the map of another body than the Earth the readout shows *No U
it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS,
reads as decimal degrees with a notice, and stays saved until you pick a format.

`map.convertPosition` gives a place in all of these forms at once, without moving the map, for
scripts, Python and the AI Assistant. It takes the place as `map.goToXY` does: `lon` and `lat`
(numbers, or degrees, minutes and seconds), or a `position` written in any form the search box
reads, and says what it assumed the same way. It answers with `lon` and `lat`, `decimal` and
`dms` as the readout writes them, `grid` (`utm`, or `ups` in the polar areas), the reference in
`utm` or `ups` (whichever `grid` names; the other is `null`), the UTM `zone` and latitude `band`
(`null` in UPS), `hemisphere`, `easting` and `northing` in meters, and `mgrs` spaced as the
readout writes it and `mgrsCompact` in one word. `digits` (0 to 5, 5 by default) sets the MGRS
precision, from 100 km to 1 m. As in the readouts, the `utm` and `ups` text round to the meter
while MGRS truncates, so the two can differ by a meter; `easting` and `northing` give the place
to the millimeter (truncated). Every key is always there, `null` where it has no value; on
another body's map the grids are `null`, and `note` says why.

```
rustgis-cli run --cmd 'map.convertPosition={"position":"18TWL8395907350"}'
```

```python
s.run("map.convertPosition", {"lon": -74.006, "lat": 40.7128})["utm"] # '18north 583959 4507351'
```

The [search box](#navigating) takes the same grid references, in any case (polar references have
their own rules, below):

Expand Down
Loading