In this section
- Single-Line Diagram (SLD) Sandbox V9 8 geodesy · gridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js lines 8922–9047
- Substation Intelligence V9 63 geodesy · gridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js lines 1–574
Single-Line Diagram (SLD) Sandbox V9 8
A JavaScript file in the cartridges folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.
Set aside from the main view: 99% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9877 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
- sha256 d8b2e61b4b14f7af456a2c0c1721efc4d0bb2e9d43fbadc8cac6075b8465eccb
- target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js · lines 8922–9047 of 9047 · version 2026-11-18 00:26 (continued from section 370) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)
- What it does
- It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 276 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
- Inputs & outputs
- In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
- What it achieves
- It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/cartridges · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
- Defines here
- ready, go, fit, schedule
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-sld-sandbox-v9-8.js:8922-9047 · blob 4336ae8ea8d1eafcf57a97906bbb6c661f9c8318 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
const p = f.properties;
const [a, b] = f.geometry.coordinates;
return {
link: p.link, bmrs: p.bmrs_code, gb_converter: p.gb_converter, far_converter: p.far_converter,
span_km: p.straight_line_km,
geometry_kind: p.geometry_kind,
route_factor: p.route_factor ?? null,
known_submarine_cable_km: p.known_submarine_cable_km ?? null,
net_mwh: p.net_mwh ?? null,
net_direction: p.net_direction ?? null,
label: label(p, km),
ends: [
measureEnd('gb', a[0], a[1], km, subs),
measureEnd('far', b[0], b[1], km, []),
],
};
});
state.loaded = true;
state.search_km = km;
paint(map, geojson);
try { arrive(map, geojson); }
catch (error) {
state.error = 'interconnector arrival threw: ' + String(error && error.message || error);
if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_ARRIVAL_THREW', null);
}
}
function ready(map) {
if (!map) return;
if (map.loaded && map.loaded()) { boot(map); return; }
let started = false;
const go = () => { if (!started) { started = true; boot(map); } };
map.once('load', go);
map.once('idle', go);
const settle = setInterval(() => {
if (map.loaded && map.loaded()) { clearInterval(settle); go(); }
}, 500);
setTimeout(() => clearInterval(settle), 60000);
}
const timer = setInterval(() => {
const map = window.__GRIDATLAS_V9_MAP__;
if (!map) return;
clearInterval(timer);
try { ready(map); }
catch (error) {
state.error = String(error && error.message || error);
if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_MODULE_THREW', null);
}
}, 400);
setTimeout(() => {
clearInterval(timer);
/* Ninety seconds and no map ever appeared on the window. The module never
got as far as loading, so nothing below it can speak for it. */
if (!state.loaded && isInterconnectorArrival()) answer(false, 'NO_MAP_WITHIN_90S', null);
}, 90000);
})();
/** Keep ordinary feature cards clear of the fixed search/menu controls.
* Project cards have their own draggable bar and mobile sheet; preserve it.
*/
(() => {
let queued = false;
const ordinaryStyles = new WeakMap();
function fit() {
queued = false;
const container = window.__GRIDATLAS_V9_MAP__?.getContainer();
if (!container) return;
const map = container.getBoundingClientRect();
const menu = document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect();
const search = document.querySelector('.search-bar-wrapper')?.getBoundingClientRect();
for (const popup of container.querySelectorAll('.maplibregl-popup')) {
const content = popup.querySelector('.maplibregl-popup-content');
const close = popup.querySelector('.maplibregl-popup-close-button');
if (!content || !close) continue;
if (popup.querySelector('.gridatlas-card-bar') || popup.classList.contains('gridatlas-sheet')) {
// Arrival cards gain their project bar asynchronously. Give back only
// styles we still own; do not leave a second decorated close button or
// an extra 44px header above the project's own controls.
for (const saved of ordinaryStyles.get(content) || []) {
if (saved.element.style.getPropertyValue(saved.property) === saved.written) {
if (saved.previous) saved.element.style.setProperty(saved.property, saved.previous, saved.priority);
else saved.element.style.removeProperty(saved.property);
}
}
ordinaryStyles.delete(content);
continue;
}
if (!ordinaryStyles.has(content)) {
ordinaryStyles.set(content, [
...['min-width', 'min-height', 'color', 'background', 'border'].map(property => ({element: close, property})),
{element: content, property: 'padding-top'}
].map(saved => ({...saved, previous: saved.element.style.getPropertyValue(saved.property),
priority: saved.element.style.getPropertyPriority(saved.property)})));
}
// A normal feature popup's close control otherwise measures only 20px.
close.style.minWidth = '44px';
close.style.minHeight = '44px';
close.style.color = '#bfe9ee';
close.style.background = '#0a1a1d';
close.style.border = '1px solid #2f6f75';
content.style.paddingTop = '44px';
for (const saved of ordinaryStyles.get(content)) saved.written = saved.element.style.getPropertyValue(saved.property);
const top = Math.max(map.top, menu?.bottom || 0, search?.bottom || 0) + 8;
const bottom = Math.min(map.bottom, window.innerHeight) - 8;
content.style.setProperty('max-height', Math.max(44, bottom - top - 20) + 'px', 'important');
const rect = popup.getBoundingClientRect();
const left = Math.max(map.left + 8, Math.min(rect.left, map.right - rect.width - 8));
const y = Math.max(top, Math.min(rect.top, bottom - rect.height));
if (rect.top < top || rect.bottom > bottom || rect.left < map.left || rect.right > map.right) {
popup.classList.add('gridatlas-free');
popup.style.setProperty('--gx', left + 'px');
popup.style.setProperty('--gy', y + 'px');
}
}
}
function schedule() {
if (!queued) { queued = true; requestAnimationFrame(fit); }
}
// Observe content insertion, not our own style writes.
new MutationObserver(schedule).observe(document.documentElement, {childList: true, subtree: true});
window.addEventListener('resize', schedule);
window.visualViewport?.addEventListener('resize', schedule);
schedule();
})();Substation Intelligence V9 63
A JavaScript file in the cartridges folder of GridAtlas that maps elizabeth line, using haversine and SHA-256 and uses data from the Ventus Grid Engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.
Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.
Evidence
- line 4 comment: * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit
geodesygridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js · lines 1–574 of 8609 · version 2026-11-18 00:26 · pattern switchOn (shared by 4 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 4 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Map Removal Test (gridatlas); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Genome Workflow (ventus-grid-engine).
- What it achieves
- It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine. Checked by Map Removal Test.
- Application
- gridatlas · atlas/cartridges · script
- VEDIC
- SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
- Used by
- linked from Code Generator — Substation Finder Page (link), referenced by Map Removal Test (new URL import.meta.url), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL), mentioned in Standalone (comment link)
- Produces
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear, zoneDrawUndo, toggleZoneDrawMode, _zoneDrawNearVertex, _zoneDrawEdgeDots, _zoneDrawNearEdgeDot, _zoneDrawOnClick, _zoneDrawOnMouseDown, _zoneDrawOnMouseMove, _zoneDrawOnMouseUp, openPopup, closeActivePopup, toggleCurtain, getRadiusValue, validateRadiusInput, updateMeasureDisplay, updateMeasureLayers, clearMeasure, undoLastMeasurePoint
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-574 · blob c6f9632fdb6e803baae03a54a542fe508431d153 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* substation-intelligence-v9-63, generation 202609060259 (UTC).
*
* ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit
* this file: edit a part and rebuild under a new generation. Each part is
* hashed in manifests/202609060259-substation-intelligence-v9-63-parts.json.
*
* carried_shell_script atlas/parts/202609060254-ventus-corev8engine-polyzone-grabbable.js
* module atlas/modules/202609011950-geodesy.js
* module atlas/modules/202609012245-network-topology.js
* module atlas/modules/202609012245-electrical-distance.js
* module atlas/modules/202609012250-rating-envelope.js
* module atlas/modules/202609020015-injection-response.js
* module atlas/modules/202609012345-planned-change.js
* module atlas/modules/202609012350-owner-boundary.js
* module atlas/modules/202609030137-pinned-products.js
* module atlas/modules/202609030157-version-ledger.js
* module atlas/modules/202609030205-corridor-estimate.js
* module atlas/modules/202609031958-menu-bar.js
* module atlas/modules/202609032220-arrival-tidy.js
* module atlas/modules/202609030048-pipeline-news-layers.js
* module atlas/modules/202609040400-sld-styles.js
* module atlas/modules/202609051624-teleprint-controls.js
* part atlas/parts/202609012350-substation-intelligence-body.js
*/
'use strict';
window.initVentusMap = function({ config, center, zoom }) {
if (typeof maplibregl === 'undefined') {
document.getElementById('fatal-banner').style.display = 'block';
throw new Error('CRITICAL: MapLibre failed to load.');
}
// ── Utilities ────────────────────────────────────────────────────────────────
function deepFreeze(obj) {
Object.keys(obj).forEach(prop => {
if (typeof obj[prop] === 'object' && obj[prop] !== null) deepFreeze(obj[prop]);
});
return Object.freeze(obj);
}
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
}
function normalizeStatus(status) {
return String(status ?? '').trim().toLowerCase();
}
function fmt(n, decimals) {
return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}
// ── Earth model ───────────────────────────────────────────────────────────────
const EARTH_RADIUS_KM = 6378.137;
const MAX_RADIUS_KM = Math.PI * EARTH_RADIUS_KM; // 20037.508 km
// ── V5.1: Named constants ────────────────────────────────────────────────────
const DEG_TO_RAD = Math.PI / 180;
const HIT_RADIUS_VERTEX_PX = 22;
const HIT_RADIUS_EDGE_PX = 16;
/* How much clear screen space an add-a-point dot needs beyond a corner's
own grab radius before it is allowed to exist on that edge. */
const EDGE_DOT_CLEARANCE_PX = 10;
const CLICK_DEBOUNCE_MS = 220;
const HOVER_THROTTLE_MS = 100;
const POPUP_MAX_WIDTH = '300px';
const ZONE_DRAW_VERTICES = 24;
const ZONE_DRAW_DEFAULT_KM = 0.337;
function haversine(lon1, lat1, lon2, lat2) {
const R = EARTH_RADIUS_KM, r = Math.PI / 180;
const dLat = (lat2 - lat1) * r, dLon = (lon2 - lon1) * r;
const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
// ── Config Loading ────────────────────────────────────────────────────────────
const GRID_CONFIG = deepFreeze(config);
const RUNTIME_STATE = {};
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
});
});
const layerConfigById = new Map(
GRID_CONFIG.flatMap(g => g.layers).map(l => [l.id, l])
);
// Removed naei_co2 from here so it gets its own dedicated source
const REPD_IDS = ['solar','solar_operational','solar_roof','wind','wind_onshore_operational','wind_offshore_operational','bess','bess_operational','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes'];
const TRANSIT_IDS = ['elizabeth','lu','dlr','metro','tram','hs2'];
const TRANSIT_SOURCE_MAP = { 'elizabeth':'src-elizabeth','lu':'src-lu','dlr':'src-metros','metro':'src-metros','tram':'src-metros','hs2':'src-hs2' };
const TRANSIT_URLS = { 'src-elizabeth':'/elizabeth_line.geojson','src-lu':'/london_underground.geojson','src-metros':'/uk_metros_trams.geojson','src-hs2':'/hs2.geojson' };
const SEARCH_THRESHOLD = {
'solar':50,'solar_roof':0.5,'wind':50,'bess':50,'biomass':50,
'tidal':10,'hydrogen':10,'hydro':10,'flywheel':1,'act':10,'geothermal':1,'caes':1
};
const TECH_TERMS = new Map([
['solar','solar farm'],['solar_roof','rooftop solar'],['wind','wind farm'],
['bess','battery storage'],['biomass','biomass plant'],['tidal','tidal energy'],
['hydrogen','hydrogen plant'],['hydro','hydro power'],['flywheel','flywheel storage'],
['act','advanced conversion energy'],['geothermal','geothermal energy'],['caes','compressed air energy storage']
]);
const TECH_COLOURS = new Map([
['solar','#ffff00'],['solar_roof','#ffcc00'],['wind','#00ffff'],['bess','#ffae00'],
['biomass','#39ff14'],['tidal','#00bfff'],['hydrogen','#ffffff'],['hydro','#00aaff'],
['flywheel','#ff69b4'],['act','#ff6600'],['geothermal','#ff3300'],['caes','#88aaff']
]);
const STATUS_COLOURS = {
'operational':'#00ff88','under construction':'#ffcc00','awaiting construction':'#ffaa00',
'consented':'#ff8800','planning permission granted':'#ff8800','planning approved':'#ff8800',
'application submitted':'#8888ff','pre-construction':'#aaaaff'
};
let statusMode = false;
let radiusMode = false;
let radiusMarker = null;
let radiusCenter = null;
let radiusAreaMode = false;
let radiusAreaMarker = null;
let radiusAreaCenter = null;
// ── ZONE DRAW STATE ───────────────────────────────────────────────────────────
const ZONE_DRAW_MAX_KM = MAX_RADIUS_KM;
let zoneDrawMode = false;
let zoneDrawPoints = [];
let zoneDrawDragging = false;
let zoneDrawDragIdx = -1;
let zoneDrawJustDragged = false;
let _zoneDrawCollapsed = false;
function _zoneDrawGetRadius() {
const input = document.getElementById('zonedraw-radius-input');
if (!input) return ZONE_DRAW_DEFAULT_KM;
const v = parseFloat(input.value);
if (isNaN(v) || v <= 0) return ZONE_DRAW_DEFAULT_KM;
if (v > ZONE_DRAW_MAX_KM) return ZONE_DRAW_MAX_KM;
return v;
}
function _zoneDrawCirclePoints(lon, lat, radiusKm, n) {
const R = EARTH_RADIUS_KM, DEG = Math.PI / 180;
const ad = radiusKm / R;
const lat1 = lat * DEG;
return Array.from({ length: n }, (_, i) => {
const b = (i / n) * 2 * Math.PI;
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(ad) + Math.cos(lat1) * Math.sin(ad) * Math.cos(b));
const lon2 = lon * DEG + Math.atan2(Math.sin(b) * Math.sin(ad) * Math.cos(lat1), Math.cos(ad) - Math.sin(lat1) * Math.sin(lat2));
return [lon2 / DEG, lat2 / DEG];
});
}
function _zoneDrawCalcArea(pts) {
if (pts.length < 3) return { areaKm2: 0, areaHa: 0, areaAc: 0, areaMi2: 0, areaM2: 0, perimKm: 0, pitches: 0 };
let area = 0;
const R = EARTH_RADIUS_KM;
for (let i = 0; i < pts.length; i++) {
const j = (i + 1) % pts.length;
const xi = pts[i][0] * Math.PI / 180, yi = pts[i][1] * Math.PI / 180;
const xj = pts[j][0] * Math.PI / 180, yj = pts[j][1] * Math.PI / 180;
area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
}
const areaKm2 = Math.abs(area) * R * R / 2;
let perimKm = 0;
for (let i = 0; i < pts.length; i++) perimKm += haversine(pts[i][0], pts[i][1], pts[(i+1)%pts.length][0], pts[(i+1)%pts.length][1]);
const areaM2 = areaKm2 * 1e6;
return { areaKm2, areaHa: areaM2 / 10000, areaAc: areaM2 / 4046.85642, areaMi2: areaKm2 * 0.386102, areaM2, perimKm, pitches: areaM2 / 7140 };
}
function _zoneDrawUpdateLayers(dragOnly) {
if (!map.getSource('src-zonedraw-fill')) return;
const n = zoneDrawPoints.length;
if (n < 3) {
['fill','line','points'].forEach(s => map.getSource(`src-zonedraw-${s}`).setData({ type: 'FeatureCollection', features: [] }));
return;
}
const ring = [...zoneDrawPoints, zoneDrawPoints[0]];
map.getSource('src-zonedraw-fill').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] } }] });
map.getSource('src-zonedraw-line').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'LineString', coordinates: ring } }] });
if (dragOnly) {
map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features:
zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }))
});
} else {
const vFeatures = zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }));
const mFeatures = [];
zoneDrawPoints.forEach((c, i) => {
/* Same rule as the hit test, so a dot is never drawn where it
cannot be pressed and never pressable where it is not drawn. */
_zoneDrawEdgeDots(i).forEach(d => {
mFeatures.push({ type: 'Feature', properties: { kind: 'mid', edgeIdx: i, t: d.t }, geometry: { type: 'Point', coordinates: d.dot } });
});
});
map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features: [...vFeatures, ...mFeatures] });
}
}
let _zoneDrawPopupRaf = null;
function _zoneDrawShowPopup() {
if (zoneDrawPoints.length < 3) return;
const { areaKm2, areaHa, areaAc, areaMi2, areaM2, perimKm, pitches } = _zoneDrawCalcArea(zoneDrawPoints);
const centLon = zoneDrawPoints.reduce((s, p) => s + p[0], 0) / zoneDrawPoints.length;
const centLat = zoneDrawPoints.reduce((s, p) => s + p[1], 0) / zoneDrawPoints.length;
if (_zoneDrawCollapsed) {
openPopup([centLon, centLat], `
<div onclick="window._zdExpand&&window._zdExpand()" style="font-family:monospace;background:#000;padding:5px 10px;border:1px solid #ff6600;border-radius:4px;cursor:pointer;color:#ff6600;font-size:11px;white-space:nowrap;">
◉ ${fmt(areaKm2,3)} km² · ⚽ ${fmt(pitches,0)} pitches ▾
</div>`);
window._zdExpand = () => { _zoneDrawCollapsed = false; _zoneDrawShowPopup(); };
} else {
openPopup([centLon, centLat], `
<div style="font-family:monospace;background:#000;padding:10px 12px;border:1px solid #ff6600;border-radius:4px;min-width:230px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
<b style="color:#ff6600;font-size:13px;">◉ Zone Draw</b>
<span onclick="window._zdCollapse&&window._zdCollapse()" style="color:#555;font-size:12px;cursor:pointer;padding:0 4px;user-select:none;" title="Collapse">▴ hide</span>
</div>
<div style="color:#ffae00;font-size:13px;margin-bottom:10px;">⚽ ${fmt(pitches,1)} football pitches</div>
<div style="display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:12px;">
<span style="color:#888;">Square Metres</span><span style="color:#fff;">${fmt(areaM2,0)}</span>
<span style="color:#888;">Hectares</span><span style="color:#fff;">${fmt(areaHa,2)}</span>
<span style="color:#888;">Acres</span><span style="color:#fff;">${fmt(areaAc,2)}</span>
<span style="color:#888;">Square Kilometres</span><span style="color:#fff;">${fmt(areaKm2,4)}</span>
<span style="color:#888;">Square Miles</span><span style="color:#fff;">${fmt(areaMi2,3)}</span>
<span style="color:#888;">Perimeter</span><span style="color:#fff;">${fmt(perimKm,2)} km</span>
</div>
<div style="color:#555;font-size:10px;margin-top:8px;line-height:1.4;">
<b style="color:#ff6600;">HOW TO USE:</b><br>
• <b>Drag orange dots</b> to reshape polygon<br>
• <b>Click light dots</b> on edges to add points<br>
• <b>Undo button</b> in top-left removes last point<br>
• <b>Click elsewhere</b> to start new zone
</div>
</div>`);
window._zdCollapse = () => { _zoneDrawCollapsed = true; _zoneDrawShowPopup(); };
}
}
function _zoneDrawShowPopupDebounced() {
if (_zoneDrawPopupRaf) return;
_zoneDrawPopupRaf = requestAnimationFrame(() => { _zoneDrawPopupRaf = null; _zoneDrawShowPopup(); });
}
function _zoneDrawClear() {
zoneDrawPoints = [];
zoneDrawDragging = false;
zoneDrawDragIdx = -1;
zoneDrawJustDragged = false;
_zoneDrawCollapsed = false;
window._zdExpand = null;
window._zdCollapse = null;
closeActivePopup();
_zoneDrawUpdateLayers(false);
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'none';
}
function zoneDrawUndo() {
if (zoneDrawPoints.length <= 3) { _zoneDrawClear(); return; }
zoneDrawPoints.pop();
_zoneDrawUpdateLayers(false);
_zoneDrawShowPopup();
}
function toggleZoneDrawMode() {
zoneDrawMode = !zoneDrawMode;
const btn = document.getElementById('btn-zonedraw');
if (btn) { btn.classList.toggle('active', zoneDrawMode); btn.setAttribute('aria-pressed', zoneDrawMode); }
map.getCanvas().style.cursor = zoneDrawMode ? 'crosshair' : '';
if (zoneDrawMode) {
if (radiusMode) toggleRadiusMode();
if (radiusAreaMode) toggleRadiusAreaMode();
if (measureMode) toggleMeasureMode();
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'block';
} else {
_zoneDrawClear();
}
}
function _zoneDrawNearVertex(px) {
for (let i = 0; i < zoneDrawPoints.length; i++) {
const vpx = map.project(zoneDrawPoints[i]);
const dx = px.x - vpx.x, dy = px.y - vpx.y;
if (Math.sqrt(dx*dx + dy*dy) < HIT_RADIUS_VERTEX_PX) return i;
}
return -1;
}
/* An edge is only long enough to carry add-a-point dots when its ends are
far enough apart on screen. A 24-gon zoomed out puts three dots inside
the corner's own hit radius, so the dots crowd out the corners and the
polygon becomes uneditable. One rule, used by both the hit test and the
drawing, so what you can press is always what you can see. */
function _zoneDrawEdgeDots(i) {
const j = (i + 1) % zoneDrawPoints.length;
const a = zoneDrawPoints[i], b = zoneDrawPoints[j];
const apx = map.project(a), bpx = map.project(b);
const lenPx = Math.hypot(bpx.x - apx.x, bpx.y - apx.y);
const clearance = HIT_RADIUS_VERTEX_PX + EDGE_DOT_CLEARANCE_PX;
const out = [];
for (const t of [0.33, 0.5, 0.66]) {
if (t * lenPx < clearance || (1 - t) * lenPx < clearance) continue;
out.push({ insertIdx: j, t, dot: [a[0]+(b[0]-a[0])*t, a[1]+(b[1]-a[1])*t] });
}
return out;
}
function _zoneDrawNearEdgeDot(px) {
for (let i = 0; i < zoneDrawPoints.length; i++) {
for (const d of _zoneDrawEdgeDots(i)) {
const dpx = map.project(d.dot);
const dx = px.x - dpx.x, dy = px.y - dpx.y;
if (Math.sqrt(dx*dx + dy*dy) < HIT_RADIUS_EDGE_PX) return { insertIdx: d.insertIdx, dot: d.dot };
}
}
return null;
}
function _zoneDrawOnClick(e) {
if (zoneDrawDragging) return;
if (zoneDrawJustDragged) { zoneDrawJustDragged = false; return; }
const lon = e.lngLat.lng, lat = e.lngLat.lat;
if (zoneDrawPoints.length === 0) {
const km = _zoneDrawGetRadius();
zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
_zoneDrawCollapsed = false;
const mpp = (km * 2000) / (window.innerWidth * 0.6);
const lat1 = lat * Math.PI / 180;
const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
const clampedZoom = Math.max(8, Math.min(19, targetZoom));
map.easeTo({ center: [lon, lat], zoom: clampedZoom, duration: 600 });
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
const px = map.project([lon, lat]);
if (_zoneDrawNearVertex(px) >= 0) return;
const edgeHit = _zoneDrawNearEdgeDot(px);
if (edgeHit) {
zoneDrawPoints.splice(edgeHit.insertIdx, 0, [edgeHit.dot[0], edgeHit.dot[1]]);
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
const km = _zoneDrawGetRadius();
zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
_zoneDrawCollapsed = false;
const mpp = (km * 2000) / (window.innerWidth * 0.6);
const lat1 = lat * Math.PI / 180;
const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
map.easeTo({ center: [lon, lat], zoom: Math.max(8, Math.min(19, targetZoom)), duration: 600 });
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
}
function _zoneDrawOnMouseDown(e) {
if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
const px = map.project(e.lngLat);
/* A CORNER ALWAYS WINS A PRESS.
This used to test the edge dot first and return, while the hover
handler tested the vertex first. So the cursor promised a grab and
the press silently refused, which is what "cannot select the elastic
bands" was. Measured on the live map at Cleve Hill: at the drawn zoom
the nearest midpoint sits 57.7 px from a corner and all 24 corners
drag; two zoom steps out it sits 14.4 px away and none of them do.
Hover and press now ask the same question in the same order. */
const vi = _zoneDrawNearVertex(px);
if (vi < 0 && _zoneDrawNearEdgeDot(px)) return;
if (vi >= 0) {
zoneDrawDragging = true; zoneDrawDragIdx = vi;
map.dragPan.disable();
map.getCanvas().style.cursor = 'grabbing';
e.preventDefault();
}
}
function _zoneDrawOnMouseMove(e) {
if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
if (zoneDrawDragging && zoneDrawDragIdx >= 0) {
zoneDrawPoints[zoneDrawDragIdx] = [e.lngLat.lng, e.lngLat.lat];
_zoneDrawUpdateLayers(true);
_zoneDrawShowPopupDebounced();
return;
}
const px = map.project(e.lngLat);
const vi = _zoneDrawNearVertex(px);
const edgeHit = vi < 0 ? _zoneDrawNearEdgeDot(px) : null;
map.getCanvas().style.cursor = vi >= 0 ? 'grab' : (edgeHit ? 'copy' : 'crosshair');
}
function _zoneDrawOnMouseUp() {
if (!zoneDrawDragging) return;
zoneDrawDragging = false;
zoneDrawDragIdx = -1;
zoneDrawJustDragged = true;
map.dragPan.enable();
map.getCanvas().style.cursor = 'crosshair';
_zoneDrawUpdateLayers(false);
_zoneDrawShowPopup();
setTimeout(() => { zoneDrawJustDragged = false; }, 50);
}
const urlCache = {};
let globalSubsData = null;
let allREPDFeatures = [];
let searchIndex = [];
// ── Single popup instance — prevents accumulation ────────────────────────────
let activePopup = null;
function openPopup(lngLat, html, maxWidth) {
if (activePopup) { activePopup.remove(); activePopup = null; }
activePopup = new maplibregl.Popup({ maxWidth: maxWidth || POPUP_MAX_WIDTH })
.setLngLat(lngLat)
.setHTML(html)
.addTo(map);
activePopup.on('close', () => { activePopup = null; });
return activePopup;
}
function closeActivePopup() {
if (activePopup) { activePopup.remove(); activePopup = null; }
}
window._closePopupKeepShape = () => closeActivePopup();
// ── Fullscreen ───────────────────────────────────────────────────────────────
let fsActive = false;
let curtainOpen = false;
window.enterFullscreen = function() {
fsActive = true;
document.body.classList.add('fs-active');
document.documentElement.classList.add('fs-active');
document.getElementById('map-container').classList.add('is-fullscreen');
document.getElementById('btn-fullscreen').style.display = 'none';
const el = document.getElementById('map-container');
if (el.requestFullscreen) { el.requestFullscreen().catch(() => {}); }
else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); }
setTimeout(() => map.resize(), 50);
};
window.exitFullscreen = function() {
fsActive = false;
curtainOpen = false;
document.body.classList.remove('fs-active');
document.documentElement.classList.remove('fs-active');
document.getElementById('map-container').classList.remove('is-fullscreen');
document.getElementById('btn-fullscreen').style.display = '';
document.getElementById('fs-curtain').classList.remove('curtain-open');
if (document.fullscreenElement || document.webkitFullscreenElement) {
if (document.exitFullscreen) document.exitFullscreen().catch(() => {});
else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
}
setTimeout(() => map.resize(), 50);
};
function toggleCurtain() {
curtainOpen = !curtainOpen;
const curtain = document.getElementById('fs-curtain');
const tab = document.getElementById('fs-curtain-tab');
curtain.classList.toggle('curtain-open', curtainOpen);
tab.innerText = curtainOpen ? '⬆ Close' : '⬇ Layers';
}
document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && fsActive) exitFullscreen(); });
document.addEventListener('webkitfullscreenchange', () => { if (!document.webkitFullscreenElement && fsActive) exitFullscreen(); });
// ── Radius Tool ───────────────────────────────────────────────────────────────
const RADIUS_MIN = 1;
const RADIUS_MAX = MAX_RADIUS_KM;
function getRadiusValue() {
const raw = parseFloat(document.getElementById('radius-input').value);
if (isNaN(raw) || raw < RADIUS_MIN) return RADIUS_MIN;
if (raw > RADIUS_MAX) return RADIUS_MAX;
return raw;
}
function validateRadiusInput() {
const input = document.getElementById('radius-input');
const raw = parseFloat(input.value);
const invalid = isNaN(raw) || raw < RADIUS_MIN || raw > RADIUS_MAX;
input.classList.toggle('invalid', invalid);
return !invalid;
}
// ── Measure Tool ──────────────────────────────────────────────────────────────
let measureMode = false;
let measurePoints = [];
let measureClosed = false;
let _lastMouseMoveRaf = null;
function updateMeasureDisplay() {
const lineEl = document.getElementById('m-line');
const perimEl = document.getElementById('m-perim');
const areaEl = document.getElementById('m-area');
const hint = document.getElementById('m-hint');
const undoBtn = document.getElementById('btn-measure-undo');
undoBtn.style.display = (measurePoints.length > 0 && !measureClosed) ? 'inline-block' : 'none';
if (measurePoints.length < 2) {
lineEl.style.display = 'none'; perimEl.style.display = 'none'; areaEl.style.display = 'none';
hint.innerText = 'Click to add points · Double-click to close polygon';
return;
}
let totalKm = 0;
for (let i = 1; i < measurePoints.length; i++) {
totalKm += haversine(measurePoints[i-1][0], measurePoints[i-1][1], measurePoints[i][0], measurePoints[i][1]);
}
if (!measureClosed) {
lineEl.style.display = 'block'; perimEl.style.display = 'none'; areaEl.style.display = 'none';
document.getElementById('m-km').innerText = fmt(totalKm, 2);
document.getElementById('m-m').innerText = fmt(totalKm * 1000, 0);
document.getElementById('m-mi').innerText = fmt(totalKm * 0.621371, 2);
hint.innerText = 'Double-click last point to close polygon';
} else {
const closingKm = haversine(measurePoints[measurePoints.length-1][0], measurePoints[measurePoints.length-1][1], measurePoints[0][0], measurePoints[0][1]);
const perimKm = totalKm + closingKm;
let area = 0;
const R = EARTH_RADIUS_KM;
for (let i = 0; i < measurePoints.length; i++) {
const j = (i + 1) % measurePoints.length;
const xi = measurePoints[i][0] * Math.PI / 180; const yi = measurePoints[i][1] * Math.PI / 180;
const xj = measurePoints[j][0] * Math.PI / 180; const yj = measurePoints[j][1] * Math.PI / 180;
area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
}
const areaKm2 = Math.abs(area) * R * R / 2;
const areaHa = areaKm2 * 100; const areaAc = areaKm2 * 247.105;
lineEl.style.display = 'none'; perimEl.style.display = 'block'; areaEl.style.display = 'block';
document.getElementById('m-pkm').innerText = fmt(perimKm, 2); document.getElementById('m-pm').innerText = fmt(perimKm * 1000, 0);
document.getElementById('m-km2').innerText = fmt(areaKm2, 3); document.getElementById('m-ha').innerText = fmt(areaHa, 1);
document.getElementById('m-ac').innerText = fmt(areaAc, 1);
hint.innerText = 'Click 📏 Measure again to reset';
}
}
function updateMeasureLayers() {
if (!map.getSource('src-measure-line')) return;
const lineCoords = [...measurePoints];
if (measureClosed && measurePoints.length > 2) lineCoords.push(measurePoints[0]);
map.getSource('src-measure-line').setData({ type: 'FeatureCollection', features: lineCoords.length > 1 ? [{ type: 'Feature', geometry: { type: 'LineString', coordinates: lineCoords } }] : [] });
map.getSource('src-measure-fill').setData({ type: 'FeatureCollection', features: measureClosed && measurePoints.length > 2 ? [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [[...measurePoints, measurePoints[0]]] } }] : [] });
map.getSource('src-measure-points').setData({ type: 'FeatureCollection', features: measurePoints.map(c => ({ type: 'Feature', geometry: { type: 'Point', coordinates: c } })) });
}
function clearMeasure() {
measurePoints = []; measureClosed = false; updateMeasureLayers(); updateMeasureDisplay();
document.getElementById('measure-display').style.display = 'none';
}
function undoLastMeasurePoint() {
if (measurePoints.length === 0 || measureClosed) return;
measurePoints.pop(); updateMeasureLayers(); updateMeasureDisplay();
}
function toggleMeasureMode() {
measureMode = !measureMode;