GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / testcode/202609060300/atlas/cartridges

Substation Intelligence and 1 more file (part 2)

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps elizabeth line and london underground, using haversine and SHA-256, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

700 lines of JavaScript from globalgrid2050, in 2 files. Topic: Grid network and substations. Section 361 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Single-Line Diagram (SLD) Sandbox geodesy · globalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js lines 7701–7736
  2. Substation Intelligence geodesy · globalgrid2050 / testcode/202609060528/atlas/cartridges/202609060528-substation-intelligence.js lines 1–664

Single-Line Diagram (SLD) Sandbox

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps grid substations, connection points, GB transmission network and price decade rollup, using haversine.

geodesyglobalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js · lines 7701–7736 of 7736 · version 2026-09-06 03:00 (continued from section 350) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)

What it does
It maps grid substations, connection points, GB transmission network and price decade rollup. Defines 233 functions or classes, including distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg. 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: GeoJSON file grid_substations.geojson; JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; browser storage (getItem); DuckDB queries; form fields (user input). 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`), builds stats (`buildStats`) and applies development stage defaults (`applyDevelopmentStageDefaults`). Its `distanceKm` function gives distance km from two coordinate pairs (VEDIC: measure). 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
globalgrid2050 · testcode/202609060300/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, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver, publish
Defines here
installSld
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:7701-7736 · blob b9451a6d240116dae04211c0cc8216a75da78ad1 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
        dashboard.classList.remove('gridatlas-fs-layers');
        home.parent.insertBefore(dashboard, home.next);
        home = null;
      }
      boundCardToMap();
    };
    document.addEventListener('fullscreenchange', onChange);
    document.addEventListener('webkitfullscreenchange', onChange);

    const style = document.createElement('style');
    style.textContent = SLD_STYLES.fullscreenLayers();
    document.head.appendChild(style);
  }

  function installSld(map) {
    installSldStyles();
    ensureSldLayers(map);
    attachSldDragging(map);
    try { keepLayersInFullscreen(); }
    catch (error) { link.failures.push('fullscreen: ' + String(error?.message || error)); }
    try { armCorridorGestures(map); }
    catch (error) { link.failures.push('corridor sheet: ' + String(error?.message || error)); }
    // A substation click offers the layout; the neon links still draw.
    map.on('click', (event) => {
      if (fromOwnUi(event)) return;
      if (!map.getLayer(SUBS_LAYER_ID)) return;
      const hits = map.queryRenderedFeatures(event.point, { layers: [SUBS_LAYER_ID] });
      if (!hits.length) return;
      const properties = hits[0].properties || {};
      const at = representativePoint(hits[0].geometry);
      if (!at) return;
      openSldAt(map, at, properties.name || 'Grid node',
        (voltagesKv(properties)[0] ? `${voltagesKv(properties)[0]} kV` : ''));
    });
  }
})();

Substation Intelligence

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps elizabeth line and london underground, 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: 100% of its lines are the same as apps/substation-finder/Si/202609060537-substation-intelligence.js (code-generator), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9971 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
  • sha256 20bedcfc3a9037568e1bd9568512928a0a4781eaa0158ae62e2b46d4b3065db5
  • target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesyglobalgrid2050 / testcode/202609060528/atlas/cartridges/202609060528-substation-intelligence.js · lines 1–664 of 5420 · version 2026-09-06 05:28 · Not reached from any entry point (candidate for review) · pattern restoreLayers (shared by 2 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 232 functions or classes, including close, open, dockLayers, restoreLayers, show. 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 'testcode'): 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: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json. Out: CSV file gridatlas-polygon-vertices.csv; downloaded file gridatlas-polygon-; downloaded file gridatlas-polygon-vertices.csv; downloaded file gridatlas-; downloaded file globalgrid2050-map-; browser storage (setItem); interactive map; canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It restores layers (`restoreLayers`), saves outline (`saveOutline`) and reads outline (`readOutline`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 400 kV and 100 MVA. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609060528/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
mentioned in Geodesy (comment link)
Produces
close, open, dockLayers, restoreLayers, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail
Defines here
close, open, dockLayers, restoreLayers, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on, exportOutline, importOutline, createHistory, copy, deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawStorageStatus, _zoneDrawRefreshEditor, _zoneDrawUpdateLayers, _zoneDrawShowPopup
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060528/atlas/cartridges/202609060528-substation-intelligence.js:1-664 · blob a4d79e151fc9f1a2b632f53187a97278a5ad843c · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: ICP_grid_engineer · canonical: duplicate_candidate
/* 202609060528; source and token/AST compaction receipts in source-provenance.json. */

'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
'use strict';
(() => {
const registry = window.__GRIDATLAS_MODULES__ ||= {};
let state = null;
function close() {
if (!state) return;
const {map, host, rail, control, marker, style, restoreLayers} = state;
state = null;
restoreLayers();
marker.replaceWith(control);
rail.remove(); style.remove();
host.removeAttribute('data-measurement-dock');
document.body.removeAttribute('data-measurement-dock');
map.resize();
}
function open(map, controlId) {
if (state?.control.id === controlId) return;
close();
const canvas = map.getContainer();
const host = canvas.parentElement;
const control = document.getElementById(controlId);
if (!control || !host) throw Error('Measurement dock requires its existing control and map host');
const marker = document.createComment('measurement control home');
control.before(marker);
const rail = document.createElement('aside');
rail.id = 'gridatlas-measurement-dock';
rail.setAttribute('aria-label', 'Shape measurements and controls');
const controls = document.createElement('div');
controls.className = 'measurement-dock-controls';
controls.append(control);
let layersControl=null,layersMarker=null;
const dockLayers=()=>{
if(layersControl)return;
const button=document.getElementById('gridatlas-dash-toggle');if(!button)return;
layersControl=button;layersMarker=document.createComment('layers launcher home');
button.before(layersMarker);controls.prepend(button);observer.disconnect();
};
const observer=new MutationObserver(dockLayers);
observer.observe(document.body,{childList:true,subtree:true});dockLayers();
const restoreLayers=()=>{observer.disconnect();if(layersMarker&&layersControl)layersMarker.replaceWith(layersControl);};
const values = document.createElement('div');
values.className = 'measurement-dock-values';
rail.append(controls, values);
const style = document.createElement('style');
style.textContent = `
#map-container[data-measurement-dock] #map{width:calc(100% - 280px)!important;margin-left:280px!important}
#gridatlas-measurement-dock{position:absolute;left:0;top:64px;bottom:0;width:280px;box-sizing:border-box;overflow:auto;overscroll-behavior:contain;background:#080b10;border-right:1px solid #58646d;color:#fff;z-index:4100;padding:10px;font:12px/1.4 ui-monospace,monospace}
#gridatlas-measurement-dock .radius-popup{position:static!important;transform:none!important;margin:0 0 10px!important;width:auto!important;min-width:0!important;max-width:100%!important;box-sizing:border-box}
#gridatlas-measurement-dock .measurement-dock-values>div{min-width:0!important;box-sizing:border-box;max-width:100%}
#gridatlas-measurement-dock button,#gridatlas-measurement-dock input{min-height:44px}
#gridatlas-measurement-dock :focus-visible{outline:2px solid #fff;outline-offset:2px}
#gridatlas-measurement-dock #gridatlas-dash-toggle{position:static!important;display:block;width:100%;margin:0 0 8px;box-sizing:border-box}
body[data-measurement-dock] #testcode-compute-receipt,body[data-measurement-dock] .testcode-identity{visibility:hidden!important}
body[data-measurement-dock] #codex-tool-layers{visibility:hidden!important;pointer-events:none!important}
@media(max-width:700px){
 body[data-measurement-dock] .scada-wrapper{left:12px!important;right:12px!important;width:auto!important;max-height:calc(100dvh - min(240px,38dvh) - 136px)!important;box-sizing:border-box}
 body[data-measurement-dock] .scada-wrapper[data-gridatlas-collapsed="1"]{max-height:0!important}
 #map-container[data-measurement-dock] #map{width:100%!important;margin-left:0!important;height:calc(100% - min(240px,38dvh))!important}
 #gridatlas-measurement-dock{top:auto;right:0;width:100%;height:min(240px,38dvh);border-right:0;border-top:1px solid #58646d;padding:8px 12px;display:grid;grid-template-columns:minmax(110px,0.8fr) minmax(180px,1.4fr);gap:8px;z-index:4100}
 #gridatlas-measurement-dock .measurement-dock-values>div{padding:6px!important}
 #gridatlas-measurement-dock .radius-popup{padding:6px!important}
 #gridatlas-measurement-dock .radius-input-row{flex-wrap:wrap}
}
@media(max-width:350px){#gridatlas-measurement-dock{grid-template-columns:1fr}}
`;
document.head.append(style);
host.append(rail);
host.setAttribute('data-measurement-dock', controlId);
document.body.setAttribute('data-measurement-dock', controlId);
state = {map, host, rail, control, marker, style, values, restoreLayers};
map.resize();
}
function show(html) {
if (!state) throw Error('Open measurement controls before showing results');
const scroll = state.rail.scrollTop;
state.values.innerHTML = html;
state.rail.scrollTop = scroll;
}
function clearValues() {if (state) state.values.replaceChildren();}
const draftKey = 'gridatlas.polygon-draft.v1';
function validOutline(points) {
return Array.isArray(points) && points.length >= 3 && points.length <= 4096 && points.every(point => Array.isArray(point) && point.length === 2 && point.every(Number.isFinite) && Math.abs(point[0]) <= 180 && Math.abs(point[1]) <= 85.051129);
}
function saveOutline(points) {
try {
if (!validOutline(points)) return {saved:false, message:'Outline cannot be saved: invalid coordinates.'};
localStorage.setItem(draftKey, JSON.stringify({schema:draftKey, points, savedAt:new Date().toISOString()}));
return {saved:true, message:'Saved on this browser'};
} catch { return {saved:false, message:'Browser storage unavailable; keep this tab open.'}; }
}
function readOutline() {
try {
const text = localStorage.getItem(draftKey);
if (!text || text.length > 250000) return null;
const draft = JSON.parse(text);
return draft.schema === draftKey && validOutline(draft.points) ? draft.points.map(point => point.slice()) : null;
} catch { return null; }
}
function clearOutline() {
try {localStorage.removeItem(draftKey);return {saved:true,message:'Polygon reset'};}
catch {return {saved:false,message:'Polygon reset here; browser storage could not be cleared.'};}
}
function analyzeOutline(points) {
const fail=(code,message)=>({valid:false,code,message});
if(!validOutline(points))return fail('coordinates','Use 3 to 4096 finite map coordinates.');
const n=points.length,edges=[];
const orient=(a,b,c)=>{const x=(b[0]-a[0])*(c[1]-a[1]),y=(b[1]-a[1])*(c[0]-a[0]),v=x-y;return Math.abs(v)<=Number.EPSILON*8*(Math.abs(x)+Math.abs(y))?0:Math.sign(v);};
const on=(a,b,p)=>p[0]>=Math.min(a[0],b[0])&&p[0]<=Math.max(a[0],b[0])&&p[1]>=Math.min(a[1],b[1])&&p[1]<=Math.max(a[1],b[1]);
for(let i=0;i<n;i++){
const a=points[i],b=points[(i+1)%n],c=points[(i+2)%n];
if(a[0]===b[0]&&a[1]===b[1])return fail('repeated','Consecutive vertices coincide. Move or remove the repeated corner.');
if(Math.abs(a[0]-b[0])>180)return fail('antimeridian','This outline crosses the date line. Area is not assessed by this map tool.');
if(orient(a,b,c)===0&&(a[0]-b[0])*(c[0]-b[0])+(a[1]-b[1])*(c[1]-b[1])>0)return fail('overlap','Adjacent edges double back over one another.');
edges.push({i,a,b,minX:Math.min(a[0],b[0]),maxX:Math.max(a[0],b[0]),minY:Math.min(a[1],b[1]),maxY:Math.max(a[1],b[1])});
}
edges.sort((a,b)=>a.minX-b.minX);let active=[];
for(const edge of edges){
active=active.filter(other=>other.maxX>=edge.minX);
for(const other of active){
const gap=Math.abs(edge.i-other.i);if(gap===1||gap===n-1||edge.minY>other.maxY||edge.maxY<other.minY)continue;
const a=edge.a,b=edge.b,c=other.a,d=other.b,o1=orient(a,b,c),o2=orient(a,b,d),o3=orient(c,d,a),o4=orient(c,d,b);
if((o1*o2<0&&o3*o4<0)||(o1===0&&on(a,b,c))||(o2===0&&on(a,b,d))||(o3===0&&on(c,d,a))||(o4===0&&on(c,d,b)))return fail('crossing','Non-adjacent edges cross or touch. Move the corners until the boundary is simple.');
}
active.push(edge);
}
const origin=points[0];let twiceArea=0;
for(let i=1;i<n-1;i++)twiceArea+=(points[i][0]-origin[0])*(points[i+1][1]-origin[1])-(points[i+1][0]-origin[0])*(points[i][1]-origin[1]);
if(twiceArea===0)return fail('degenerate','The outline has no enclosed area.');
return {valid:true,code:'simple',message:'Simple outline in map coordinates.'};
}
function exportOutline(points, measurements) {
const validity=analyzeOutline(points);if(!validity.valid)throw Error('Polygon not exported: '+validity.message);
if (!validOutline(points)) throw Error('Draw a valid polygon before saving a file.');
const ring = points.map(point => point.slice());
const origin=ring[0];
const winding = ring.reduce((sum,point,i) => {const next=ring[(i+1)%ring.length];return sum+(point[0]-origin[0])*(next[1]-origin[1])-(next[0]-origin[0])*(point[1]-origin[1]);},0);
if (winding < 0) ring.reverse();
ring.push(ring[0].slice());
const properties = {name:'GridAtlas drawn polygon', source:'User-drawn outline', coordinate_reference:'WGS84 longitude, latitude', boundary:'Screening outline only; not a surveyed boundary or connection offer.'};
for (const [key,value] of Object.entries(measurements || {})) if (['area_m2','area_ha','perimeter_km'].includes(key) && Number.isFinite(value) && value >= 0) properties[key]=value;
return {type:'FeatureCollection',features:[{type:'Feature',properties,geometry:{type:'Polygon',coordinates:[ring]}}]};
}
function importOutline(text) {
if (typeof text !== 'string' || text.length > 250000) throw Error('Choose a GeoJSON file under 250 KB.');
let data;
try {data=JSON.parse(text);} catch {throw Error('The file is not valid JSON. Your current polygon is unchanged.');}
if (data?.type === 'FeatureCollection') {
if (!Array.isArray(data.features) || data.features.length !== 1) throw Error('Choose a file containing exactly one polygon.');
data=data.features[0];
}
if (data?.type === 'Feature') data=data.geometry;
if (data?.type !== 'Polygon' || !Array.isArray(data.coordinates) || data.coordinates.length !== 1) throw Error('Choose one Polygon without holes; other geometries are not flattened.');
const ring=data.coordinates[0];
if (!Array.isArray(ring) || ring.length < 4 || JSON.stringify(ring[0]) !== JSON.stringify(ring.at(-1))) throw Error('The polygon ring must be closed.');
const points=ring.slice(0,-1);
if (!validOutline(points) || new Set(points.map(point=>JSON.stringify(point))).size < 3) throw Error('Polygon coordinates must be valid WGS84 longitude/latitude pairs, with 3 to 4096 vertices.');
return points.map(point=>point.slice());
}
registry.polygonFiles = Object.freeze({schema:'gridatlas.polygon-files.v1',exportOutline,importOutline,analyzeOutline});
function createHistory(limit=80) {
let states=[[]],position=0;
const copy=points=>points.map(point=>point.slice());
return Object.freeze({
commit(points) {
if (JSON.stringify(states[position])===JSON.stringify(points)) return;
states=states.slice(0,position+1);states.push(copy(points));
if(states.length>limit)states.shift();position=states.length-1;
},
undo() {if(position===0)return null;return copy(states[--position]);},
redo() {if(position===states.length-1)return null;return copy(states[++position]);},
get canUndo(){return position>0;},get canRedo(){return position<states.length-1;}
});
}
registry.polygonHistory = Object.freeze({createHistory});
registry.polygonDraft = Object.freeze({schema:draftKey,validOutline,saveOutline,readOutline,clearOutline});
registry.measurementDock = Object.freeze({schema:'gridatlas.measurement-dock.v1',open,show,close,clearValues});
})();
'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.');
}
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function normalizeStatus(status) {
return String(status ?? '').trim().toLowerCase();
}
function fmt(n, decimals) {
return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}
const measurementDock = window.__GRIDATLAS_MODULES__?.measurementDock;
if (!measurementDock) throw Error('Measurement dock module missing');
const EARTH_RADIUS_KM = 6378.137;
const MAX_RADIUS_KM = Math.PI * EARTH_RADIUS_KM;
const DEG_TO_RAD = Math.PI / 180;
const HIT_RADIUS_VERTEX_PX = 22;
const HIT_RADIUS_EDGE_PX = 16;
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;
const bounded = Math.max(0, Math.min(1, a));
return R * 2 * Math.atan2(Math.sqrt(bounded), Math.sqrt(1 - bounded));
}
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])
);
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;
const ZONE_DRAW_MAX_KM = MAX_RADIUS_KM;
let zoneDrawMode = false;
let zoneDrawLocked = false;
let zoneDrawPoints = [];
let zoneDrawDragging = false;
let zoneDrawDragIdx = -1;
let zoneDrawJustDragged = false;
let _zoneDrawCollapsed = false;
const zoneHistory = window.__GRIDATLAS_MODULES__.polygonHistory.createHistory();
let zoneHistoryApplying = 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 _zoneDrawStorageStatus(result) {
let status = document.getElementById('zonedraw-storage-status');
if (!status) {
status = document.createElement('div'); status.id = 'zonedraw-storage-status';
status.setAttribute('role','status'); status.style.cssText = 'font-size:10px;margin-top:8px;color:#cbd5e1';
document.getElementById('zonedraw-display')?.append(status);
}
status.textContent = result.message;
}
function _zoneDrawRefreshEditor() {
const select=document.getElementById('zonedraw-vertex');if(!select)return;
const previous=Math.min(Number(select.value)||0,Math.max(0,zoneDrawPoints.length-1));
if(select.options.length!==zoneDrawPoints.length){select.replaceChildren();zoneDrawPoints.forEach((_,i)=>{const option=document.createElement('option');option.value=String(i);option.textContent='Vertex '+(i+1);select.append(option);});}
select.value=String(previous);const point=zoneDrawPoints[previous];
const lon=document.getElementById('zonedraw-longitude'),lat=document.getElementById('zonedraw-latitude');
lon.value=point?String(point[0]):'';lat.value=point?String(point[1]):'';
for(const control of [select,lon,lat,document.getElementById('btn-zonedraw-coordinate')])control.disabled=zoneDrawLocked||zoneDrawPoints.length<3;
const remove=document.getElementById('btn-zonedraw-remove');if(remove)remove.disabled=zoneDrawLocked||zoneDrawPoints.length<=3;
}
function _zoneDrawUpdateLayers(dragOnly, renderOnly = false) {
if(!dragOnly && !renderOnly)_zoneDrawRefreshEditor();
if (!dragOnly && !renderOnly) {
if (!zoneHistoryApplying) zoneHistory.commit(zoneDrawPoints);
const undo=document.getElementById('btn-zonedraw-undo'),redo=document.getElementById('btn-zonedraw-redo');
if(undo)undo.disabled=!zoneHistory.canUndo;if(redo)redo.disabled=!zoneHistory.canRedo;
}
const csvButton=document.getElementById('btn-zonedraw-csv');if(csvButton)csvButton.disabled=zoneDrawPoints.length<3;
const fitButton=document.getElementById('btn-zonedraw-fit');if(fitButton)fitButton.disabled=zoneDrawPoints.length<3;
const exportButton = document.getElementById('btn-zonedraw-export');
const validity=window.__GRIDATLAS_MODULES__.polygonFiles.analyzeOutline(zoneDrawPoints);
if (exportButton) {exportButton.disabled=!validity.valid;exportButton.title=validity.valid?'Save a closed polygon':validity.message;}
if (!dragOnly && !renderOnly && zoneDrawPoints.length >= 3) _zoneDrawStorageStatus(window.__GRIDATLAS_MODULES__.polygonDraft.saveOutline(zoneDrawPoints));
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: validity.valid ? [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] } }] : [] });
map.getSource('src-zonedraw-line').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'LineString', coordinates: ring } }] });
if (zoneDrawLocked) {map.getSource('src-zonedraw-points').setData({type:'FeatureCollection',features:[]});return;}
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) => {
_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 validity=window.__GRIDATLAS_MODULES__.polygonFiles.analyzeOutline(zoneDrawPoints);
if(!validity.valid){measurementDock.show('<div id="zonedraw-validity-warning" role="status" style="padding:10px;border:1px solid #ffb14d;color:#ffcc80"><strong>Area not assessed</strong><p>'+validity.message+'</p><p>The outline is kept for repair. Drag a corner, edit a coordinate, or Undo. GeoJSON export resumes when the outline is simple.</p></div>');return;}
const { areaKm2, areaHa, areaAc, areaMi2, areaM2, perimKm, pitches } = _zoneDrawCalcArea(zoneDrawPoints);
if (_zoneDrawCollapsed) {
measurementDock.show( `
                <button type="button" data-zonedraw-toggle aria-label="Expand polygon measurements" aria-expanded="false" onclick="window._zdExpand&&window._zdExpand()" style="font-family:monospace;background:#000;padding:5px 10px;border:1px solid #ff6600;border-radius:4px;cursor:pointer;color:#ff9a58;font-size:12px;white-space:normal;max-width:100%;text-align:left;">
                    ◉ ${fmt(areaKm2,3)} km² · ⚽ ${fmt(pitches,0)} pitches &nbsp;▾
                </button>`);
window._zdExpand = () => { _zoneDrawCollapsed = false; _zoneDrawShowPopup(); document.querySelector('[data-zonedraw-toggle]')?.focus(); };
} else {
measurementDock.show( `
                <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>
                        <button type="button" data-zonedraw-toggle aria-label="Collapse polygon measurements" aria-expanded="true" onclick="window._zdCollapse&&window._zdCollapse()" style="color:#bbb;background:#000;border:1px solid #777;border-radius:3px;font-size:12px;cursor:pointer;padding:0 8px;" title="Collapse">▴ hide</button>
                    </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:#aaa;font-size:11px;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</b> restores the previous edit<br>
                        • <b>Reset polygon</b> to start a new zone
                    </div>
                </div>`);
window._zdCollapse = () => { _zoneDrawCollapsed = true; _zoneDrawShowPopup(); document.querySelector('[data-zonedraw-toggle]')?.focus(); };
}
}
function _zoneDrawShowPopupDebounced() {
if (_zoneDrawPopupRaf) return;
_zoneDrawPopupRaf = requestAnimationFrame(() => { _zoneDrawPopupRaf = null; _zoneDrawShowPopup(); });
}
function _zoneDrawClear() {
zoneDrawLocked=false;
const lock=document.getElementById('btn-zonedraw-lock');
if(lock){lock.textContent='Lock polygon';lock.setAttribute('aria-pressed','false');}
_zoneDrawStorageStatus(window.__GRIDATLAS_MODULES__.polygonDraft.clearOutline());
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 zoneDrawHistoryMove(direction) {
const points = zoneHistory[direction](); if (!points) return;
zoneDrawPoints = points; zoneDrawDragging=false; zoneDrawDragIdx=-1;
zoneHistoryApplying=true;
try {_zoneDrawUpdateLayers(false);} finally {zoneHistoryApplying=false;}
if(points.length>=3)_zoneDrawShowPopup();
else {measurementDock.clearValues();_zoneDrawStorageStatus(window.__GRIDATLAS_MODULES__.polygonDraft.clearOutline());}
}
function zoneDrawUndo() {zoneDrawHistoryMove('undo');}
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';
measurementDock.open(map, 'zonedraw-display');
if (!zoneDrawPoints.length) {
const restored = window.__GRIDATLAS_MODULES__.polygonDraft.readOutline();
if (restored) {
zoneDrawPoints = restored;
_zoneDrawUpdateLayers(false); _zoneDrawFit();
_zoneDrawStorageStatus({message:'Restored saved polygon from this browser'});
}
}
if (zoneDrawPoints.length >= 3) _zoneDrawShowPopup();
} else {
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'none';
measurementDock.close();
}
}
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;
}
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 _zoneDrawFit() {
const lons = zoneDrawPoints.map(p => p[0]), lats = zoneDrawPoints.map(p => p[1]);
map.fitBounds([[Math.min(...lons), Math.min(...lats)], [Math.max(...lons), Math.max(...lats)]], {
padding: { top: 100, right: 36, bottom: 48, left: 36 }, maxZoom: 19, duration: 600
});
}
function _zoneDrawOnClick(e) {
if (zoneDrawLocked) return;
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;
_zoneDrawFit();
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
const px = map.project([lon, lat]);
if (_zoneDrawNearVertex(px) >= 0) return;
const edgeHit = _zoneDrawNearEdgeDot(px);
if (edgeHit) {
if(zoneDrawPoints.length>=4096){_zoneDrawStorageStatus({message:'This outline already has 4096 vertices. Remove an unneeded corner before adding another.'});return;}
zoneDrawPoints.splice(edgeHit.insertIdx, 0, [edgeHit.dot[0], edgeHit.dot[1]]);
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
return;
}
function _zoneDrawOnMouseDown(e) {
if (!zoneDrawMode || zoneDrawLocked || zoneDrawPoints.length < 3) return;
const px = map.project(e.lngLat);
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 || zoneDrawLocked || 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 = [];
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() {
measurementDock.clearValues();
if (activePopup) { activePopup.remove(); activePopup = null; }
}
window._closePopupKeepShape = () => closeActivePopup();
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(); });
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;
}
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]);