In this section
- Substation Finder — Si Page geodesy · code-generator / apps/substation-finder/Si/index.html lines 4711–5013
- Ventus Core geodesy · code-generator / apps/substation-finder/Si/ventus-core.js lines 1–397
Substation Finder — Si Page
A map page in Code Generator that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine. Published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
geodesycode-generator / apps/substation-finder/Si/index.html · lines 4711–5013 of 5013 (continued from section 295) · Entry point · pattern enterFullscreen (shared by 2 files)
- What it does
- It maps grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 104 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_11kv_ukpn.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson. Out: JSON file manifest_v4.json; web page; interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
- What it achieves
- It normalizes status (`normalizeStatus`), toggles curtain (`toggleCurtain`) and gets radius (`getRadiusValue`). 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 132 kV, 220 kV and 275 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder/Si · page
- 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.
- Uses
- https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js
- Used by
- mentioned in Standalone (comment link)
- Produces
- deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen, toggleCurtain, getRadiusValue, validateRadiusInput, fmt, updateMeasureDisplay, updateMeasureLayers, clearMeasure
- Defines here
- deepFreeze, updateUIState, FetchQueue, fetchWithTimeout, fetchAndParseGeoJSON, fetchAndParseCSV, snapLines, buildDOM, hydrateLayer
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/index.html:4711-5013 · blob 4e9b8b6a923698ac72c91325688593fcae31ffb3 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
if (typeof maplibregl === 'undefined' || typeof Papa === 'undefined') {
document.getElementById('fatal-banner').style.display = 'block';
throw new Error('CRITICAL: Core scripts 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);
}
const GRID_CONFIG = deepFreeze([
{
group: "Topology (GeoJSON)",
layers: [
{ id: "400", label: "400kV", color: "#0054ff", type: "line", width: 2.5, url: "/grid_400kv.geojson", snap: true, preload: true },
{ id: "275", label: "275kV", color: "#ff0000", type: "line", width: 2.0, url: "/grid_275kv.geojson", snap: true, preload: true },
{ id: "220", label: "220kV", color: "#ff9900", type: "line", width: 1.8, url: "/grid_220kv.geojson", snap: true, preload: true },
{ id: "132", label: "132kV", color: "#00cc00", type: "line", width: 1.5, url: "/grid_132kv.geojson", snap: true, preload: true },
{ id: "66", label: "66kV", color: "#b200ff", type: "line", width: 1.2, url: "/grid_66kv.geojson", snap: true, preload: true },
{ id: "subs", label: "Subs", color: "#ffffff", type: "point", radius: 4.5, url: "/grid_substations.geojson", isSubs: true, preload: true }
]
},
{
group: "Assets (GeoJSON)",
layers: [
{ id: "nuc", label: "Nuclear", color: "#39ff14", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['==', ['get','source'], 'nuclear'], preload: true },
{ id: "gas", label: "Gas", color: "#ff4500", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['!=', ['get','source'], 'nuclear'], preload: true },
{ id: "ind", label: "Industry", color: "#ff6600", type: "point", radius: 4.5, url: "/industrial_offtakers.geojson", preload: true },
{ id: "dc", label: "Data Ctrs",color: "#00ffff", type: "point", radius: 4.5, url: "/datacentres.geojson", preload: true },
{ id: "air", label: "Airports", color: "#ff00ff", type: "point", radius: 4.5, url: "/airports.geojson", preload: true },
{ id: "rail", label: "Railways", color: "#ffd700", type: "point", radius: 4.5, url: "/railways.geojson", preload: true }
]
},
{
group: "REPD (CSV Parser Active)",
layers: [
{ id: "solar", label: "Solar PV", color: "#ffff00", type: "csv", radius: 4.5, url: "/repd-solar-operational.csv", preload: false },
{ id: "wind", label: "Wind Farm", color: "#00ffff", type: "csv", radius: 4.5, url: "/repd.csv", preload: false },
{ id: "bess", label: "BESS Storage", color: "#ffae00", type: "csv", radius: 4.5, url: "/repd-grid-batteries.csv", preload: false }
]
}
]);
const RUNTIME_STATE = {};
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
});
});
setInterval(() => {
const now = new Date();
document.getElementById('clock').innerText = now.toLocaleTimeString('en-GB');
document.getElementById('days').innerText = Math.floor((new Date('2050-01-01') - now) / 86400000) + ' DAYS';
}, 1000);
const map = new maplibregl.Map({
container: 'map',
style: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
center: [-3.5, 54.0],
zoom: 4.2,
attributionControl: false
});
new ResizeObserver(() => map.resize()).observe(document.getElementById('map'));
function updateUIState(id, state) {
RUNTIME_STATE[id].status = state;
const span = document.getElementById(`lbl-${id}`);
if (span) {
const baseText = span.getAttribute('data-base-label');
span.innerText = `${baseText} [${state}]`;
span.style.opacity = state === 'FAIL' ? '0.5' : '1';
}
}
class FetchQueue {
constructor(concurrency) {
this.concurrency = concurrency;
this.active = 0;
this.queue = [];
}
async add(task) {
if (this.active >= this.concurrency) await new Promise(resolve => this.queue.push(resolve));
this.active++;
try { return await task(); }
finally {
this.active--;
if (this.queue.length > 0) this.queue.shift()();
}
}
}
const networkQueue = new FetchQueue(4);
const urlCache = {};
let globalSubsData = null;
async function fetchWithTimeout(url, ms = 8000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(id);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response;
} catch (err) {
clearTimeout(id);
throw err;
}
}
async function fetchAndParseGeoJSON(url) {
if (urlCache[url]) return await urlCache[url];
const promise = fetchWithTimeout(url).then(res => res.json()).then(data => Array.isArray(data.features) ? data.features : []);
urlCache[url] = promise;
return promise;
}
async function fetchAndParseCSV(url) {
if (urlCache[url]) return await urlCache[url];
const promise = fetchWithTimeout(url).then(res => res.text()).then(csvText => {
return new Promise((resolve, reject) => {
Papa.parse(csvText, {
header: true, skipEmptyLines: true, dynamicTyping: true,
complete: res => {
const features = [];
res.data.forEach(row => {
const lat = row.Lat || row.lat || row.Latitude || row.latitude || row.Y || row.y;
const lon = row.Lon || row.lon || row.Longitude || row.longitude || row.X || row.x;
if (lat && lon && isFinite(lat) && isFinite(lon)) {
features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: [+lon, +lat] }, properties: row });
}
});
resolve(features);
},
error: err => reject(err)
});
});
});
urlCache[url] = promise;
return promise;
}
function snapLines(features, subs) {
if (!subs || !subs.length) return features;
const tol = 0.05, rad = Math.PI / 180;
features.forEach(f => {
const c = f.geometry && f.geometry.coordinates;
if (!c || c.length < 2) return;
[0, c.length - 1].forEach(i => {
let best = c[i], min = Infinity;
const latCos = Math.cos(c[i][1] * rad);
subs.forEach(s => {
const sc = s.geometry.coordinates;
const dx = (c[i][0] - sc[0]) * latCos, dy = (c[i][1] - sc[1]);
const d = (dx * dx) + (dy * dy);
if (d < min && d < tol * tol) { min = d; best = sc; }
});
c[i] = best;
});
});
return features;
}
function buildDOM() {
const container = document.getElementById('scada-ui-container');
container.innerHTML = '';
const fragment = document.createDocumentFragment();
GRID_CONFIG.forEach(group => {
const groupDiv = document.createElement('div');
groupDiv.className = 'key-group';
groupDiv.innerHTML = `<div class="key-title">${group.group}</div>`;
group.layers.forEach(layer => {
const label = document.createElement('label');
label.className = 'key-item';
const input = document.createElement('input');
input.type = 'checkbox';
input.dataset.layerId = layer.id;
const span = document.createElement('span');
span.id = `lbl-${layer.id}`;
span.setAttribute('data-base-label', layer.label);
span.style.color = layer.color;
span.innerText = `${layer.label} [WAIT]`;
label.appendChild(input);
label.appendChild(document.createTextNode(' '));
label.appendChild(span);
groupDiv.appendChild(label);
});
fragment.appendChild(groupDiv);
});
const bmGroup = document.createElement('div');
bmGroup.className = 'key-group';
bmGroup.innerHTML = `
<div class="key-title">Basemap</div>
<label class="key-item"><input type="radio" name="bm" value="dark" checked> Dark</label>
<label class="key-item"><input type="radio" name="bm" value="sat"> Satellite</label>
`;
fragment.appendChild(bmGroup);
container.appendChild(fragment);
container.addEventListener('change', e => {
if (e.target.type === 'checkbox' && e.target.dataset.layerId) {
const layerId = e.target.dataset.layerId;
const isVisible = e.target.checked;
map.setLayoutProperty(`l-${layerId}`, 'visibility', isVisible ? 'visible' : 'none');
if (isVisible) hydrateLayer(layerId);
} else if (e.target.name === 'bm') {
map.setLayoutProperty('l-sat', 'visibility', e.target.value === 'sat' ? 'visible' : 'none');
}
});
}
async function hydrateLayer(layerId) {
const state = RUNTIME_STATE[layerId];
if (state.loaded || state.loading) return;
state.loading = true;
const layerConfig = GRID_CONFIG.flatMap(g => g.layers).find(l => l.id === layerId);
await networkQueue.add(async () => {
try {
let features = layerConfig.type === 'csv' ? await fetchAndParseCSV(layerConfig.url) : await fetchAndParseGeoJSON(layerConfig.url);
if (features.length === 0) {
updateUIState(layerId, 'EMPTY');
return;
}
if (layerConfig.isSubs) globalSubsData = features;
if (layerConfig.snap && globalSubsData) features = snapLines(features, globalSubsData);
map.getSource(`src-${layerId}`).setData({ type: 'FeatureCollection', features });
state.loaded = true;
updateUIState(layerId, 'OK');
} catch (err) {
console.error(`[LAYER FAILED] ${layerId}:`, err);
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' } });
const allLayerIds = [];
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
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;
map.addLayer(layerObject);
allLayerIds.push(`l-${layer.id}`);
});
});
map.on('click', e => {
const features = map.queryRenderedFeatures(e.point, { layers: allLayerIds });
if (!features.length) return;
const p = features[0].properties;
const name = p.name || p.SiteName || p['Site Name'] || 'Unnamed Asset';
const info = p.operator || p.capacity || p['Installed Capacity (MWelec)'] || p.voltage || 'Data Node';
new maplibregl.Popup({ maxWidth: '250px' })
.setLngLat(e.lngLat)
.setHTML(`<div style="font-family:monospace;color:#000"><b>${name}</b><br><span style="color:#444">${info}</span></div>`)
.addTo(map);
});
map.on('mousemove', e => {
const features = map.queryRenderedFeatures(e.point, { layers: allLayerIds });
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
});
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
if (layer.preload) hydrateLayer(layer.id);
});
});
});
</script>
</body>
</html>Ventus Core
A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line, london underground, UK metros trams and HS2, using haversine. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
Set aside from the main view: 96% of its lines are the same as apps/substation-finder/Si/ventus-corev6engine.js (code-generator), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Ventus Corev6engine; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9612 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/ventus-corev6engine.js:1-1341 41bcb30d5f403645ae06cf85b4a340acd6beddb9
- sha256 43fb9d6c635dd24833a945ed12710fb5c65ae1a560277eb4deaa504a1983eb5b
- target sha256 c8f6e2e4c2f443114f8ad964f0207136310d2ded80c1e8d9ed44c9d59f46243a
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesycode-generator / apps/substation-finder/Si/ventus-core.js · lines 1–397 of 1315 · Entry point · pattern _zoneDrawShowPopupDebounced (shared by 16 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 56 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json; form fields (user input). Out: interactive map. Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v5 Page (globalgrid2050, https://globalgrid2050.com/repd_grid_atlasv5/). Reached from 95 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V030 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v030.html). It is itself an entry point, published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
- What it achieves
- It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). 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). It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- Loaded by the Renewable Energy Planning Database (REPD) Grid Atlas v5 page in GlobalGrid2050 at https://globalgrid2050.com/repd_grid_atlasv5/.
- Application
- code-generator · apps/substation-finder/Si · 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.
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v5 Page (script src)
- Produces
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear, zoneDrawUndo, toggleZoneDrawMode, _zoneDrawNearVertex, _zoneDrawNearEdgeDot, _zoneDrawOnClick, _zoneDrawOnMouseDown, _zoneDrawOnMouseMove, _zoneDrawOnMouseUp, openPopup, closeActivePopup
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/ventus-core.js:1-397 · blob 3d972d212f4a50ff8af06e94812784883cc5ac0d · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
'use strict';
window.initVentusMap = function({ config, center, zoom }) {
if (typeof maplibregl === 'undefined') {
document.getElementById('fatal-banner').style.display = 'block';
throw new Error('CRITICAL: MapLibre failed to load.');
}
// ── Utilities ────────────────────────────────────────────────────────────────
function deepFreeze(obj) {
Object.keys(obj).forEach(prop => {
if (typeof obj[prop] === 'object' && obj[prop] !== null) deepFreeze(obj[prop]);
});
return Object.freeze(obj);
}
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
}
function normalizeStatus(status) {
return String(status ?? '').trim().toLowerCase();
}
function fmt(n, decimals) {
return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}
// ── Earth model ───────────────────────────────────────────────────────────────
// WGS84 equatorial radius — used consistently throughout all geometry,
// area calculations, and the geodesic cap limit.
// MAX_RADIUS_KM = π × R = 20,037.508 km (equatorial half-circumference).
const EARTH_RADIUS_KM = 6378.137;
const MAX_RADIUS_KM = Math.PI * EARTH_RADIUS_KM; // 20037.508 km
// ── V5.1: Named constants — single source of truth for tunable values ────────
const DEG_TO_RAD = Math.PI / 180;
const HIT_RADIUS_VERTEX_PX = 18; // px — vertex grab target radius
const HIT_RADIUS_EDGE_PX = 22; // px — edge midpoint grab target radius
const CLICK_DEBOUNCE_MS = 220; // ms — dblclick ghost-vertex guard
const HOVER_THROTTLE_MS = 100; // ms — mousemove query cadence
const POPUP_MAX_WIDTH = '300px';
const ZONE_DRAW_VERTICES = 24; // vertices in initial circle
const ZONE_DRAW_DEFAULT_KM = 0.337; // ~50 football pitches starting radius
function haversine(lon1, lat1, lon2, lat2) {
const R = EARTH_RADIUS_KM, r = Math.PI / 180;
const dLat = (lat2 - lat1) * r, dLon = (lon2 - lon1) * r;
const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
// ── Config Loading ────────────────────────────────────────────────────────────
const GRID_CONFIG = deepFreeze(config);
const RUNTIME_STATE = {};
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
});
});
// V5.1: O(1) layer config lookup — replaces repeated flatMap(…).find(…) calls
const layerConfigById = new Map(
GRID_CONFIG.flatMap(g => g.layers).map(l => [l.id, l])
);
const REPD_IDS = ['solar','solar_roof','wind','bess','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;
// RADIUS AREA STATE
let radiusAreaMode = false;
let radiusAreaMarker = null;
let radiusAreaCenter = null;
// ── ZONE DRAW STATE ───────────────────────────────────────────────────────────
// Circle → draggable polygon tool.
// Click places a 24-vertex circle at 50-pitch radius. Drag any vertex to deform.
// Radius input (up to 20,037.508 km — WGS84 equatorial half-circumference) sets circle size before first click.
// Auto-zooms on placement so the shape fills the viewport.
const ZONE_DRAW_MAX_KM = MAX_RADIUS_KM;
let zoneDrawMode = false;
let zoneDrawPoints = []; // [lon, lat] vertices
let zoneDrawDragging = false;
let zoneDrawDragIdx = -1;
let zoneDrawJustDragged = false;
let _zoneDrawCollapsed = false;
function _zoneDrawGetRadius() {
const input = document.getElementById('zonedraw-radius-input');
if (!input) return ZONE_DRAW_DEFAULT_KM;
const v = parseFloat(input.value);
if (isNaN(v) || v <= 0) return ZONE_DRAW_DEFAULT_KM;
if (v > ZONE_DRAW_MAX_KM) return ZONE_DRAW_MAX_KM;
return v;
}
function _zoneDrawCirclePoints(lon, lat, radiusKm, n) {
// Generate n evenly-spaced vertices on a geodesic circle
const R = EARTH_RADIUS_KM, DEG = Math.PI / 180;
const ad = radiusKm / R;
const lat1 = lat * DEG;
return Array.from({ length: n }, (_, i) => {
const b = (i / n) * 2 * Math.PI;
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(ad) + Math.cos(lat1) * Math.sin(ad) * Math.cos(b));
const lon2 = lon * DEG + Math.atan2(Math.sin(b) * Math.sin(ad) * Math.cos(lat1), Math.cos(ad) - Math.sin(lat1) * Math.sin(lat2));
return [lon2 / DEG, lat2 / DEG];
});
}
function _zoneDrawCalcArea(pts) {
if (pts.length < 3) return { areaKm2: 0, areaHa: 0, areaAc: 0, areaMi2: 0, areaM2: 0, perimKm: 0, pitches: 0 };
let area = 0;
const R = EARTH_RADIUS_KM;
for (let i = 0; i < pts.length; i++) {
const j = (i + 1) % pts.length;
const xi = pts[i][0] * Math.PI / 180, yi = pts[i][1] * Math.PI / 180;
const xj = pts[j][0] * Math.PI / 180, yj = pts[j][1] * Math.PI / 180;
area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
}
const areaKm2 = Math.abs(area) * R * R / 2;
let perimKm = 0;
for (let i = 0; i < pts.length; i++) perimKm += haversine(pts[i][0], pts[i][1], pts[(i+1)%pts.length][0], pts[(i+1)%pts.length][1]);
const areaM2 = areaKm2 * 1e6;
return { areaKm2, areaHa: areaM2 / 10000, areaAc: areaM2 / 4046.85642, areaMi2: areaKm2 * 0.386102, areaM2, perimKm, pitches: areaM2 / 7140 };
}
function _zoneDrawUpdateLayers(dragOnly) {
if (!map.getSource('src-zonedraw-fill')) return;
const n = zoneDrawPoints.length;
if (n < 3) {
['fill','line','points'].forEach(s => map.getSource(`src-zonedraw-${s}`).setData({ type: 'FeatureCollection', features: [] }));
return;
}
const ring = [...zoneDrawPoints, zoneDrawPoints[0]];
map.getSource('src-zonedraw-fill').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] } }] });
map.getSource('src-zonedraw-line').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'LineString', coordinates: ring } }] });
if (dragOnly) {
// Lightweight path — only move vertex dots
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 {
// Full rebuild — vertices + edge midpoints
const vFeatures = zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }));
const mFeatures = [];
zoneDrawPoints.forEach((c, i) => {
const b = zoneDrawPoints[(i + 1) % n];
[0.33, 0.5, 0.66].forEach(t => {
mFeatures.push({ type: 'Feature', properties: { kind: 'mid', edgeIdx: i, t }, geometry: { type: 'Point', coordinates: [c[0]+(b[0]-c[0])*t, c[1]+(b[1]-c[1])*t] } });
});
});
map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features: [...vFeatures, ...mFeatures] });
}
}
let _zoneDrawPopupRaf = null;
function _zoneDrawShowPopup() {
if (zoneDrawPoints.length < 3) return;
const { areaKm2, areaHa, areaAc, areaMi2, areaM2, perimKm, pitches } = _zoneDrawCalcArea(zoneDrawPoints);
const centLon = zoneDrawPoints.reduce((s, p) => s + p[0], 0) / zoneDrawPoints.length;
const centLat = zoneDrawPoints.reduce((s, p) => s + p[1], 0) / zoneDrawPoints.length;
if (_zoneDrawCollapsed) {
openPopup([centLon, centLat], `
<div onclick="window._zdExpand&&window._zdExpand()" style="font-family:monospace;background:#000;padding:5px 10px;border:1px solid #ff6600;border-radius:4px;cursor:pointer;color:#ff6600;font-size:11px;white-space:nowrap;">
◉ ${fmt(areaKm2,3)} km² · ⚽ ${fmt(pitches,0)} pitches ▾
</div>`);
window._zdExpand = () => { _zoneDrawCollapsed = false; _zoneDrawShowPopup(); };
} else {
openPopup([centLon, centLat], `
<div style="font-family:monospace;background:#000;padding:10px 12px;border:1px solid #ff6600;border-radius:4px;min-width:230px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
<b style="color:#ff6600;font-size:13px;">◉ Zone Draw</b>
<span onclick="window._zdCollapse&&window._zdCollapse()" style="color:#555;font-size:12px;cursor:pointer;padding:0 4px;user-select:none;" title="Collapse">▴ hide</span>
</div>
<div style="color:#ffae00;font-size:13px;margin-bottom:10px;">⚽ ${fmt(pitches,1)} football pitches</div>
<div style="display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:12px;">
<span style="color:#888;">Square Metres</span><span style="color:#fff;">${fmt(areaM2,0)}</span>
<span style="color:#888;">Hectares</span><span style="color:#fff;">${fmt(areaHa,2)}</span>
<span style="color:#888;">Acres</span><span style="color:#fff;">${fmt(areaAc,2)}</span>
<span style="color:#888;">Square Kilometres</span><span style="color:#fff;">${fmt(areaKm2,4)}</span>
<span style="color:#888;">Square Miles</span><span style="color:#fff;">${fmt(areaMi2,3)}</span>
<span style="color:#888;">Perimeter</span><span style="color:#fff;">${fmt(perimKm,2)} km</span>
</div>
<div style="color:#555;font-size:9px;margin-top:8px;">Drag vertices to reshape · Click edge dot to add point</div>
</div>`);
window._zdCollapse = () => { _zoneDrawCollapsed = true; _zoneDrawShowPopup(); };
}
}
function _zoneDrawShowPopupDebounced() {
if (_zoneDrawPopupRaf) return;
_zoneDrawPopupRaf = requestAnimationFrame(() => { _zoneDrawPopupRaf = null; _zoneDrawShowPopup(); });
}
function _zoneDrawClear() {
zoneDrawPoints = [];
zoneDrawDragging = false;
zoneDrawDragIdx = -1;
zoneDrawJustDragged = false;
_zoneDrawCollapsed = false;
window._zdExpand = null;
window._zdCollapse = null;
closeActivePopup();
_zoneDrawUpdateLayers(false);
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'none';
}
function zoneDrawUndo() {
if (zoneDrawPoints.length <= 3) { _zoneDrawClear(); return; }
zoneDrawPoints.pop();
_zoneDrawUpdateLayers(false);
_zoneDrawShowPopup();
}
function toggleZoneDrawMode() {
zoneDrawMode = !zoneDrawMode;
const btn = document.getElementById('btn-zonedraw');
if (btn) { btn.classList.toggle('active', zoneDrawMode); btn.setAttribute('aria-pressed', zoneDrawMode); }
map.getCanvas().style.cursor = zoneDrawMode ? 'crosshair' : '';
if (zoneDrawMode) {
if (radiusMode) toggleRadiusMode();
if (radiusAreaMode) toggleRadiusAreaMode();
if (measureMode) toggleMeasureMode();
const el = document.getElementById('zonedraw-display');
if (el) el.style.display = 'block';
} else {
_zoneDrawClear();
}
}
function _zoneDrawNearVertex(px) {
for (let i = 0; i < zoneDrawPoints.length; i++) {
const vpx = map.project(zoneDrawPoints[i]);
const dx = px.x - vpx.x, dy = px.y - vpx.y;
if (Math.sqrt(dx*dx + dy*dy) < HIT_RADIUS_VERTEX_PX) return i;
}
return -1;
}
function _zoneDrawNearEdgeDot(px) {
for (let i = 0; i < zoneDrawPoints.length; i++) {
const j = (i + 1) % zoneDrawPoints.length;
const a = zoneDrawPoints[i], b = zoneDrawPoints[j];
for (const t of [0.33, 0.5, 0.66]) {
const dot = [a[0]+(b[0]-a[0])*t, a[1]+(b[1]-a[1])*t];
const dpx = map.project(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: j, dot };
}
}
return null;
}
function _zoneDrawOnClick(e) {
if (zoneDrawDragging) return;
if (zoneDrawJustDragged) { zoneDrawJustDragged = false; return; }
const lon = e.lngLat.lng, lat = e.lngLat.lat;
// First click — place circle, auto-zoom
if (zoneDrawPoints.length === 0) {
const km = _zoneDrawGetRadius();
zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
_zoneDrawCollapsed = false;
// Auto-zoom: derive zoom so circle diameter fills ~60% of viewport
const mpp = (km * 2000) / (window.innerWidth * 0.6);
const lat1 = lat * Math.PI / 180;
const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
const clampedZoom = Math.max(8, Math.min(19, targetZoom));
map.easeTo({ center: [lon, lat], zoom: clampedZoom, duration: 600 });
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
const px = map.project([lon, lat]);
if (_zoneDrawNearVertex(px) >= 0) return;
const edgeHit = _zoneDrawNearEdgeDot(px);
if (edgeHit) {
zoneDrawPoints.splice(edgeHit.insertIdx, 0, [edgeHit.dot[0], edgeHit.dot[1]]);
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
return;
}
// Click on empty space — place new circle
const km = _zoneDrawGetRadius();
zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
_zoneDrawCollapsed = false;
const mpp = (km * 2000) / (window.innerWidth * 0.6);
const lat1 = lat * Math.PI / 180;
const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
map.easeTo({ center: [lon, lat], zoom: Math.max(8, Math.min(19, targetZoom)), duration: 600 });
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
}
function _zoneDrawOnMouseDown(e) {
if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
const px = map.project(e.lngLat);
if (_zoneDrawNearEdgeDot(px)) return;
const vi = _zoneDrawNearVertex(px);
if (vi >= 0) {
zoneDrawDragging = true; zoneDrawDragIdx = vi;
map.dragPan.disable();
map.getCanvas().style.cursor = 'grabbing';
e.preventDefault();
}
}
function _zoneDrawOnMouseMove(e) {
if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
if (zoneDrawDragging && zoneDrawDragIdx >= 0) {
zoneDrawPoints[zoneDrawDragIdx] = [e.lngLat.lng, e.lngLat.lat];
_zoneDrawUpdateLayers(true);
_zoneDrawShowPopupDebounced();
return;
}
const px = map.project(e.lngLat);
const vi = _zoneDrawNearVertex(px);
const edgeHit = vi < 0 ? _zoneDrawNearEdgeDot(px) : null;
map.getCanvas().style.cursor = vi >= 0 ? 'grab' : (edgeHit ? 'copy' : 'crosshair');
}
function _zoneDrawOnMouseUp() {
if (!zoneDrawDragging) return;
zoneDrawDragging = false;
zoneDrawDragIdx = -1;
zoneDrawJustDragged = true;
map.dragPan.enable();
map.getCanvas().style.cursor = 'crosshair';
_zoneDrawUpdateLayers(false);
_zoneDrawShowPopup();
setTimeout(() => { zoneDrawJustDragged = false; }, 50);
}
const urlCache = {};
let globalSubsData = null;
let allREPDFeatures = [];
let searchIndex = [];
// ── Single popup instance — prevents accumulation ────────────────────────────
let activePopup = null;
function openPopup(lngLat, html, maxWidth) {
if (activePopup) { activePopup.remove(); activePopup = null; }
activePopup = new maplibregl.Popup({ maxWidth: maxWidth || POPUP_MAX_WIDTH })
.setLngLat(lngLat)
.setHTML(html)
.addTo(map);
activePopup.on('close', () => { activePopup = null; });
return activePopup;
}
function closeActivePopup() {
if (activePopup) { activePopup.remove(); activePopup = null; }
}
// V5.1: exposed for inline popup buttons — closes tracked popup, keeps map shape visible
window._closePopupKeepShape = () => closeActivePopup();
// ── Fullscreen ───────────────────────────────────────────────────────────────
let fsActive = false;
let curtainOpen = false;