GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / testcode / sandbox/202609060459/atlas/cartridges

Substation Intelligence (part 15)

A JavaScript file in the cartridges folder of Testcode 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 testcode, in 1 file. Topic: Grid network and substations. Section 455 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. Substation Intelligence geodesy · testcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js lines 1130–1829

Substation Intelligence

A JavaScript file in the cartridges folder of Testcode 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: 99% 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.9913 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
  • sha256 916bad1b531c94d9acd3bc54f6ed205b467b96e6c1d86beea47a7d66e2f51669
  • target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesytestcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js · lines 1130–1829 of 5400 · version 2026-09-06 04:59 (continued from section 453) · Not reached from any entry point (candidate for review) · pattern _zoneDrawRefreshEditor (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 230 functions or classes, including close, open, show, clearValues, validOutline. 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: 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 saves outline (`saveOutline`), reads outline (`readOutline`) and exports outline (`exportOutline`). 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
testcode · sandbox/202609060459/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 Standalone (comment link)
Produces
close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on
Defines here
handleLayerToggle, getLayerConfig, getSourceIdForLayer, transitExpressionValue, transitFilterMatches, geometryFitsMapLayer, countTransitFeaturesLayerCanDraw, setLayerControlAvailability, updateTransitSourceStates, hydrateLayer, evalFilter, pointOf, endTouch, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf, index, land, siteOf, graph
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js:1130-1829 · blob fd03f2ae502f2d404cb773df8858c2746ada6401 · 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: unreached_review
document.getElementById('fs-curtain-tab').addEventListener('click', toggleCurtain);
const input = document.getElementById('search-input'); const btn = document.getElementById('search-btn'); const resultsEl = document.getElementById('search-results');
input.addEventListener('input', () => searchProjects(input.value));
input.addEventListener('keydown', e => { if (e.key === 'Enter') searchProjects(input.value); if (e.key === 'Escape') resultsEl.style.display = 'none'; });
btn.addEventListener('click', () => searchProjects(input.value));
document.getElementById('map').addEventListener('click', () => { resultsEl.style.display = 'none'; });
document.getElementById('btn-export').addEventListener('click', exportCSV); document.getElementById('btn-status').addEventListener('click', toggleStatusMode);
document.getElementById('btn-radius').addEventListener('click', toggleRadiusMode); document.getElementById('btn-measure').addEventListener('click', toggleMeasureMode);
document.getElementById('btn-measure-undo').addEventListener('click', undoLastMeasurePoint);
const zoneReset = document.createElement('button');
zoneReset.id = 'btn-zonedraw-reset';
zoneReset.type = 'button';
zoneReset.textContent = 'Reset polygon';
zoneReset.title = 'Clear this polygon and place a new circle';
zoneReset.style.cssText = 'display:block;margin-top:8px;padding:8px;border:1px solid #ff6600;background:#111;color:#ffb14d;cursor:pointer;min-height:44px';
zoneReset.addEventListener('click', () => {
_zoneDrawClear();
const control = document.getElementById('zonedraw-display');
if (control && zoneDrawMode) control.style.display = 'block';
});
document.getElementById('zonedraw-display').append(zoneReset);
const zoneExport = document.createElement('button');
zoneExport.id = 'btn-zonedraw-export'; zoneExport.type = 'button';
zoneExport.textContent = 'Save GeoJSON'; zoneExport.disabled = zoneDrawPoints.length < 3;
zoneExport.style.cssText = 'display:block;margin-top:8px;padding:8px;border:1px solid #42bcca;background:#111;color:#b9f8ff;cursor:pointer;min-height:44px';
zoneExport.addEventListener('click', () => {
try {
const area = _zoneDrawCalcArea(zoneDrawPoints);
const data = window.__GRIDATLAS_MODULES__.polygonFiles.exportOutline(zoneDrawPoints,{area_m2:area.areaM2,area_ha:area.areaHa,perimeter_km:area.perimKm});
const url = URL.createObjectURL(new Blob([JSON.stringify(data,null,2)+'\n'],{type:'application/geo+json'}));
const anchor = document.createElement('a'); anchor.href=url;
anchor.download='gridatlas-polygon-'+new Date().toISOString().replace(/[:.]/g,'-')+'.geojson';
document.body.append(anchor); anchor.click(); anchor.remove();
setTimeout(() => URL.revokeObjectURL(url),1000);
_zoneDrawStorageStatus({message:'GeoJSON download created'});
} catch(error) {_zoneDrawStorageStatus({message:error.message});}
});
document.getElementById('zonedraw-display').append(zoneExport);
const zoneImport = document.createElement('button');
zoneImport.id='btn-zonedraw-import'; zoneImport.type='button'; zoneImport.textContent='Open GeoJSON';
zoneImport.style.cssText=zoneExport.style.cssText;
const zoneFile=document.createElement('input'); zoneFile.type='file'; zoneFile.id='zonedraw-file';
zoneFile.accept='.geojson,.json,application/geo+json,application/json'; zoneFile.hidden=true;
zoneImport.addEventListener('click',()=>zoneFile.click());
zoneFile.addEventListener('change',async()=>{
const file=zoneFile.files[0]; if(!file)return;
try {
if(file.size>250000)throw Error('Choose a GeoJSON file under 250 KB.');
const points=window.__GRIDATLAS_MODULES__.polygonFiles.importOutline(await file.text());
zoneDrawPoints=points; zoneDrawDragging=false; zoneDrawDragIdx=-1;
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup(); _zoneDrawFit();
_zoneDrawStorageStatus({message:'Opened '+points.length+' polygon vertices from '+file.name});
} catch(error) {_zoneDrawStorageStatus({message:error.message});}
finally {zoneFile.value='';}
});
document.getElementById('zonedraw-display').append(zoneImport,zoneFile);
const zoneRedo=document.createElement('button');zoneRedo.id='btn-zonedraw-redo';zoneRedo.type='button';
zoneRedo.textContent='Redo edit';zoneRedo.disabled=true;zoneRedo.style.cssText=zoneExport.style.cssText;
zoneRedo.addEventListener('click',()=>zoneDrawHistoryMove('redo'));
document.getElementById('zonedraw-display').append(zoneRedo);
const zoneLock=document.createElement('button');zoneLock.id='btn-zonedraw-lock';zoneLock.type='button';
zoneLock.textContent='Lock polygon';zoneLock.setAttribute('aria-pressed','false');zoneLock.style.cssText=zoneExport.style.cssText;
zoneLock.addEventListener('click',()=>{
zoneDrawLocked=!zoneDrawLocked;zoneDrawDragging=false;zoneDrawDragIdx=-1;map.dragPan.enable();
zoneLock.textContent=zoneDrawLocked?'Unlock polygon':'Lock polygon';zoneLock.setAttribute('aria-pressed',String(zoneDrawLocked));
map.getCanvas().style.cursor=zoneDrawLocked?'grab':'crosshair';_zoneDrawUpdateLayers(false);
_zoneDrawStorageStatus({message:zoneDrawLocked?'Polygon locked: pan and zoom without editing vertices':'Polygon unlocked: drag corners to edit'});
});
document.getElementById('zonedraw-display').append(zoneLock);
const zoneFit=document.createElement('button');zoneFit.id='btn-zonedraw-fit';zoneFit.type='button';
zoneFit.textContent='Fit polygon';zoneFit.disabled=zoneDrawPoints.length<3;zoneFit.style.cssText=zoneExport.style.cssText;
zoneFit.addEventListener('click',()=>{if(zoneDrawPoints.length>=3)_zoneDrawFit();});
document.getElementById('zonedraw-display').append(zoneFit);
const zoneCSV=document.createElement('button');zoneCSV.id='btn-zonedraw-csv';zoneCSV.type='button';
zoneCSV.textContent='Save vertex CSV';zoneCSV.disabled=zoneDrawPoints.length<3;zoneCSV.style.cssText=zoneExport.style.cssText;
zoneCSV.addEventListener('click',()=>{
if(zoneDrawPoints.length<3)return;
let chainage=0;const lines=['vertex,longitude_deg,latitude_deg,chainage_m,next_segment_m'];
zoneDrawPoints.forEach((p,i)=>{const q=zoneDrawPoints[(i+1)%zoneDrawPoints.length],length=haversine(p[0],p[1],q[0],q[1])*1000;
lines.push([i+1,p[0],p[1],chainage,length].join(','));chainage+=length;});
const url=URL.createObjectURL(new Blob([lines.join('\r\n')+'\r\n'],{type:'text/csv;charset=utf-8'}));
const anchor=document.createElement('a');anchor.href=url;anchor.download='gridatlas-polygon-vertices.csv';
document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
_zoneDrawStorageStatus({message:'Vertex CSV created. Chainage follows the drawn order; the last segment closes the outline. Distances are geodesic estimates.'});
});
document.getElementById('zonedraw-display').append(zoneCSV);
const zoneEditor=document.createElement('details');zoneEditor.id='zonedraw-coordinate-editor';zoneEditor.style.cssText='margin-top:8px;font-size:12px';
const summary=document.createElement('summary');summary.textContent='Edit or remove vertices';summary.style.cssText='min-height:44px;cursor:pointer';zoneEditor.append(summary);
for(const spec of [['Vertex','zonedraw-vertex','select'],['Longitude (degrees)','zonedraw-longitude','input'],['Latitude (degrees)','zonedraw-latitude','input']]){
const label=document.createElement('label');label.textContent=spec[0];label.htmlFor=spec[1];label.style.display='block';
const control=document.createElement(spec[2]);control.id=spec[1];control.disabled=true;control.style.cssText='display:block;box-sizing:border-box;width:100%;min-height:44px;background:#111;color:#fff;border:1px solid #64748b';
if(spec[2]==='input'){control.type='number';control.step='any';control.min=spec[1].endsWith('longitude')?'-180':'-85.051129';control.max=spec[1].endsWith('longitude')?'180':'85.051129';}
zoneEditor.append(label,control);
}
const zoneApply=document.createElement('button');zoneApply.id='btn-zonedraw-coordinate';zoneApply.type='button';zoneApply.textContent='Apply coordinate';zoneApply.disabled=true;zoneApply.style.cssText=zoneExport.style.cssText;zoneEditor.append(zoneApply);
const zoneRemove=document.createElement('button');zoneRemove.id='btn-zonedraw-remove';zoneRemove.type='button';zoneRemove.textContent='Remove selected vertex';zoneRemove.disabled=true;zoneRemove.style.cssText=zoneExport.style.cssText;zoneEditor.append(zoneRemove);
zoneRemove.title='Keep at least three vertices. Undo restores a removed vertex.';
zoneRemove.addEventListener('click',()=>{
if(zoneDrawLocked||zoneDrawPoints.length<=3)return;
const i=Number(document.getElementById('zonedraw-vertex').value);
if(!Number.isInteger(i)||!zoneDrawPoints[i])return;
zoneDrawPoints.splice(i,1);_zoneDrawUpdateLayers(false);_zoneDrawShowPopup();
_zoneDrawStorageStatus({message:'Removed vertex '+(i+1)+'. Undo restores the exact outline.'});
});
document.getElementById('zonedraw-display').append(zoneEditor);
document.getElementById('zonedraw-vertex').addEventListener('change',_zoneDrawRefreshEditor);
zoneApply.addEventListener('click',()=>{
if(zoneDrawLocked||zoneDrawPoints.length<3)return;
const i=Number(document.getElementById('zonedraw-vertex').value),a=document.getElementById('zonedraw-longitude').value,b=document.getElementById('zonedraw-latitude').value;
const lon=Number(a),lat=Number(b);
if(!a.trim()||!b.trim()||!Number.isInteger(i)||!zoneDrawPoints[i]||!Number.isFinite(lon)||!Number.isFinite(lat)||Math.abs(lon)>180||Math.abs(lat)>85.051129){_zoneDrawStorageStatus({message:'Enter longitude from -180 to 180 and latitude from -85.051129 to 85.051129 degrees. The outline has not changed.'});return;}
zoneDrawPoints[i]=[lon,lat];_zoneDrawUpdateLayers(false);_zoneDrawShowPopup();
_zoneDrawStorageStatus({message:'Updated vertex '+(i+1)+'. Undo restores its previous coordinate.'});
});
const existingUndo=document.getElementById('btn-zonedraw-undo');
if(existingUndo){existingUndo.textContent='Undo edit';existingUndo.title='Undo the last polygon edit, import or reset';existingUndo.disabled=true;}
const radiusInput = document.getElementById('radius-input');
if(radiusInput) {
radiusInput.addEventListener('input', () => validateRadiusInput());
radiusInput.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); if (validateRadiusInput() && radiusCenter) doRadiusSearch(radiusCenter.lon, radiusCenter.lat); } e.stopPropagation(); });
radiusInput.addEventListener('blur', () => {
const raw = parseFloat(radiusInput.value);
if (isNaN(raw) || raw < RADIUS_MIN) radiusInput.value = RADIUS_MIN; else if (raw > RADIUS_MAX) radiusInput.value = RADIUS_MAX;
radiusInput.classList.remove('invalid'); if (radiusCenter) doRadiusSearch(radiusCenter.lon, radiusCenter.lat);
});
}
const btnRadiusArea = document.getElementById('btn-radius-area');
if (btnRadiusArea) btnRadiusArea.addEventListener('click', toggleRadiusAreaMode);
const btnZoneDraw = document.getElementById('btn-zonedraw');
if (btnZoneDraw) btnZoneDraw.addEventListener('click', toggleZoneDrawMode);
const btnZoneDrawUndo = document.getElementById('btn-zonedraw-undo');
if (btnZoneDrawUndo) btnZoneDrawUndo.addEventListener('click', zoneDrawUndo);
const zdRadiusInput = document.getElementById('zonedraw-radius-input');
if (zdRadiusInput) {
zdRadiusInput.addEventListener('keydown', e => { e.stopPropagation(); });
zdRadiusInput.addEventListener('blur', () => {
const raw = parseFloat(zdRadiusInput.value);
if (isNaN(raw) || raw <= 0) zdRadiusInput.value = String(ZONE_DRAW_DEFAULT_KM);
else if (raw > ZONE_DRAW_MAX_KM) zdRadiusInput.value = String(ZONE_DRAW_MAX_KM);
});
}
const rAreaInput = document.getElementById('radius-area-input');
if (rAreaInput) {
rAreaInput.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
if (radiusAreaCenter) doRadiusAreaMeasure(radiusAreaCenter.lon, radiusAreaCenter.lat);
}
e.stopPropagation();
});
rAreaInput.addEventListener('blur', () => {
const raw = parseFloat(rAreaInput.value);
if (isNaN(raw) || raw <= 0) rAreaInput.value = 1; else if (raw > MAX_RADIUS_KM) rAreaInput.value = MAX_RADIUS_KM;
rAreaInput.classList.remove('invalid');
if (radiusAreaCenter) doRadiusAreaMeasure(radiusAreaCenter.lon, radiusAreaCenter.lat);
});
}
}
function handleLayerToggle(layerId, isVisible) {
if (map.getLayer(`l-${layerId}`)) map.setLayoutProperty(`l-${layerId}`, 'visibility', isVisible ? 'visible' : 'none');
if (map.getLayer(`l-${layerId}-glow`)) map.setLayoutProperty(`l-${layerId}-glow`, 'visibility', (isVisible && !statusMode) ? 'visible' : 'none');
const mapId = `l-${layerId}`;
if (isVisible) {
if (!_visibleInteractiveIds.includes(mapId)) _visibleInteractiveIds.push(mapId);
if (!_visibleHoverIds.includes(mapId)) _visibleHoverIds.push(mapId);
} else {
_visibleInteractiveIds = _visibleInteractiveIds.filter(id => id !== mapId);
_visibleHoverIds = _visibleHoverIds.filter(id => id !== mapId);
}
if (isVisible && layerId !== '400') hydrateLayer(layerId);
}
function getLayerConfig(layerId) { return layerConfigById.get(layerId); }
function getSourceIdForLayer(layerId) {
if (REPD_IDS.includes(layerId)) return 'src-repd';
if (TRANSIT_IDS.includes(layerId)) return TRANSIT_SOURCE_MAP[layerId];
if (layerId === 'naei_co2') return 'src-naei_co2';
return `src-${layerId}`;
}
function transitExpressionValue(expression, feature) {
if (!Array.isArray(expression)) return expression;
if (expression[0] === 'get') return feature && feature.properties
? feature.properties[expression[1]] : undefined;
if (expression[0] === 'literal') return expression[1];
return undefined;
}
function transitFilterMatches(filter, feature) {
if (!Array.isArray(filter) || filter.length === 0) return true;
const operator = filter[0];
if (operator === 'all') return filter.slice(1).every(item => transitFilterMatches(item, feature));
if (operator === 'any') return filter.slice(1).some(item => transitFilterMatches(item, feature));
if (operator === '!') return !transitFilterMatches(filter[1], feature);
if (operator === '==') return transitExpressionValue(filter[1], feature) === transitExpressionValue(filter[2], feature);
if (operator === '!=') return transitExpressionValue(filter[1], feature) !== transitExpressionValue(filter[2], feature);
if (operator === 'in' || operator === '!in') {
const needle = transitExpressionValue(filter[1], feature);
const haystack = transitExpressionValue(filter[2], feature);
const contains = typeof haystack === 'string'
? haystack.includes(String(needle))
: Array.isArray(haystack) && haystack.includes(needle);
return operator === 'in' ? contains : !contains;
}
return true;
}
function geometryFitsMapLayer(layerType, geometryType) {
if (layerType === 'circle' || layerType === 'heatmap') return geometryType === 'Point' || geometryType === 'MultiPoint';
if (layerType === 'line') return geometryType === 'LineString' || geometryType === 'MultiLineString';
if (layerType === 'fill' || layerType === 'fill-extrusion') return geometryType === 'Polygon' || geometryType === 'MultiPolygon';
return true;
}
function countTransitFeaturesLayerCanDraw(layerId, features) {
const layerConfig = getLayerConfig(layerId);
const mapLayer = map.getLayer(`l-${layerId}`);
if (!layerConfig || !mapLayer) return 0;
return features.reduce((count, feature) => {
const geometryType = feature && feature.geometry && feature.geometry.type;
if (!geometryFitsMapLayer(mapLayer.type, geometryType)) return count;
return transitFilterMatches(layerConfig.filter, feature) ? count + 1 : count;
}, 0);
}
function setLayerControlAvailability(layerId, available) {
document.querySelectorAll(`input[data-layer-id="${layerId}"]`).forEach(input => {
input.disabled = !available;
if (!available) input.checked = false;
});
if (available) return;
[`l-${layerId}`, `l-${layerId}-glow`].forEach(mapLayerId => {
if (map.getLayer(mapLayerId)) map.setLayoutProperty(mapLayerId, 'visibility', 'none');
});
const mapLayerId = `l-${layerId}`;
_visibleInteractiveIds = _visibleInteractiveIds.filter(id => id !== mapLayerId);
_visibleHoverIds = _visibleHoverIds.filter(id => id !== mapLayerId);
}
function updateTransitSourceStates(sourceId, features) {
TRANSIT_IDS.forEach(transitId => {
if (TRANSIT_SOURCE_MAP[transitId] !== sourceId || !RUNTIME_STATE[transitId]) return;
const available = countTransitFeaturesLayerCanDraw(transitId, features) > 0;
RUNTIME_STATE[transitId].loaded = true;
RUNTIME_STATE[transitId].loading = false;
setLayerControlAvailability(transitId, available);
updateUIState(transitId, available ? 'OK' : 'EMPTY');
});
}
async function hydrateLayer(layerId) {
const state = RUNTIME_STATE[layerId];
if (!state || state.loaded || state.loading) return;
state.loading = true; updateUIState(layerId, 'LOAD');
const layerConfig = getLayerConfig(layerId);
if (!layerConfig) { updateUIState(layerId, 'FAIL'); state.loading = false; return; }
await networkQueue.add(async () => {
try {
let features = await fetchAndParseGeoJSON(layerConfig.url);
if (features.length === 0) {
if (TRANSIT_IDS.includes(layerId)) updateTransitSourceStates(TRANSIT_SOURCE_MAP[layerId], features);
else { state.loaded = true; state.loading = false; updateUIState(layerId, 'EMPTY'); }
return;
}
if (layerConfig.isSubs) globalSubsData = features;
if (layerConfig.snap) {
if (!globalSubsData) { const subsLayer = getLayerConfig('subs'); globalSubsData = await fetchAndParseGeoJSON(subsLayer.url); }
console.warn(`[SNAP] Runtime snapping active for "${layerId}" — ${features.length} features. Move to build pipeline when possible.`);
features = snapLines(features, globalSubsData);
}
const sourceId = getSourceIdForLayer(layerId);
const source = map.getSource(sourceId);
if (!source) { console.error(`[SOURCE MISSING] ${sourceId}`); updateUIState(layerId, 'FAIL'); state.loading = false; return; }
source.setData({ type: 'FeatureCollection', features });
state.loaded = true; state.loading = false;
if (REPD_IDS.includes(layerId)) {
allREPDFeatures = features; buildSearchIndex();
function evalFilter(filter, props) {
if (!filter) return true;
const op = filter[0];
if (op === '==') { const v = filter[1][0] === 'get' ? props[filter[1][1]] : null; return String(v).toLowerCase() === String(filter[2]).toLowerCase(); }
if (op === 'all') { return filter.slice(1).every(f => evalFilter(f, props)); }
if (op === '>=') { const v = filter[1][0] === 'coalesce' ? (parseFloat(props[filter[1][1][1]]) || 0) : 0; return v >= filter[2]; }
return true;
}
REPD_IDS.forEach(id => {
if (!RUNTIME_STATE[id]) return;
RUNTIME_STATE[id].loaded = true; RUNTIME_STATE[id].loading = false;
const lCfg = getLayerConfig(id);
const filtered = lCfg && lCfg.filter ? features.filter(f => evalFilter(lCfg.filter, f.properties)) : features.filter(f => f.properties.tech === id);
const idStats = filtered.reduce((acc, f) => {
acc.count++;
acc.mw += parseFloat(f.properties.capacity) || 0;
return acc;
}, { count: 0, mw: 0 });
updateUIState(id, idStats.count > 0 ? 'OK' : 'EMPTY', idStats.count > 0 ? idStats : null);
});
if (statusMode) { toggleStatusMode(); toggleStatusMode(); }
} else if (layerId === 'naei_co2') {
const stats = features.reduce((acc, f) => {
acc.count++;
acc.mw += parseFloat(f.properties.emission_tco2e) || 0;
return acc;
}, { count: 0, mw: 0 });
updateUIState(layerId, stats.count > 0 ? 'OK' : 'EMPTY', stats.count > 0 ? stats : null);
} else if (TRANSIT_IDS.includes(layerId)) {
updateTransitSourceStates(TRANSIT_SOURCE_MAP[layerId], features);
} else {
updateUIState(layerId, 'OK');
}
} catch (err) { console.error(`[LAYER FAILED] ${layerId}:`, err); state.loading = false; updateUIState(layerId, 'FAIL'); }
});
}
map.on('load', () => {
buildDOM();
map.addSource('sat-s', { type: 'raster', tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'], tileSize: 256 });
map.addLayer({ id: 'l-sat', type: 'raster', source: 'sat-s', layout: { visibility: 'none' } });
map.addSource('src-radius-circle', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-radius-circle-fill', type: 'fill', source: 'src-radius-circle', paint: { 'fill-color': '#00ffff', 'fill-opacity': 0.04 } });
map.addLayer({ id: 'l-radius-circle-stroke', type: 'line', source: 'src-radius-circle', paint: { 'line-color': '#00ffff', 'line-width': 1.5, 'line-opacity': 0.7, 'line-dasharray': [4, 3] } });
map.addSource('src-radius-area', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-radius-area-fill', type: 'fill', source: 'src-radius-area', paint: { 'fill-color': '#ff00ff', 'fill-opacity': 0.08 } });
map.addLayer({ id: 'l-radius-area-stroke', type: 'line', source: 'src-radius-area', paint: { 'line-color': '#ff00ff', 'line-width': 1.5, 'line-opacity': 0.8, 'line-dasharray': [2, 2] } });
map.addSource('src-measure-line', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-measure-fill', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-measure-points', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-measure-fill', type: 'fill', source: 'src-measure-fill', paint: { 'fill-color': '#ffff00', 'fill-opacity': 0.08 } });
map.addLayer({ id: 'l-measure-line', type: 'line', source: 'src-measure-line', paint: { 'line-color': '#ffff00', 'line-width': 2, 'line-dasharray': [3, 2] } });
map.addLayer({ id: 'l-measure-points', type: 'circle', source: 'src-measure-points', paint: { 'circle-color': '#ffff00', 'circle-radius': 5, 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000' } });
map.addSource('src-zonedraw-fill', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-zonedraw-line', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-zonedraw-points', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-zonedraw-fill', type: 'fill', source: 'src-zonedraw-fill', paint: { 'fill-color': '#ff6600', 'fill-opacity': 0.18 } });
map.addLayer({ id: 'l-zonedraw-line', type: 'line', source: 'src-zonedraw-line', paint: { 'line-color': '#ff6600', 'line-width': 3, 'line-dasharray': [4, 2] } });
map.addLayer({ id: 'l-zonedraw-points', type: 'circle', source: 'src-zonedraw-points', paint: {
'circle-color': ['case', ['==', ['get', 'kind'], 'vertex'], '#ffb14d', '#c96a12'],
'circle-radius': ['case', ['==', ['get', 'kind'], 'vertex'], 11, 5],
'circle-stroke-width': ['case', ['==', ['get', 'kind'], 'vertex'], 3, 1.5],
'circle-stroke-color': ['case', ['==', ['get', 'kind'], 'vertex'], '#ffffff', '#3a1c00'],
'circle-opacity': ['case', ['==', ['get', 'kind'], 'vertex'], 1, 0.75]
} });
const allLayerIds = [];
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
if (REPD_IDS.includes(layer.id) || TRANSIT_IDS.includes(layer.id) || layer.id === 'ev' || layer.id === 'naei_co2') return;
if (layer.id === '400') {
map.addSource('src-400', {
type: 'geojson',
data: '../cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson'
});
} else {
map.addSource(`src-${layer.id}`, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
}
const layerObject = {
id: `l-${layer.id}`, type: layer.type === 'line' ? 'line' : 'circle', source: `src-${layer.id}`, layout: { visibility: 'none' },
paint: layer.type === 'line' ? { 'line-color': layer.color, 'line-width': layer.width } : { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000' }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${layer.id}`);
});
});
map.addSource('src-naei_co2', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({
id: `l-naei_co2-glow`,
type: 'circle',
source: 'src-naei_co2',
filter: ['>=', ['coalesce', ['get', 'emission_tco2e'], 0], 50000],
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,20,200000,40,1000000,60,5000000,90],
'circle-opacity': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,0.15,200000,0.25,1000000,0.35],
'circle-blur': 1.0,
'circle-stroke-width': 0
}
});
map.addLayer({
id: 'l-naei_co2',
type: 'circle',
source: 'src-naei_co2',
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,'#ffcc00',50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,6,50000,10,200000,14,1000000,20,5000000,28],
'circle-stroke-width': 1.5,
'circle-stroke-color': '#000',
'circle-opacity': 0.85
}
});
allLayerIds.push('l-naei_co2-glow', 'l-naei_co2');
Object.keys(TRANSIT_URLS).forEach(sourceId => { map.addSource(sourceId, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } }); });
TRANSIT_IDS.forEach(id => {
const layer = getLayerConfig(id);
const layerObject = {
id: `l-${id}`, type: 'circle', source: TRANSIT_SOURCE_MAP[id], layout: { visibility: 'none' },
paint: { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${id}`);
});
map.addSource('src-ev', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-ev', type: 'circle', source: 'src-ev', layout: { visibility: 'none' }, paint: { 'circle-color': '#00ff88', 'circle-radius': 5, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 } });
allLayerIds.push('l-ev');
map.addSource('src-repd', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
REPD_IDS.forEach(id => {
const layer = getLayerConfig(id);
if (id === 'solar_roof') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 1.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],1.0,26,2  … [line shortened here: 497 characters; full line on GitHub]
}
if (id === 'solar') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 4.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],4.0,'#ffff00',20.0,'#ffaa00',50.0,'#ff4400',200.0,'#ff0000'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capac  … [line shortened here: 622 characters; full line on GitHub]
}
if (id === 'solar_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#00ff88',50.0,'#00cc66',200.0,'#009944',350.0,'#006622'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','ca  … [line shortened here: 629 characters; full line on GitHub]
}
if (id === 'bess_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#ffb3d9',50.0,'#ff69b4',200.0,'#ff1493',350.0,'#cc0066'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','ca  … [line shortened here: 629 characters; full line on GitHub]
}
if (id === 'wind_onshore_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ffee',50.0,'#00ffcc',200.0,'#00ccaa',350.0,'#008877'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','ca  … [line shortened here: 629 characters; full line on GitHub]
}
if (id === 'wind_offshore_operational') {
map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ccff',50.0,'#3399ff',200.0,'#0055dd',350.0,'#003399'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','ca  … [line shortened here: 629 characters; full line on GitHub]
}
const circlePaint = id === 'solar_roof'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffcc00',0.99,'#ffcc00',1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,7,0.5,7,0.99,8,1.0,16,2.0,18,5.0,22,10.0,28], 'circle-stroke-width': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,1,0.99,1,1.0,2], 'circle-stroke-color'  … [line shortened here: 433 characters; full line on GitHub]
: id === 'solar'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffff00',20.0,'#ffcc00',50.0,'#ffaa00',200.0,'#ff6600',500.0,'#ff2200'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 }
: id === 'solar_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#66ff99',10,'#33ff77',50,'#00dd55',100,'#00bb44',200,'#008833',350,'#006622',500,'#004411'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,10,10,14,50,18,100,22,200,28,350,35,500,42], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'bess_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffccee',10,'#ffb3d9',50,'#ff69b4',100,'#ff1493',200,'#dd0077',350,'#990066',500,'#660044'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'wind_onshore_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ccfff5',10,'#99ffee',50,'#00ffcc',100,'#00ddaa',200,'#00aa88',350,'#007766',500,'#004433'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: id === 'wind_offshore_operational'
? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#cce5ff',10,'#99ccff',50,'#3399ff',100,'#0066ee',200,'#0044bb',350,'#003399',500,'#001166'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
: { 'circle-color': layer.color, 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 };
map.addLayer({ id: `l-${id}`, type: 'circle', source: 'src-repd', filter: layer.filter, layout: { visibility: 'none' }, paint: circlePaint });
allLayerIds.push(`l-${id}`);
});
_rebuildVisibleCache(allLayerIds);
let _pendingToolClick = null;
map.getCanvas().addEventListener('mousedown', e => {
if (!zoneDrawMode) return;
const lngLat = map.unproject([e.offsetX, e.offsetY]);
_zoneDrawOnMouseDown({ lngLat, preventDefault: () => e.preventDefault() });
});
map.on('zoomend', () => {
if (zoneDrawMode && zoneDrawPoints.length >= 3) _zoneDrawUpdateLayers(false, true);
});
(function attachZoneTouch() {
const canvas = map.getCanvas();
const pointOf = touch => {
const r = canvas.getBoundingClientRect();
return map.unproject([touch.clientX - r.left, touch.clientY - r.top]);
};
canvas.addEventListener('touchstart', e => {
if (!zoneDrawMode || e.touches.length !== 1) return;
_zoneDrawOnMouseDown({ lngLat: pointOf(e.touches[0]), preventDefault: () => {} });
if (zoneDrawDragging) e.preventDefault();
}, { passive: false });
canvas.addEventListener('touchmove', e => {
if (!zoneDrawMode || !zoneDrawDragging || e.touches.length !== 1) return;
e.preventDefault();
_zoneDrawOnMouseMove({ lngLat: pointOf(e.touches[0]) });
}, { passive: false });
const endTouch = () => { if (zoneDrawMode && zoneDrawDragging) _zoneDrawOnMouseUp(); };
canvas.addEventListener('touchend', endTouch);
canvas.addEventListener('touchcancel', endTouch);
})();
map.on('click', e => {
if (measureMode) {
_pendingToolClick = setTimeout(() => {
_pendingToolClick = null;
if (!measureClosed) {
measurePoints.push([e.lngLat.lng, e.lngLat.lat]);
updateMeasureLayers();
updateMeasureDisplay();
}
}, CLICK_DEBOUNCE_MS);
return;
}
if (zoneDrawMode) { _zoneDrawOnClick(e); return; }
if (radiusMode) { doRadiusSearch(e.lngLat.lng, e.lngLat.lat); return; }
if (radiusAreaMode) { doRadiusAreaMeasure(e.lngLat.lng, e.lngLat.lat); return; }
if (!_visibleInteractiveIds.length) return;
const features = map.queryRenderedFeatures(e.point, { layers: _visibleInteractiveIds });
if (!features.length) return;
const p = features[0].properties || {}; const name = p.name || p.SiteName || p['Site Name'] || 'Unnamed Asset';
if (p.type === 'supermarket') {
const address = [p.street, p.city, p.postcode].filter(Boolean).join(', '); const area = p.area_m2 ? `${p.area_m2.toLocaleString()} m²` : '';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:${p.colour || '#00ffff'};font-size:13px">${escapeHTML(p.brand || name)}</b><br>${p.name && p.name !== p.brand ? `<span style="color:#fff">${escapeHTML(p.name)}</span><br>` : ''}<span style="color:#888">${escapeHTML(address)}</span><br>${area ? `<span style="color:#ffae00">Area: ${escapeHTML(area)}</  … [line shortened here: 429 characters; full line on GitHub]
}
if (p.type === 'elizabeth_line_station') {
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#60399E;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">Elizabeth Line Station</span><br><span style="color:#555;font-size:10px">${escapeHTML(p.operator)}</span></div>`); return;
}
if (p.type === 'stadium') {
const club = p.club ? `<span style="color:#fff">${escapeHTML(p.club)}</span><br>` : ''; const cap = p.capacity && p.capacity !== "Unknown" ? `Capacity: ${Number(p.capacity).toLocaleString()}` : 'Capacity: Unknown';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#e5ff00;font-size:13px">${escapeHTML(name)}</b><br>${club}<span style="color:#888">${escapeHTML(p.sport)}</span><br><span style="color:#ffae00">${escapeHTML(cap)}</span></div>`); return;
}
if (p.type === 'naei_emitter') {
const tonnes = p.emission_tco2e ? Number(p.emission_tco2e).toLocaleString('en-GB', { maximumFractionDigits: 0 }) : 'Unknown';
const dataLabel = p.datatype === 'O' ? 'Self-reported by the company' : p.datatype === 'M' ? 'Estimated by the government' : 'Official figures';
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:8px 10px;border:1px solid #ff4400;border-radius:4px;min-width:220px;max-width:280px"><b style="color:#ff4400;font-size:13px">🏭 ${escapeHTML(name)}</b><br><span style="color:#888;font-size:10px">Run by: ${escapeHTML(p.operator || 'Unknown')}</span><br><span style="color:#aaa;font-size:10px">Industry: ${escapeHTML(p.secto  … [line shortened here: 936 characters; full line on GitHub]
}
const tech = p.tech || ''; const rawTech = p.raw_tech || p.type || tech; const voltage = p.voltage || ''; const capacity = parseFloat(p.capacity) || 0; const powerKw = p.power_kw || null; const connectors = p.connectors || ''; const status = p.status || ''; const operator = p.operator || ''; const mounting = (p.mounting && p.mounting !== 'nan') ? ` | ${escapeHTML(p.mounting)}` : ''; const capStr =  … [line shortened here: 796 characters; full line on GitHub]
openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">${escapeHTML(rawTech)}${voltage ? ` | ${escapeHTML(voltage)}` : ''}${mounting}</span><br>${evFields}${capStr ? `<span style="color:#ffae00">${escapeHTML(capStr)}</span>` : ''}${status ? `<span style="color:${statusCol};font-  … [line shortened here: 566 characters; full line on GitHub]
});
map.on('dblclick', e => {
if (_pendingToolClick) { clearTimeout(_pendingToolClick); _pendingToolClick = null; }
if (zoneDrawMode) { e.preventDefault(); return; }
if (!measureMode || measurePoints.length < 2) return;
e.preventDefault();
measureClosed = true;
updateMeasureLayers();
updateMeasureDisplay();
});
window.addEventListener('mouseup', () => { if (zoneDrawMode) _zoneDrawOnMouseUp(); });
map.on('mousemove', e => {
if (zoneDrawMode) { _zoneDrawOnMouseMove(e); return; }
if (measureMode || radiusMode || radiusAreaMode) { map.getCanvas().style.cursor = 'crosshair'; return; }
if (!_visibleHoverIds.length) { map.getCanvas().style.cursor = ''; return; }
const now = Date.now();
if (now - _lastHoverMs < HOVER_THROTTLE_MS) return;
_lastHoverMs = now;
if (_lastMouseMoveRaf) return;
_lastMouseMoveRaf = requestAnimationFrame(() => {
_lastMouseMoveRaf = null;
const features = map.queryRenderedFeatures(e.point, { layers: _visibleHoverIds });
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
});
});
GRID_CONFIG.forEach(group => { group.layers.forEach(layer => { if (layer.preload && layer.id !== '400') hydrateLayer(layer.id); }); });
const state400 = RUNTIME_STATE['400'];
if (state400) { state400.loaded = true; state400.loading = false; updateUIState('400', 'OK'); }
focusCanonicalProjectDeepLink();
});
};
(() => {
'use strict';
const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
if (NS.geodesy) return;
const EARTH_RADIUS_KM = 6378.137;
const DEG = Math.PI / 180;
function distanceKm(lon1, lat1, lon2, lat2) {
const dLat = (lat2 - lat1) * DEG;
const dLon = (lon2 - lon1) * DEG;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
function representativePoint(geometry) {
if (!geometry) return null;
const { type, coordinates } = geometry;
if (type === 'Point') {
return Array.isArray(coordinates) && coordinates.length >= 2
? [coordinates[0], coordinates[1]] : null;
}
const ring = type === 'Polygon' ? coordinates && coordinates[0]
: type === 'MultiPolygon' ? coordinates && coordinates[0] && coordinates[0][0]
: null;
if (!Array.isArray(ring) || !ring.length) return null;
let sumLon = 0;
let sumLat = 0;
for (const point of ring) {
sumLon += point[0];
sumLat += point[1];
}
return [sumLon / ring.length, sumLat / ring.length];
}
function voltagesKv(properties) {
if (!properties) return [];
const out = [];
const explicit = properties.kv ?? properties.KV;
if (explicit != null && String(explicit).trim() !== '') {
for (const token of String(explicit).match(/\d+(?:\.\d+)?/g) || []) {
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value);
}
}
const volts = properties.voltage ?? properties.VOLTAGE;
if (volts != null) {
for (const token of String(volts).match(/\d+(?:\.\d+)?/g) || []) {
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value / 1000);
}
}
return [...new Set(out)].sort((a, b) => b - a);
}
function destinationPoint(lon, lat, km, bearingDeg) {
const ad = km / EARTH_RADIUS_KM;
const brg = bearingDeg * DEG;
const p1 = lat * DEG;
const p2 = Math.asin(Math.sin(p1) * Math.cos(ad)
+ Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
const l2 = lon * DEG + Math.atan2(
Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
return [l2 / DEG, p2 / DEG];
}
function initialBearingDeg(lon1, lat1, lon2, lat2) {
const p1 = lat1 * DEG; const p2 = lat2 * DEG;
const dl = (lon2 - lon1) * DEG;
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return (Math.atan2(y, x) / DEG + 360) % 360;
}
NS.geodesy = Object.freeze({
schema: 'gridatlas.module.geodesy.v1',
EARTH_RADIUS_KM,
distanceKm,
destinationPoint,
initialBearingDeg,
representativePoint,
voltagesKv
});
})();
(() => {
'use strict';
const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
if (NS.networkTopology) return;
const ACCEPTS = 'data-grid-gb.transmission-network.v1';
const NOT_AN_ASSESSMENT =
'Counts, lengths, ratings and impedances are what the network operator '
+ 'publishes about this site. None of them states whether any project can '
+ 'connect here, which depends on queue position, committed connections, '
+ 'consent and commercial terms that no published appendix contains.';
const IMPEDANCE_BASIS =
'R, X and B are percentages on a 100 MVA base, as published. They are '
+ 'network parameters, not a solved power flow.';
const UNDECLARED = 'undeclared';
function voltageOf(node) {
if (!node) return null;
if (node.voltage_consistent_with_site !== true) return null;
return Number.isFinite(node.voltage_kv) ? node.voltage_kv : null;
}
const bandKey = (kv) => (kv == null ? UNDECLARED : String(kv));
function ratingsOf(row) {
const seasons = { winter: row.winter_mva, spring: row.spring_mva,
summer: row.summer_mva, autumn: row.autumn_mva };
const published = {};
for (const [season, value] of Object.entries(seasons)) {
if (Number.isFinite(value)) published[season] = value;
}
return Object.keys(published).length ? published : null;
}
function physicalUnits(records) {
const pairs = new Map();
for (const record of records) {
const near = String(record.from_node);
const far = String(record.to_node);
const forward = near < far;
const key = forward ? near + '\u0000' + far : far + '\u0000' + near;
if (!pairs.has(key)) pairs.set(key, { forward: 0, reverse: 0 });
const seen = pairs.get(key);
if (forward) seen.forward += 1; else seen.reverse += 1;
}
let units = 0;
for (const seen of pairs.values()) {
units += (seen.forward && seen.reverse)
? Math.max(seen.forward, seen.reverse)
: seen.forward + seen.reverse;
}
return units;
}
function parametersOf(row) {
const published = {};
for (const [key, field] of [['r_pct', 'r_pct_100mva'], ['x_pct', 'x_pct_100mva'],
['b_pct', 'b_pct_100mva']]) {
if (Number.isFinite(row[field])) published[key] = row[field];
}
return Object.keys(published).length ? published : null;
}
function index(product) {
if (!product || product.schema !== ACCEPTS) return null;
const nodes = new Map();
for (const node of product.nodes || []) {
if (node && node.node) nodes.set(node.node, node);
}
const sitesByCode = new Map();
const sitesByName = new Map();
for (const site of product.sites || []) {
if (!site || !site.code) continue;
sitesByCode.set(String(site.code).toUpperCase(), site);
if (site.name) sitesByName.set(String(site.name).toUpperCase().trim(), site);
}
const byNode = new Map();
function land(nodeName, entry) {
if (!nodeName) return;
if (!byNode.has(nodeName)) byNode.set(nodeName, []);
byNode.get(nodeName).push(entry);
}
for (const [kind, rows] of [['circuit', product.circuits],
['transformer', product.transformers], ['planned_change', product.planned_changes]]) {
for (const row of rows || []) {
if (!row) continue;
land(row.node_1, { kind, row, near: 'node_1', far: 'node_2' });
land(row.node_2, { kind, row, near: 'node_2', far: 'node_1' });
}
}
function siteOf(nodeName) {
const node = nodes.get(nodeName);
return node ? node.site_code : null;
}
function graph() {
return {
schema: 'gridatlas.module.network-topology.graph.v1',
has: (name) => nodes.has(name),