From 4a61c755d94856853747360f8031f989f6488035 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 09:41:01 -0800 Subject: [PATCH] Search reads degrees-minutes-seconds, UTM, MGRS and plus codes --- scripts/format-scope.json | 3 + scripts/package-boundaries.json | 8 + src/search/coordinateParser.js | 68 ++++- src/search/coordinateParser.test.mjs | 7 +- src/search/gridReference.js | 232 ++++++++++++++++ src/search/gridReference.test.mjs | 395 +++++++++++++++++++++++++++ src/search/plusCode.js | 90 ++++++ 7 files changed, 788 insertions(+), 15 deletions(-) create mode 100644 src/search/gridReference.js create mode 100644 src/search/gridReference.test.mjs create mode 100644 src/search/plusCode.js diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 8487f7472..99ab5a1c8 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -180,6 +180,9 @@ "src/search/google.js", "src/search/coordinateParser.js", "src/search/coordinateParser.test.mjs", + "src/search/gridReference.js", + "src/search/gridReference.test.mjs", + "src/search/plusCode.js", "src/search/coordinateGeocoder.js", "src/search/presetGeocoder.js", "src/search/offlineGeocoders.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index c275337cb..bec87c9ba 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -670,6 +670,8 @@ "src/search/alpsGeocoder.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/search/nominatim.js", "src/nominatimGeocode.js", @@ -3268,6 +3270,8 @@ "src/app/layers/directions.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/voice/session.js", "src/voice/sessionCommands.js", @@ -4264,6 +4268,8 @@ "src/app/layers/directions.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/app/localGeojsonServices.js", "src/data/displayText.js", @@ -4609,6 +4615,8 @@ "src/services/terrainHeights.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/search/nominatim.js", "src/nominatimGeocode.js", diff --git a/src/search/coordinateParser.js b/src/search/coordinateParser.js index 948cc25e7..bbcd1f024 100644 --- a/src/search/coordinateParser.js +++ b/src/search/coordinateParser.js @@ -1,14 +1,18 @@ /** - * Strict decimal-degree coordinate parsing for the search box. + * Strict coordinate parsing for the search box. * * A search that guesses is worse than one that declines: reading `12junk, 34oops` * as 12, 34 flies the operator somewhere they did not ask for and looks like a * successful search. So every rule here is exact — a component is a decimal - * number, optionally signed, optionally marked with one hemisphere letter, and - * nothing else. Two-dimensional WGS84 geo URIs use their own strict grammar. - * Degrees/minutes/seconds and grid references are not handled; - * they fall through to the geocoders, which is what happens today. + * number, or degrees with minutes and seconds marked by their symbols + * (`40°26'46"`), optionally signed, optionally marked with one hemisphere + * letter, and nothing else. Two-dimensional WGS84 geo URIs use their own + * strict grammar, as do UTM and MGRS grid references (`gridReference.js`) and + * full plus codes (`plusCode.js`). Unmarked runs such as `40 26 46 N` and + * short plus codes are not handled; they fall through to the geocoders. */ +import { parseGridReference } from './gridReference.js'; +import { parsePlusCode } from './plusCode.js'; /** One decimal-degree component: an optional hemisphere letter on either side. */ const COMPONENT = @@ -18,6 +22,14 @@ const COMPONENT = const GEO_URI = /^geo:(-?\d{1,2}(?:\.\d+)?),(-?\d{1,3}(?:\.\d+)?)(?:;crs=wgs84)?$/i; +/** + * Degrees, minutes and optional seconds, each marked by its symbol, with an + * optional sign and one optional hemisphere letter on either side. Only the + * last number may have a decimal part. + */ +const DMS_COMPONENT = + /^([NSEW])?\s*([+-])?(\d{1,3})\s*[°º]\s*(\d{1,2}(?:\.\d+)?)\s*['′’]\s*(?:(\d{1,2}(?:\.\d+)?)\s*(?:"|″|”|''|′′))?\s*([NSEW])?$/i; + /** Hemisphere letters, by the axis each one can name. */ const LATITUDE_LETTERS = new Set(['N', 'S']); @@ -29,7 +41,7 @@ const LATITUDE_LETTERS = new Set(['N', 'S']); */ function readComponent(text) { const match = COMPONENT.exec(String(text).trim()); - if (!match) return null; + if (!match) return readDmsComponent(text); const [, before, digits, after] = match; // Two letters on one component is a contradiction, not a coordinate. if (before && after) return null; @@ -47,6 +59,34 @@ function readComponent(text) { }; } +/** + * Read one degrees-minutes-seconds component, by the same rules as a decimal + * one: a sign and a letter never both, minutes and seconds below 60, and a + * decimal part only on the last number given. + * + * @param {string} text + * @returns {{ value: number, axis: 'lat'|'lon'|null } | null} + */ +function readDmsComponent(text) { + const match = DMS_COMPONENT.exec(String(text).trim()); + if (!match) return null; + const [, before, sign, degrees, minutes, seconds, after] = match; + if (before && after) return null; + const letter = (before || after || '').toUpperCase(); + if (letter && sign) return null; + if (seconds !== undefined && minutes.includes('.')) return null; + if (Number(minutes) >= 60 || (seconds !== undefined && Number(seconds) >= 60)) + return null; + const magnitude = + Number(degrees) + Number(minutes) / 60 + Number(seconds ?? 0) / 3600; + if (!letter) + return { value: sign === '-' ? -magnitude : magnitude, axis: null }; + return { + value: letter === 'S' || letter === 'W' ? -magnitude : magnitude, + axis: LATITUDE_LETTERS.has(letter) ? 'lat' : 'lon', + }; +} + /** * Split on a comma, a semicolon, or whitespace — never on anything else. * A hemisphere letter stays with the number it names, so `40.7 N 74.0 W` @@ -61,8 +101,9 @@ function splitComponents(query) { return trimmed.length === 2 && trimmed.every(Boolean) ? trimmed : null; } const words = text.split(/\s+/); - // Each component has at most a number, a degree sign and one hemisphere. - if (words.length > 6) return null; + // Each component has at most degrees, minutes and seconds with their + // symbols and one hemisphere letter. + if (words.length > 14) return null; // Keep every character: extracting tokens would turn `1e3` or `1.2.3` // into invented coordinates. A lone letter between numbers can name either // component; require an unambiguous split rather than guessing its owner. @@ -88,7 +129,9 @@ export function formatCoordinateLabel(lat, lon) { } /** - * Parse a decimal-degree pair or a two-dimensional WGS84 geo URI, or return null. + * Parse a decimal-degree or degrees-minutes-seconds pair, a two-dimensional + * WGS84 geo URI, a UTM or MGRS grid reference or a full plus code, or return + * null. * * Both orders are accepted when the hemisphere letters say which is which * (`W 40, N 74` is longitude then latitude); with no letters the conventional @@ -107,7 +150,12 @@ export function parseCoordinateQuery(query) { const parts = /^geo:/i.test(text) ? GEO_URI.exec(text)?.slice(1, 3) : splitComponents(text); - if (!parts) return null; + if (!parts) { + const point = parseGridReference(text) ?? parsePlusCode(text); + return ( + point && { ...point, label: formatCoordinateLabel(point.lat, point.lon) } + ); + } const first = readComponent(parts[0]); const second = readComponent(parts[1]); diff --git a/src/search/coordinateParser.test.mjs b/src/search/coordinateParser.test.mjs index 6128d5f4c..a9ec94de3 100644 --- a/src/search/coordinateParser.test.mjs +++ b/src/search/coordinateParser.test.mjs @@ -124,12 +124,9 @@ test('malformed and ambiguous coordinates are refused, never guessed', () => { '0, 181', '0, -180.5', 'N 100, W 74', - // Degrees/minutes/seconds is out of scope and must fall through, not - // be read as a decimal pair. - '40°26\'46"N, 79°58\'56"W', + // Degrees/minutes/seconds without their symbols must fall through, not + // be read as a decimal pair (marked ones are in gridReference.test.mjs). '40 26 46, 79 58 56', - // A grid reference is out of scope too. - '33UXP0500444998', ]) { assert.equal( parseCoordinateQuery(query), diff --git a/src/search/gridReference.js b/src/search/gridReference.js new file mode 100644 index 000000000..db890f492 --- /dev/null +++ b/src/search/gridReference.js @@ -0,0 +1,232 @@ +/** + * UTM and MGRS grid references to latitude and longitude, for the search box. + * + * Strict, like the decimal parser: a reference either reads exactly or is + * declined. UTM is `18T 585628 4511322` (zone, latitude band, easting, + * northing); MGRS is `18T WL 85650 11369`, spaced or not, with 1 to 5 digits + * each for easting and northing. MGRS letters are capitals, as references are + * printed, unless written unspaced to 100 m or finer (`18twl856113`): + * lower-case `1 jan 2023` or `3 usa 12` is ordinary text, not a grid square. The polar UPS bands (A, B, + * Y, Z) and the zones Svalbard does not use (32X, 34X, 36X) decline. A UTM `S` + * is the 32°N–40°N band when its northing falls in that band, and otherwise + * the southern hemisphere, as UTM is also written; a southern reference + * between about 50°S and 58°S written that way reads as band S. + */ + +/** WGS84. */ +const A = 6378137; +const F = 1 / 298.257223563; +const K0 = 0.9996; +const FALSE_EASTING = 500000; +const FALSE_NORTHING_SOUTH = 10000000; + +/** Latitude bands C to X (no I or O), 8° each from 80°S; X is 12°. */ +const BANDS = 'CDEFGHJKLMNPQRSTUVWX'; + +/** MGRS 100 km column letters by zone set, and the row letters. */ +const COLUMN_SETS = ['ABCDEFGH', 'JKLMNPQR', 'STUVWXYZ']; +const ROW_LETTERS = 'ABCDEFGHJKLMNPQRSTUV'; + +/** The latitude range of a band letter, or null. */ +function bandRange(letter) { + const index = BANDS.indexOf(letter); + if (index < 0) return null; + const south = -80 + index * 8; + return { south, north: letter === 'X' ? 84 : south + 8 }; +} + +/** + * Inverse transverse Mercator (Krüger's series to the sixth order, as in + * Karney 2011): UTM easting and northing in a zone to latitude and longitude. + */ +function utmToLatLon(zone, easting, northing, southern) { + const n = F / (2 - F); + const n2 = n * n; + const n3 = n2 * n; + const n4 = n3 * n; + const n5 = n4 * n; + const n6 = n5 * n; + const rectifying = (A / (1 + n)) * (1 + n2 / 4 + n4 / 64 + n6 / 256); + const beta = [ + n / 2 - + (2 / 3) * n2 + + (37 / 96) * n3 - + n4 / 360 - + (81 / 512) * n5 + + (96199 / 604800) * n6, + n2 / 48 + + n3 / 15 - + (437 / 1440) * n4 + + (46 / 105) * n5 - + (1118711 / 3870720) * n6, + (17 / 480) * n3 - (37 / 840) * n4 - (209 / 4480) * n5 + (5569 / 90720) * n6, + (4397 / 161280) * n4 - (11 / 504) * n5 - (830251 / 7257600) * n6, + (4583 / 161280) * n5 - (108847 / 3991680) * n6, + (20648693 / 638668800) * n6, + ]; + const xi = + (southern ? northing - FALSE_NORTHING_SOUTH : northing) / (K0 * rectifying); + const eta = (easting - FALSE_EASTING) / (K0 * rectifying); + let xiPrime = xi; + let etaPrime = eta; + for (let j = 1; j <= 6; j += 1) { + xiPrime -= beta[j - 1] * Math.sin(2 * j * xi) * Math.cosh(2 * j * eta); + etaPrime -= beta[j - 1] * Math.cos(2 * j * xi) * Math.sinh(2 * j * eta); + } + const conformal = Math.asin(Math.sin(xiPrime) / Math.cosh(etaPrime)); + const longitudeOffset = Math.atan2(Math.sinh(etaPrime), Math.cos(xiPrime)); + // Conformal to geodetic latitude, by Newton's method on tan φ. + const e = Math.sqrt(F * (2 - F)); + const tauPrime = Math.tan(conformal); + let tau = tauPrime; + for (let i = 0; i < 6; i += 1) { + const sigma = Math.sinh( + e * Math.atanh((e * tau) / Math.sqrt(1 + tau * tau)), + ); + const tauIPrime = + tau * Math.sqrt(1 + sigma * sigma) - sigma * Math.sqrt(1 + tau * tau); + const delta = + ((tauPrime - tauIPrime) / Math.sqrt(1 + tauIPrime * tauIPrime)) * + ((1 + (1 - e * e) * tau * tau) / + ((1 - e * e) * Math.sqrt(1 + tau * tau))); + tau += delta; + if (Math.abs(delta) < 1e-12) break; + } + const lat = (Math.atan(tau) * 180) / Math.PI; + let lon = (zone - 1) * 6 - 180 + 3 + (longitudeOffset * 180) / Math.PI; + if (lon > 180) lon -= 360; + if (lon < -180) lon += 360; + return { lat, lon }; +} + +/** + * Whether a latitude sits in a band, allowing `slack` degrees past its edges + * (an MGRS square's centre can lie across the band edge the square touches). + */ +function inBand(lat, range, slack = 0) { + return lat >= range.south - slack && lat <= range.north + slack; +} + +/** Zones 32, 34 and 36 do not exist in band X (Svalbard's widened zones). */ +function zoneExists(zone, band) { + return !(band === 'X' && (zone === 32 || zone === 34 || zone === 36)); +} + +/** UTM `18T 585628 4511322` (or `18 T 585628 4511322`), or null. */ +function parseUtm(text) { + const match = + /^(\d{1,2})\s*([C-HJ-NP-X])\s+(\d{6}(?:\.\d+)?)\s*m?\s+(\d{1,7}(?:\.\d+)?)\s*m?$/i.exec( + text, + ); + if (!match) return null; + const zone = Number(match[1]); + const letter = match[2].toUpperCase(); + const easting = Number(match[3]); + const northing = Number(match[4]); + if ( + zone < 1 || + zone > 60 || + easting < 100000 || + easting > 900000 || + northing > 10000000 || + !zoneExists(zone, letter) + ) + return null; + const range = bandRange(letter); + const asBand = utmToLatLon(zone, easting, northing, range.south < 0); + const bandFits = inBand(asBand.lat, range); + if (bandFits) return asBand; + // `S` is also how UTM is written for the southern hemisphere. Where both + // fit, the 32°N–40°N band (Tokyo, Los Angeles, the Mediterranean) is far + // likelier than 50°S–58°S, so the band wins above. + if (letter === 'S') { + const south = utmToLatLon(zone, easting, northing, true); + if (south.lat < 0 && south.lat >= -80) return south; + } + return null; +} + +/** + * The lowest northing of each band, in metres, that MGRS's 2,000 km row + * cycle is lifted past (the NGA table, as used by proj4's mgrs module). + */ +const BAND_MIN_NORTHING = { + C: 1100000, + D: 2000000, + E: 2800000, + F: 3700000, + G: 4600000, + H: 5500000, + J: 6400000, + K: 7300000, + L: 8200000, + M: 9100000, + N: 0, + P: 800000, + Q: 1700000, + R: 2600000, + S: 3500000, + T: 4400000, + U: 5300000, + V: 6200000, + W: 7000000, + X: 7900000, +}; + +/** + * MGRS as `18TWL8565011369`, `18T WL 8565011369` or `18T WL 85650 11369` + * (easting and northing the same length), or null. + */ +function parseMgrs(text) { + const match = + /^(\d{1,2})\s*([C-HJ-NP-X])\s*([A-HJ-NP-Z])([A-HJ-NP-V])(?:\s*(\d{2,10})|\s*(\d{1,5})\s+(\d{1,5}))$/i.exec( + text, + ); + if (!match) return null; + const zone = Number(match[1]); + const band = match[2].toUpperCase(); + const column = match[3].toUpperCase(); + const row = match[4].toUpperCase(); + let east = ''; + let north = ''; + if (match[5]) { + if (match[5].length % 2) return null; + east = match[5].slice(0, match[5].length / 2); + north = match[5].slice(match[5].length / 2); + } else if (match[6]) { + if (match[6].length !== match[7].length) return null; + [east, north] = [match[6], match[7]]; + } + if (zone < 1 || zone > 60 || !zoneExists(zone, band)) return null; + const precision = east.length; + const letters = text.replace(/[\d\s]/g, ''); + if (letters !== letters.toUpperCase() && (precision < 3 || /\s/.test(text))) + return null; + const columnIndex = COLUMN_SETS[(zone - 1) % 3].indexOf(column); + if (columnIndex < 0) return null; + // Rows start at A in odd zones and at F in even ones. + const rowIndex = + (ROW_LETTERS.indexOf(row) - (zone % 2 === 0 ? 5 : 0) + 20) % 20; + const scale = 10 ** (5 - precision); + // The centre of the square the digits name; a 1 m reference is its corner. + const half = precision < 5 ? scale / 2 : 0; + const easting = (columnIndex + 1) * 100000 + Number(east || 0) * scale + half; + let northing = rowIndex * 100000 + Number(north || 0) * scale + half; + while (northing < BAND_MIN_NORTHING[band]) northing += 2000000; + const range = bandRange(band); + const point = utmToLatLon(zone, easting, northing, range.south < 0); + // Slack of the square's size in degrees of latitude. + return inBand(point.lat, range, scale / 111000) ? point : null; +} + +/** + * A UTM or MGRS reference as `{ lat, lon }`, or null when the text is not + * exactly one. + * @param {string} text + */ +export function parseGridReference(text) { + if (typeof text !== 'string') return null; + const trimmed = text.trim(); + if (!trimmed || trimmed.length > 40) return null; + return parseUtm(trimmed) ?? parseMgrs(trimmed); +} diff --git a/src/search/gridReference.test.mjs b/src/search/gridReference.test.mjs new file mode 100644 index 000000000..aa111400a --- /dev/null +++ b/src/search/gridReference.test.mjs @@ -0,0 +1,395 @@ +// GRID REFERENCES AND PLUS CODES — UTM, MGRS and full Open Location Codes read +// as coordinates. Each is exact or refused, like a decimal pair: a misread +// reference flies the operator somewhere else and looks like success. +// +// The UTM and MGRS points are one per latitude band (and the zone edges) from +// pyproj and the mgrs package; the plus codes are from the Open Location Code +// project's test data (decoding.csv, validityTests.csv). +// +// Run with: npm test +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseGridReference } from './gridReference.js'; +import { parsePlusCode } from './plusCode.js'; +import { parseCoordinateQuery } from './coordinateParser.js'; + +/** Metres between two points, near enough for sub-metre checks. */ +function metres(a, b) { + const r = Math.PI / 180; + const h = + Math.sin(((b.lat - a.lat) * r) / 2) ** 2 + + Math.cos(a.lat * r) * + Math.cos(b.lat * r) * + Math.sin(((b.lon - a.lon) * r) / 2) ** 2; + return 12742000 * Math.asin(Math.sqrt(h)); +} + +// [MGRS, its latitude, its longitude, UTM, its latitude, its longitude] +const GRID = [ + [ + '18TWL8565011369', + 40.7488215, + -73.9854319, + '18T 585651 4511369', + 40.748817, + -73.985428, + ], + [ + '56HLH3490052290', + -33.8567842, + 151.2152996, + '56H 334900 6252291', + -33.856784, + 151.215297, + ], + [ + '33XWG1427883355', + 78.2232003, + 15.6266906, + '33X 514279 8683355', + 78.2232, + 15.6267, + ], + [ + '32VKN9747700830', + 60.392994, + 5.3241531, + '32V 297477 6700830', + 60.39299, + 5.32415, + ], + [ + '17MQV8185780012', + -0.1806554, + -78.4678355, + '17M 781858 9980013', + -0.180653, + -78.467834, + ], + [ + '60KXF1292941202', + -17.713404, + 178.0649977, + '60K 612930 8041203', + -17.7134, + 178.065, + ], + [ + '03WVM8047852917', + 64.5010996, + -165.4064093, + '3W 480479 7152918', + 64.5011, + -165.4064, + ], + ['31NAA6603200011', 0.0001039, 9.92e-5, '31N 166033 11', 0.0001, 0.0001], + [ + '01CDM4324728161', + -79.8999987, + -179.9000186, + '1C 443248 1128161', + -79.9, + -179.9, + ], + [ + '19FEV4500027239', + -54.7999989, + -68.2999931, + '19F 545000 3927239', + -54.8, + -68.3, + ], + [ + '54SUD1748374870', + 34.9999987, + 138.9999956, + '54S 317484 3874871', + 35.0, + 139.0, + ], + ['30UXC9988909362', 51.500002, -0.1200043, '30U 699890 5709362', 51.5, -0.12], + [ + '10JBR3890542412', + -26.7152573, + -125.6244681, + '10J 238906 7042412', + -26.7152593, + -125.6244672, + ], + [ + '05RMK1662242662', + 26.6023189, + -153.8374266, + '5R 416623 2942663', + 26.6023191, + -153.8374241, + ], + [ + '31DDC8763628944', + -70.046176, + 2.6753849, + '31D 487636 2228945', + -70.0461753, + 2.6753768, + ], + [ + '50LNP6584960983', + -10.3033721, + 117.601397, + '50L 565849 8860983', + -10.3033722, + 117.6013945, + ], + [ + '14EMV6706624140', + -59.3202819, + -99.5786192, + '14E 467066 3424141', + -59.3202803, + -99.5786205, + ], + [ + '57QYF1413419747', + 22.7716198, + 161.0856759, + '57Q 714135 2519747', + 22.7716153, + 161.0856775, + ], + [ + '24PXB9668711309', + 14.5677772, + -37.1743636, + '24P 696687 1611310', + 14.5677806, + -37.1743652, + ], + [ + '30GTV9870806681', + -41.4662188, + -5.4104109, + '30G 298709 5406682', + -41.4662184, + -5.4104096, + ], + [ + '60XWU3439017795', + 83.8999979, + 179.899971, + '60X 534391 9317796', + 83.9, + 179.9, + ], + ['32VJH3227421798', 55.9999999, 3.1000066, '32V 132274 6221799', 56.0, 3.1], + [ + '60RWP4163073757', + 25.9820077, + 177.4159163, + '60R 541631 2873757', + 25.9820033, + 177.415919, + ], + [ + '60VWL2412126400', + 58.8767223, + 177.4183599, + '60V 524121 6526400', + 58.876719, + 177.4183593, + ], + [ + '60UUD2978050375', + 52.7763309, + 174.4763915, + '60U 329781 5850376', + 52.7763332, + 174.476393, + ], + [ + '32GKT8210286690', + -42.5414587, + 6.3464153, + '32G 282102 5286690', + -42.5414631, + 6.346413, + ], +]; + +test('MGRS and UTM references read to within a metre in every latitude band', () => { + for (const [mgrs, mgrsLat, mgrsLon, utm, utmLat, utmLon] of GRID) { + const fromMgrs = parseGridReference(mgrs); + assert.ok(fromMgrs, mgrs); + assert.ok(metres(fromMgrs, { lat: mgrsLat, lon: mgrsLon }) < 1, mgrs); + const fromUtm = parseGridReference(utm); + assert.ok(fromUtm, utm); + assert.ok(metres(fromUtm, { lat: utmLat, lon: utmLon }) < 1, utm); + } +}); + +test('MGRS reads spaced, unspaced and at every precision', () => { + const times = { lat: 40.74882, lon: -73.98543 }; + for (const text of [ + '18TWL8565011369', + '18T WL 8565011369', + '18T WL 85650 11369', + '18twl8565011369', + ]) + assert.ok(metres(parseGridReference(text), times) < 1, text); + // Coarser references name the centre of their square. + assert.ok(metres(parseGridReference('18TWL856113'), times) < 71, '100 m'); + assert.ok(metres(parseGridReference('18TWL8511'), times) < 710, '1 km'); + assert.ok(metres(parseGridReference('18TWL81'), times) < 7100, '10 km'); + // A square with no digits is not enough to go on. + assert.equal(parseGridReference('18TWL'), null); +}); + +test('a UTM S is the 32°N–40°N band where it fits, else the southern hemisphere', () => { + const tokyo = parseGridReference('54S 383000 3950000'); + assert.ok( + tokyo.lat > 35 && tokyo.lat < 36 && tokyo.lon > 139 && tokyo.lon < 140, + ); + const sydney = parseGridReference('56S 334900 6252291'); + assert.ok(metres(sydney, { lat: -33.856784, lon: 151.215297 }) < 1); +}); + +test('malformed grid references are refused', () => { + for (const text of [ + '18TWL856501136', // odd digit count + '18T WL 8565 11369', // easting and northing of different lengths + '18IWL8565011369', // no band I + '18TIL8565011369', // no column I + '18TAL8565011369', // column A is not in zone 18's set + '61T WL 85650 11369', // no zone 61 + '0T WL 85650 11369', + '18Z WL 85650 11369', // polar bands are UPS, not UTM + '18A 585651 4511369', + '18T 58565 4511369', // a five-digit easting + '18T 585651 4511369 extra', + '18T WL 85650 11369 N', + 'WL 85650 11369', + '18T', + 'ATL', + // Ordinary text that spells a square in lower case. + '1 jan', + '7 feb', + '3 usa', + '1 jan 2023', + '4 cat 12', + '1the12', + '60 jun 202311', + '18t wl 85650 11369', + // Zones Svalbard does not use. + '32X 500000 8700000', + '34X NG 12 34', + '36XNG1234', + ]) + assert.equal(parseGridReference(text), null, text); +}); + +// [code, latitude, longitude] of each code's centre. +const PLUS_CODES = [ + ['7FG49Q00+', 20.375, 2.775], + ['7FG49QCJ+2V', 20.370062500000003, 2.7821875], + ['7FG49QCJ+2VX', 20.3701125, 2.782234375], + ['7FG49QCJ+2VXGJ', 20.370113500000002, 2.7822353515650002], + ['CR4389W6+MV36X2V', 72.34663418, 141.3621622924805], + ['4V44CC8J+XR', -47.5825625, 162.4320625], + ['7G2394VR+3RXCXV', 10.392739899999999, 21.1421003417965], + ['94GG6QPW+', 60.23625, -129.20375], + ['CP9C0000+', 77.5, 108.5], + ['549QX497+9X', -22.0315625, -124.8850625], + ['979V23X2+V97C6Q', 57.0496617, -62.949092041015504], + ['7G6MCJCM+58', 14.4204375, 33.6333125], + ['7VHJGH8G+', 21.51625, 172.57625], + ['423726P5+P72', -48.963237500000005, -174.791859375], + ['2JH70000+', -78.5, 65.5], + ['58P6PP00+', -15.275, -55.275], + ['2Q3P6CPJ+Q3H7HQ7', -88.76306733999999, 134.430234069824], + ['9R000000+', 60.0, 150.0], + ['6FPW3600+', 4.074999999999999, 18.225], + ['C55GR473+C5732', 73.8135255, -109.89708496093749], + ['CV25MQ00+', 70.67500000000001, 163.775], + ['4J86FVGW+9449', -43.5241175, 64.89533984375], + ['8V2H837Q+44', 30.3128125, 171.08781249999998], + ['C8C35800+', 78.17500000000001, -58.675], + ['62M5653J+Q3', 3.2044375, -176.8198125], + ['8H8VW72V+9GXV5', 36.9009955, 57.2938583984375], +]; + +test('full plus codes read to the centre of their area', () => { + for (const [code, lat, lon] of PLUS_CODES) { + const point = parsePlusCode(code); + assert.ok(point, code); + assert.ok( + Math.abs(point.lat - lat) < 1e-9 && Math.abs(point.lon - lon) < 1e-9, + code, + ); + } + assert.deepEqual( + parsePlusCode(' 849vcwc8+r9 '), + parsePlusCode('849VCWC8+R9'), + ); +}); + +// [code, isValid, isShort, isFull] +const VALIDITY = [ + ['8FWC2345+G6', 'true', 'false', 'true'], + ['8FWC2345+G6G', 'true', 'false', 'true'], + ['8fwc2345+', 'true', 'false', 'true'], + ['8FWCX400+', 'true', 'false', 'true'], + ['84000000+', 'true', 'false', 'true'], + ['WC2345+G6g', 'true', 'true', 'false'], + ['2345+G6', 'true', 'true', 'false'], + ['45+G6', 'true', 'true', 'false'], + ['+G6', 'true', 'true', 'false'], + ['G+', 'false', 'false', 'false'], + ['+', 'false', 'false', 'false'], + ['8FWC2345+G', 'false', 'false', 'false'], + ['8FWC2_45+G6', 'false', 'false', 'false'], + ['8FWC2\u03b745+G6', 'false', 'false', 'false'], + ['8FWC2345+G6+', 'false', 'false', 'false'], + ['8FWC2345G6+', 'false', 'false', 'false'], + ['8FWC2300+G6', 'false', 'false', 'false'], + ['WC2300+G6g', 'false', 'false', 'false'], + ['WC2345+G', 'false', 'false', 'false'], + ['WC2300+', 'false', 'false', 'false'], + ['84900000+', 'false', 'false', 'false'], + ['849VGJQF+VX7QR3J', 'true', 'false', 'true'], + ['849VGJQF+VX7QR3U', 'false', 'false', 'false'], + ['849VGJQF+VX7QR3JW', 'true', 'false', 'true'], + ['849VGJQF+VX7QR3JU', 'false', 'false', 'false'], +]; + +test('only valid full plus codes are read; short and invalid ones are refused', () => { + for (const [code, , , isFull] of VALIDITY) + assert.equal(parsePlusCode(code) !== null, isFull === 'true', code); +}); + +test('the search box reads degrees-minutes-seconds, grid references and plus codes', () => { + const near = (query, lat, lon, within) => { + const point = parseCoordinateQuery(query); + assert.ok(point, query); + assert.ok(metres(point, { lat, lon }) < within, query); + assert.match(point.label, /° [NS], .*° [EW]$/, query); + }; + near('40°26\'46"N, 79°58\'56"W', 40.446111, -79.982222, 1); + near('40° 26′ 46″ N 79° 58′ 56″ W', 40.446111, -79.982222, 1); + near("N 40°26.767' W 79°58.933'", 40.446117, -79.982217, 1); + near('-33°51\'24", 151°12\'55"', -33.856667, 151.215278, 1); + near('33UXP0500444998', 48.249493, 16.414495, 1); + near('18T 585651 4511369', 40.748817, -73.985428, 1); + near('849VCWC8+R9', 37.4220625, -122.0840625, 1); + for (const query of [ + '40°26\'46"N', // one component + '40°60\'0"N, 79°0\'0"W', // 60 minutes + '40°26\'60"N, 79°0\'0"W', // 60 seconds + '40°26.5\'46"N, 79°0\'0"W', // a decimal before the last number + '-40°26\'46"N, 79°0\'0"W', // a sign and a letter + 'N 40°26\'46"N, 79°0\'0"W', // two letters + '91°0\'0"N, 79°0\'0"W', // out of range + '40°26\'46"N, 40°26\'46"S', // both latitude + 'CWC8+R9', // a short plus code needs a place + 'CWC8+R9 Mountain View', + ]) + assert.equal(parseCoordinateQuery(query), null, query); +}); diff --git a/src/search/plusCode.js b/src/search/plusCode.js new file mode 100644 index 000000000..368536430 --- /dev/null +++ b/src/search/plusCode.js @@ -0,0 +1,90 @@ +/** + * Full Open Location Codes ("plus codes", `849VCWC8+R9`) to the centre of + * their area, for the search box. Implements the decoding half of the Open + * Location Code specification (github.com/google/open-location-code). Short + * codes (`CWC8+R9 Mountain View`) need a reference place and decline, as does + * anything that is not exactly one valid full code. + */ + +const ALPHABET = '23456789CFGHJMPQRVWX'; +const SEPARATOR = '+'; +const SEPARATOR_POSITION = 8; +const PADDING = '0'; +const PAIR_LENGTH = 10; +const GRID_COLUMNS = 4; +const GRID_ROWS = 5; +const MAX_LENGTH = 15; + +/** Whether `code` is a valid full code (the specification's isFull). */ +function isFullCode(code) { + const separator = code.indexOf(SEPARATOR); + if (separator < 0 || separator !== code.lastIndexOf(SEPARATOR)) return false; + if ( + separator !== SEPARATOR_POSITION || + code.length === SEPARATOR_POSITION + 2 + ) + return false; + const padding = code.indexOf(PADDING); + if (padding >= 0) { + // Padding only before the separator, in an even count from an even place, + // and nothing after the separator. + if (padding === 0 || padding % 2) return false; + const run = /0+/.exec(code)[0]; + if ( + run.length % 2 || + run.length !== code.split('').filter((c) => c === PADDING).length + ) + return false; + if (padding + run.length !== separator) return false; + if (code.length > separator + 1) return false; + } + for (const character of code) + if ( + character !== SEPARATOR && + character !== PADDING && + !ALPHABET.includes(character) + ) + return false; + // The first two characters keep latitude below 90 and longitude below 180. + if (ALPHABET.indexOf(code[0]) * 20 >= 180) return false; + if (ALPHABET.indexOf(code[1]) * 20 >= 360) return false; + return true; +} + +/** + * The centre of a full plus code as `{ lat, lon }`, or null. + * @param {string} text + */ +export function parsePlusCode(text) { + if (typeof text !== 'string') return null; + const code = text.trim().toUpperCase(); + if (!code || code.length > 32 || !isFullCode(code)) return null; + const digits = code + .replace(SEPARATOR, '') + .replace(/0+$/, '') + .slice(0, MAX_LENGTH); + let south = -90; + let west = -180; + let latStep = 400; + let lonStep = 400; + // Pairs: alternating latitude and longitude digits in base 20. + for (let i = 0; i < Math.min(digits.length, PAIR_LENGTH); i += 2) { + latStep /= 20; + lonStep /= 20; + south += ALPHABET.indexOf(digits[i]) * latStep; + if (i + 1 < digits.length) + west += ALPHABET.indexOf(digits[i + 1]) * lonStep; + } + // Beyond ten digits, each one picks a cell of a 4 × 5 grid. + for (let i = PAIR_LENGTH; i < digits.length; i += 1) { + latStep /= GRID_ROWS; + lonStep /= GRID_COLUMNS; + const index = ALPHABET.indexOf(digits[i]); + south += Math.floor(index / GRID_COLUMNS) * latStep; + west += (index % GRID_COLUMNS) * lonStep; + } + const lat = Math.min(90, south + latStep / 2); + let lon = west + lonStep / 2; + if (lon >= 180) lon -= 360; + return { lat, lon }; +}