In this section
- G203 03 Gps Camera Candidate geodesy · gridatlas / atlas/modules/g203-03-gps-camera-candidate.js lines 1–700
G203 03 Gps Camera Candidate
A JavaScript file in the atlas folder of GridAtlas that maps substations and 11kV. It sets panel open (`setPanelOpen`), updates text (`updateText`) and refreshes guidance (`refreshGuidance`).
geodesygridatlas / atlas/modules/g203-03-gps-camera-candidate.js · lines 1–700 of 735 · pattern shouldAcceptCameraFix (shared by 3 files)
- What it does
- It maps substations and 11kV. Defines 40 functions or classes, including setPanelOpen, notify, updateText, distanceText, bearingText. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gps'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: substations, 11kV, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV, 11kV.
- Downstream impact
- Used directly by 1 file: G203 03 Gps Camera Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Unified GridAtlas/SatNav candidate. Derived from the immutable 2 km convergence cartridge; native shell geometry stays owned by GridAtlas. Its code works with 11 kV and 33 kV. It responds to click, visibilitychange and offline events.
- Why it matters
- Checked by G203 03 Gps Camera Test.
- Application
- gridatlas · atlas/modules · script
- Uses
- none found
- Used by
- referenced by G203 03 Gps Camera Test (new URL import.meta.url)
- Produces
- setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan
- Defines here
- setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample, replacePlan, undo, setFix, fieldState, refreshSources, guidanceText, nativeLayer, syncInfrastructureControls, render, arm, mapClick, selectedIndex, stopTracking
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-03-gps-camera-candidate.js:1-700 · blob e48c743713123f1c7d099641118d83aa4886286d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
/* Unified GridAtlas/SatNav candidate. Derived from the immutable 2 km convergence cartridge; native shell geometry stays owned by GridAtlas. */
void async function () {
const root = new URL('../../../', location.href);
const vendor = new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/', root);
let installUnifiedLayerSearch = null;
void import(new URL('atlas/modules/unified-layer-search-ui.mjs', root)).then(module => {installUnifiedLayerSearch=module.installUnifiedLayerSearch;}).catch(error => console.error('Optional Layers search unavailable; native Layers retained',error));
const [maths, compass, { point }, { createWaypointState }, { createWaypointGuidance }, { assessFieldState }, { classifyDirectLeg, directLegGeometry, reconcileNavigationLayers, prepareAssetDestination, rankHigherVoltage }, {validateDestinationLeg}] = await Promise.all([
import(new URL('vendor/grid-distance-maths/src/geodesy.mjs', vendor)),
import(new URL('nav/compass.mjs', vendor)),
import(new URL('tools/satnav/line/position-overlay.mjs', root)),
import(new URL('tools/satnav/waypoints/state.mjs', root)),
import(new URL('tools/satnav/guidance/ordered-convergence-2km.mjs', root)),
import(new URL('tools/satnav/field-reliability/state.mjs', root)),
import(new URL('tools/satnav/guidance/convergence-2km.mjs', root)),
import(new URL('atlas/modules/unified-destination-contract.mjs', root)),
]);
const style = document.createElement('style');
style.textContent = `
#satnav-toggle{position:fixed;right:var(--satnav-dock-right,12px);bottom:var(--satnav-dock-bottom,112px);z-index:10031;min-height:44px;padding:6px 12px;background:#081820ed;color:#e4f7f7;border:1px solid #367078;border-radius:6px;font:600 13px system-ui,sans-serif;cursor:pointer}
#satnav-toggle:focus-visible{outline:2px solid white;outline-offset:2px}
#satnav-compact[hidden],#satnav-access[hidden]{display:none!important}
#satnav-compact,#satnav-access{position:fixed;left:max(8px,env(safe-area-inset-left));color:#e4f7f7;font:13px/1.3 system-ui,sans-serif;z-index:10030}
#satnav-compact{left:auto;right:var(--satnav-dock-right,12px);bottom:var(--satnav-panel-bottom,166px);width:min(260px,calc(100vw - 20px));display:grid;gap:4px;max-height:min(45dvh,max(64px,var(--satnav-panel-height,240px)));overflow:auto;overscroll-behavior:contain}
#gridatlas-mobile-tray[data-satnav-dock]{position:fixed!important;top:auto!important;left:auto!important;right:var(--satnav-dock-right,12px)!important;bottom:var(--satnav-tray-bottom,60px)!important;z-index:10029!important;display:flex!important;gap:4px;pointer-events:auto;width:max-content!important;max-width:calc(100vw - 20px)}
#satnav-compact [hidden],#satnav-compact :empty.satnav-readout,#satnav-field-tools:empty{display:none!important}
#satnav-compact button,#satnav-access{background:#081820ed;color:#e4f7f7;border:1px solid #367078;border-radius:6px}
#satnav-compact button{min-width:0;min-height:44px;padding:4px 7px;font:inherit;touch-action:manipulation;cursor:pointer}
#satnav-compact button:disabled{opacity:.55;cursor:default}
#satnav-compact button[aria-pressed=true]{border-color:#67f9ff;box-shadow:inset 0 0 0 1px #67f9ff}
#satnav-compact :focus-visible,#satnav-access :focus-visible{outline:2px solid white;outline-offset:-3px}
#satnav-compact .satnav-endpoint{text-align:left}
#satnav-compact .satnav-endpoint b{display:inline-block;width:43px;color:#68e8f5}
#satnav-compact .satnav-row{display:flex;gap:4px}
#satnav-compact .satnav-row button{flex:1}
#satnav-editor{display:grid;gap:4px;background:#081820ed;padding:4px;border-radius:6px}
#satnav-selected,#satnav-limit{margin:2px 3px}
#satnav-selected{font-weight:bold}
#satnav-limit{font-size:11px;color:#b6d4d6}
#satnav-compact .satnav-readout{background:#081820ed;margin:0;padding:3px 6px;border-radius:4px;font-size:12px;overflow-wrap:anywhere}
#satnav-guide{color:#8bf7f7}
#satnav-access{bottom:max(8px,env(safe-area-inset-bottom));max-width:min(300px,calc(100vw - 110px));font-size:11px}
#satnav-access summary{min-height:24px;box-sizing:border-box;padding:4px 7px;cursor:pointer}
#satnav-access p{margin:0;padding:2px 8px 7px}
`;
document.head.append(style);
const panel = document.createElement('section');
panel.id = 'satnav-compact';
panel.setAttribute('aria-label', 'SatNav map controls');
panel.innerHTML = `
<button class="satnav-endpoint" type="button" id="satnav-from" aria-pressed="false"><b>FROM</b><span>My location</span></button>
<button class="satnav-endpoint" type="button" id="satnav-to" aria-pressed="false"><b>TO</b><span>Tap map</span></button>
<div class="satnav-row">
<button type="button" id="satnav-add" aria-label="Add a waypoint" aria-pressed="false">+ Pin</button>
<button type="button" id="satnav-undo" disabled>Undo</button>
<button type="button" id="satnav-edit" aria-controls="satnav-editor" aria-expanded="false" disabled>Edit</button>
</div>
<button type="button" id="satnav-use-fix" hidden>Place at my GPS fix</button>
<div id="satnav-editor" hidden>
<div class="satnav-row"><button type="button" id="satnav-prev" aria-label="Previous pin">Previous</button><button type="button" id="satnav-next" aria-label="Next pin">Next</button></div>
<p id="satnav-selected"></p>
<div class="satnav-row"><button type="button" id="satnav-replace">Move on map</button><button type="button" id="satnav-remove">Delete</button></div>
<div class="satnav-row"><button type="button" id="satnav-earlier">Earlier</button><button type="button" id="satnav-later">Later</button></div>
<p id="satnav-limit"></p>
</div>
<div class="satnav-row"><button type="button" id="satnav-location">My location</button><button type="button" id="satnav-stop" disabled>Stop</button></div>
<p class="satnav-readout" id="satnav-status" role="status"></p>
<p class="satnav-readout" id="satnav-guide" aria-label="Waypoint guidance"></p>
<details id="satnav-infrastructure"><summary>Infrastructure layers</summary>
<div class="satnav-row"><button type="button" id="satnav-osm11" aria-pressed="false" disabled>11 kV (OSM)</button></div>
<div class="satnav-row"><button type="button" id="satnav-ukpn" aria-pressed="false" disabled>UKPN secondary</button></div>
<p class="satnav-readout" id="satnav-layer-status" role="status"></p>
</details>
<div id="satnav-field-tools"></div>`;
const access = document.createElement('details');
access.id = 'satnav-access';
access.innerHTML = '<summary>Check access before entry</summary><p>Maps do not grant access. You and your organisation must check land rights, restrictions and safe working conditions. Ventus retains its own legal and safety duties.</p>';
const toggle = document.createElement('button');
toggle.id = 'satnav-toggle';
toggle.type = 'button';
toggle.setAttribute('aria-controls', panel.id);
let panelOpen = false;
function setPanelOpen(open) {
panelOpen = Boolean(open);
panel.hidden = access.hidden = !panelOpen;
toggle.setAttribute('aria-expanded', String(panelOpen));
if (!panelOpen) picking = null; // cancel an uncommitted map-pick, never stop GPS or change the route
render();
}
toggle.addEventListener('click', () => setPanelOpen(!panelOpen));
panel.hidden = access.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
toggle.textContent = 'SATNAV';
document.body.append(toggle, panel, access);
const controls = Object.fromEntries([...panel.querySelectorAll('[id]')].map(el => [el.id.slice(7), el]));
const notify = (name, detail) => panel.dispatchEvent(new CustomEvent('satnav:' + name, { detail }));
const updateText = (element, value) => { if (element.textContent !== value) element.textContent = value; };
const distanceText = metres => metres >= 1000 ? (metres / 1000).toFixed(1) + ' km' : Math.round(metres) + ' m';
const bearingText = degrees => (Math.round(degrees) % 360) + '°';
const collection = features => ({ type: 'FeatureCollection', features });
let state = createWaypointState();
let snapshot = state.snapshot();
let roles = { from: null, to: null, gpsOrigin: false };
let selected = null, picking = null, closed = false;
let guidance = createWaypointGuidance(maths, compass);
// The model records reversible coordinate edits. Keep matching endpoint roles with each edit.
let history = [], localPlan = null;
let map = null, fix = null, watch = null, generation = 0, pendingLocation = false;
let followCamera = false, layerSearch = null;
let locationRequestedAt = null, streetZoomPending = false;
// G203-03 camera policy; no additional watch, listener timer, or data acquisition.
function cameraTarget(map,fix,streetZoom){
if (!map || !fix) return null;
const target={center:[fix.longitude,fix.latitude]};
if(streetZoom){
const current=map.getZoom(), maximum=map.getMaxZoom();
if(Number.isFinite(current)&&Number.isFinite(maximum))target.zoom=Math.min(maximum,Math.max(17,current));
}
return target;
}
function shouldAcceptCameraFix(fix,quality,requestedAt,hidden){
return !hidden && quality==="usable" && fix!==null && Number.isFinite(fix.timestampMs) && (requestedAt===null||fix.timestampMs>=requestedAt);
}
const pauseFollow = () => {
if (followCamera) {
followCamera = false;
streetZoomPending = false;
render();
}
};
const pauseGesture = event => { if (event?.originalEvent) pauseFollow(); };
let resumedAt = null, lastFixMs = -Infinity, permissionDenied = false;
let notice = '', planData = collection([]), positionData = collection([]);
let planDirty = true, positionDirty = true, planDistance = 0, longLegs = 0, dateLineLegs = 0;
const planSource = 'gridatlas-satnav-waypoints';
const positionSource = 'gridatlas-satnav-position';
const layers = [
[positionSource, 'accuracy', 'gps-accuracy', 'fill', {'fill-color':'#ffdf61','fill-opacity':.22}],
[planSource, 'line', 'selected-section', 'line', {'line-color':'#00ffff','line-width':3,'line-dasharray':[3,2]}],
[planSource, 'via', 'waypoint', 'circle', {'circle-color':'#ffffff','circle-radius':6,'circle-stroke-color':'#006a76','circle-stroke-width':3}],
[planSource, 'start', 'start-point', 'circle', {'circle-color':'#00ffff','circle-radius':7,'circle-stroke-color':'#071820','circle-stroke-width':2}],
[planSource, 'end', 'destination-point', 'circle', {'circle-color':'#ff65d5','circle-radius':8,'circle-stroke-color':'#071820','circle-stroke-width':2}],
[positionSource, 'gps', 'measured-gps', 'circle', {'circle-color':'#ffdf61','circle-radius':7,'circle-stroke-color':'#171100','circle-stroke-width':2}],
];
function refreshGuidance() {
let pins = roles.from && snapshot.pins.length > 1 ? snapshot.pins : [];
if (closed) pins = [...pins, {id:'return-' + roles.from, coordinate:pins[0].coordinate}];
guidance.setRoute(pins);
}
function changePlan() {
snapshot = state.snapshot();
closed = false;
if (!snapshot.pins.some(pin => pin.id === selected)) selected = snapshot.pins[0]?.id ?? null;
if (!selected) controls.editor.hidden = true;
planDistance = 0;
longLegs = 0;
dateLineLegs = 0;
const features = [];
for (const [i, pin] of snapshot.pins.entries()) {
const role = pin.id === roles.from ? 'start-point' : pin.id === roles.to ? 'destination-point' : 'waypoint';
const feature = point(role, pin.coordinate);
feature.properties.pinId = pin.id;
feature.properties.order = i + 1;
features.push(feature);
if (!i) continue;
const previous = snapshot.pins[i - 1].coordinate;
const leg = classifyDirectLeg(maths, previous, pin.coordinate);
planDistance += leg.metres;
if (leg.status === 'over-limit') { longLegs++; continue; }
if (leg.status === 'antimeridian') { dateLineLegs++; continue; }
const geometry = directLegGeometry(maths, previous, pin.coordinate);
if (geometry) features.push({type:'Feature', properties:{role:'selected-section'}, geometry});
}
planData = collection(features);
planDirty = true;
refreshGuidance();
notify('pins', snapshot.pins);
render();
}
function edit(operation) {
const before = {...roles};
if (!operation()) return false;
history.push({roles:before});
if (history.length > 256) history.shift();
changePlan();
return true;
}
function setPin(which, at, fromGps = false) {
if (localPlan) {
// A bad coordinate must leave the preview and the user's plan intact.
createWaypointState().add(at);
leaveExample();
if (which === 'from' || (which === 'add' && !roles.from)) pendingLocation = false;
if (which === 'to' && !roles.from && watch !== null && compass.fixQuality(fix) === 'usable') {
pendingLocation = false;
setPin('from', [fix.longitude, fix.latitude], true);
}
}
const replaceId = which === 'replace' ? selected : roles[which];
if (replaceId) {
return edit(() => {
if (!state.replace(replaceId, at)) return false;
if (replaceId === roles.from) roles.gpsOrigin = fromGps;
return true;
});
}
return edit(() => {
const toIndex = roles.to ? snapshot.pins.length - 1 : snapshot.pins.length;
const establishesFrom = which === 'from' || (which === 'add' && !roles.from);
const atIndex = establishesFrom ? 0 : which === 'to' ? snapshot.pins.length : toIndex;
const id = state.add(at, atIndex);
if (establishesFrom) {roles.from = id; roles.gpsOrigin = fromGps;}
if (which === 'to') roles.to = id;
selected = id;
return true;
});
}
function place(at, fromGps = false) {
if (!picking) return;
const which = picking;
picking = null;
if (which === 'from' || (which === 'add' && !roles.from) || (which === 'replace' && selected === roles.from)) pendingLocation = false;
try { notice = ''; setPin(which, at, fromGps); }
catch (error) { notice = error.message; }
render();
}
function restoreLocalPlan() {
if (!localPlan) return false;
({state, roles, selected, history} = localPlan);
localPlan = null;
snapshot = state.snapshot();
guidance = createWaypointGuidance(maths, compass);
pendingLocation = !roles.from && watch !== null;
picking = null;
notice = '';
return true;
}
function leaveExample() {
if (restoreLocalPlan()) changePlan();
}
function replacePlan(coordinates, {example = false} = {}) {
if (!Array.isArray(coordinates) || !coordinates.length || coordinates.length > snapshot.maxPins) throw new RangeError('Choose a plan with 1 to 20,000 pins');
const imported = createWaypointState();
for (const at of coordinates) imported.add(at); // Validate everything before switching state.
const newPins = imported.snapshot().pins;
if (example) {
localPlan ??= {state, roles, selected, history};
history = [];
controls.editor.hidden = true;
} else {
restoreLocalPlan();
history = [{state, roles:{...roles}}];
}
state = imported;
roles = {from:newPins[0].id, to:newPins.length > 1 ? newPins.at(-1).id : null, gpsOrigin:false};
guidance = createWaypointGuidance(maths, compass);
picking = null;
pendingLocation = false;
selected = roles.from;
notice = '';
changePlan();
}
function undo() {
if (localPlan) {leaveExample(); return;}
const previous = history.pop();
if (!previous) return;
if (previous.state) {
state = previous.state;
guidance = createWaypointGuidance(maths, compass);
} else state.undo();
roles = previous.roles;
picking = null;
pendingLocation = false;
notice = '';
changePlan();
}
function setFix(next) {
fix = next;
const features = [];
if (next) {
const at = [next.longitude, next.latitude];
features.push(point('measured-gps', at));
if (next.accuracyM > 0) features.push({type:'Feature',properties:{role:'gps-accuracy'},geometry:{type:'Polygon',coordinates:[maths.geodesicCircle(...at,next.accuracyM/1000,64)]}});
}
positionData = collection(features);
positionDirty = true;
notify('fix', next);
}
function fieldState(sample) {
return assessFieldState({tracking:watch !== null,hidden:document.hidden,resumedAt,fix:sample,
networkOnline:navigator.onLine,permissionDenied}, compass.fixQuality);
}
function refreshSources() {
if (!map || !map.getLayer('l-sat')) return;
for (const [id, data] of [[planSource,planData],[positionSource,positionData]]) {
if (!map.getSource(id)) map.addSource(id, {type:'geojson',data});
else if (id === planSource ? planDirty : positionDirty) map.getSource(id).setData(data);
}
for (const [source, key, role, type, paint] of layers) {
const id = source + '-' + key;
if (!map.getLayer(id)) map.addLayer({id,source,type,paint,filter:['==',['get','role'],role]});
}
// Keep the separately owned mapped-footpath line above infrastructure too.
// One ordering owner avoids two timers fighting over the last layer.
const navigationOrder = layers.map(([source,key]) => source + '-' + key);
if (map.getLayer('satnav-active-walking-route')) navigationOrder.splice(2,0,'satnav-active-walking-route');
reconcileNavigationLayers(map, navigationOrder);
planDirty = positionDirty = false;
}
function guidanceText() {
const result = guidance.locate(fix, Date.now());
if (result.status === 'complete') return 'Arrived at the final pin';
if (result.status === 'over-limit') return 'Direct leg exceeds 2 km · choose a nearer waypoint or destination';
if (result.status !== 'guiding' || !Number.isFinite(result.distanceM)) return '';
const name = closed && result.targetIndex === snapshot.pins.length ? 'Return to FROM' : 'Pin ' + (result.targetIndex + 1);
const parts = [name, distanceText(result.distanceM)];
if (Number.isFinite(result.bearingDeg)) parts.push(bearingText(result.bearingDeg) + ' true');
if (Number.isFinite(result.remainingM)) parts.push(distanceText(result.remainingM) + ' remaining');
if (result.offRoute === true) parts.push('Off planned line');
return parts.join(' · ');
}
// The compact interface delegates selection to the existing native controls.
// Never create a second infrastructure source or independently toggle visibility.
const nativeLayers = [['osm11','11kv'],['ukpn','ukpn_secondary']];
function nativeLayer(id) {
return document.querySelector('#scada-ui-container input[data-layer-id="'+id+'"]');
}
function syncInfrastructureControls() {
for (const [key,id] of nativeLayers) {
const input = nativeLayer(id), button = controls[key];
button.disabled = !map || !input || input.disabled || !map.getLayer('l-'+id);
button.setAttribute('aria-pressed',String(Boolean(input?.checked)));
}
const available = nativeLayers.filter(([key]) => !controls[key].disabled).length;
const deferred = nativeLayers.filter(([key,id]) => !controls[key].disabled && controls[key].getAttribute('aria-pressed') === 'true' && map.getZoom() < (map.getLayer('l-'+id).minzoom ?? 0));
updateText(controls['layer-status'], !available ? 'Infrastructure unavailable in this composition'
: deferred.length ? 'Selected layers appear at zoom '+Math.min(...deferred.map(([,id])=>map.getLayer('l-'+id).minzoom))+' or higher'
: available < nativeLayers.length ? 'Some layers are unavailable in this composition' : '');
}
for (const [key,id] of nativeLayers) controls[key].onclick = () => {
const input = nativeLayer(id);
if (!map || !input || input.disabled || !map.getLayer('l-'+id)) return;
input.click();
syncInfrastructureControls();
refreshSources();
};
function render() {
refreshSources();
syncInfrastructureControls();
const count = snapshot.pins.length;
controls.from.disabled = controls.to.disabled = controls.location.disabled = !map;
controls.add.disabled = !map || count >= snapshot.maxPins;
controls.stop.disabled = watch === null;
updateText(controls.location, watch !== null ? (followCamera ? 'Following GPS' : 'Resume follow') : roles.from ? 'Start GPS' : 'My location');
controls.undo.disabled = !localPlan && !history.length;
controls.edit.disabled = !count || Boolean(localPlan);
controls.edit.setAttribute('aria-expanded', String(!controls.editor.hidden));
updateText(controls.from.querySelector('span'), picking === 'from' ? 'Tap map' : roles.from ? (roles.gpsOrigin ? 'GPS fix' : 'Selected point') : 'My location');
updateText(controls.to.querySelector('span'), picking === 'to' || !roles.to ? 'Tap map' : 'Selected point');
for (const key of ['from','to','add']) controls[key].setAttribute('aria-pressed', String(picking === key));
controls['use-fix'].hidden = !picking || compass.fixQuality(fix) !== 'usable';
if (!controls.editor.hidden) {
const index = snapshot.pins.findIndex(pin => pin.id === selected);
updateText(controls.selected, 'Pin ' + (index+1) + ' of ' + count + (selected === roles.from ? ' · FROM' : selected === roles.to ? ' · TO' : ''));
updateText(controls.limit, 'Maximum ' + snapshot.maxPins.toLocaleString('en-GB') + ' pins');
controls.prev.disabled = index <= 0;
controls.next.disabled = index >= count - 1;
const via = selected !== roles.from && selected !== roles.to;
controls.earlier.disabled = !via || index <= (roles.from ? 1 : 0);
controls.later.disabled = !via || index >= count - (roles.to ? 2 : 1);
}
const messages = [];
if (!map) messages.push('Loading map');
else if (picking) messages.push(picking === 'add' ? 'Tap map to add pin' : picking === 'replace' ? 'Tap map to move pin' : 'Tap map to set ' + picking.toUpperCase());
else if (count > 1) messages.push(count + ' pins · ' + distanceText(planDistance) + ' planned');
if (longLegs) messages.push('Direct leg exceeds 2 km · add a nearer waypoint or destination');
if (dateLineLegs) messages.push('Line omitted at the date line');
if (notice) messages.push(notice);
if (fieldState(fix).mapAvailability === 'offline-unverified') messages.push('Offline · map coverage unverified');
if (fix) {
messages.push('GPS ±' + Math.round(fix.accuracyM) + ' m');
if (fix.heading !== null && compass.fixQuality(fix) === 'usable') messages.push('GPS course ' + bearingText(fix.heading));
}
updateText(controls.status, messages.join(' · '));
const guide = guidanceText();
updateText(controls.guide, guide);
updateText(toggle, panelOpen ? 'HIDE SATNAV' : watch !== null ? 'SATNAV · GPS active' : 'SATNAV');
toggle.setAttribute('aria-label', panelOpen ? 'Hide SatNav controls' : watch !== null ? 'Show SatNav controls, GPS active' : 'Show SatNav controls');
if (!panelOpen && watch !== null && guide) toggle.title = guide;
else toggle.removeAttribute('title');
}
function arm(which) {
picking = picking === which ? null : which;
notice = '';
if (picking === 'from') pendingLocation = false;
render();
}
function mapClick(event) {
if (picking && event.lngLat) {
const at = event.lngLat.wrap ? event.lngLat.wrap() : event.lngLat;
place([at.lng, at.lat]);
} else if (event.point && !localPlan) {
const {x,y} = event.point;
const ids = ['start','via','end'].map(role => planSource + '-' + role);
if (!ids.every(id => map.getLayer(id))) return;
const hit = map.queryRenderedFeatures([[x-7,y-7],[x+7,y+7]], {layers:ids})[0];
if (hit?.properties?.pinId) { selected = hit.properties.pinId; controls.editor.hidden = false; render(); }
}
}
for (const name of ['from','to','add','replace']) controls[name].onclick = () => arm(name);
controls['use-fix'].onclick = () => {
if (compass.fixQuality(fix) === 'usable') place([fix.longitude,fix.latitude], true);
else {notice = 'Waiting for a usable GPS fix';render();}
};
controls.undo.onclick = undo;
controls.edit.onclick = () => {controls.editor.hidden = !controls.editor.hidden; picking = null; render();};
const selectedIndex = () => snapshot.pins.findIndex(pin => pin.id === selected);
for (const [name,offset] of [['prev',-1],['next',1]]) controls[name].onclick = () => {
selected = snapshot.pins[selectedIndex() + offset].id;
picking = null;
render();
};
for (const [name,offset] of [['earlier',-1],['later',1]]) controls[name].onclick = () => {
picking = null;
edit(() => state.move(selected, selectedIndex() + offset));
};
controls.remove.onclick = () => {
picking = null;
edit(() => {
const removed = selected;
state.remove(removed);
if (removed === roles.from) { roles.from = null; roles.gpsOrigin = false; pendingLocation = false; }
if (removed === roles.to) roles.to = null;
return true;
});
};
function stopTracking(message) {
generation++;
if (watch !== null) navigator.geolocation.clearWatch(watch);
watch = null;
followCamera = false;
streetZoomPending = false;
locationRequestedAt = null;
lastFixMs = -Infinity;
pendingLocation = false;
notice = message;
setFix(null);
notify('stop');
render();
}
function centreOnFix() {
if ((!pendingLocation && !followCamera) ||
!shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) return;
const first = pendingLocation;
pendingLocation = false;
locationRequestedAt = null;
const at = [fix.longitude,fix.latitude];
// Preserve explicit FROM and route pins; only an empty FROM takes the first fix.
try { if (first && !roles.from) setPin('from', at, true); }
catch (error) { notice = error.message; return; }
if (!followCamera) return; // A gesture may precede the first usable fix.
const target = cameraTarget(map,fix,streetZoomPending);
if (target) {
streetZoomPending = false;
map.jumpTo(target); // Subsequent fixes and Resume follow preserve zoom/bearing/pitch.
}
}
controls.location.onclick = () => {
if (!isSecureContext || !navigator.geolocation) {notice = 'Location needs HTTPS and device GPS';render();return;}
pendingLocation = true;
followCamera = true;
permissionDenied = false;
picking = null;
notice = 'Waiting for GPS';
if (watch !== null) {
if (shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) {notice = '';centreOnFix();}
render();
return;
}
locationRequestedAt = Date.now();
streetZoomPending = true;
const active = ++generation;
try {
watch = navigator.geolocation.watchPosition(position => {
if (active !== generation) return;
const {longitude,latitude,accuracy:accuracyM,heading,speed} = position.coords;
const next = Object.freeze({longitude,latitude,accuracyM,timestampMs:position.timestamp,
heading:Number.isFinite(heading) && heading >= 0 && heading < 360 && Number.isFinite(speed) && speed > 0 ? heading : null});
const field = fieldState(next);
const quality = field.gpsState;
if (field.showMeasuredFix) {
if (next.timestampMs <= lastFixMs) return;
lastFixMs = next.timestampMs;
setFix(next);
notice = quality === 'poor' ? 'Low GPS accuracy' : '';
centreOnFix();
} else {
setFix(null);
notice = quality === 'stale' ? 'GPS fix is stale' : 'Waiting for a fresh GPS fix';
}
render();
}, error => {
if (active !== generation) return;
if (error.code === 1) {permissionDenied = true;stopTracking('Location permission denied');}
else {setFix(null); notice = 'Location unavailable'; render();}
}, {enableHighAccuracy:true,maximumAge:0,timeout:10000});
notify('watch');
} catch {stopTracking('Location could not start');}
render();
};
controls.stop.onclick = () => stopTracking('Location stopped');
document.addEventListener('visibilitychange', () => {
if (!document.hidden) resumedAt = Date.now();
if (watch !== null) {
setFix(null);
notice = document.hidden ? 'GPS in background' : 'Waiting for a fresh GPS fix';
render();
}
});
window.addEventListener('offline', render);
window.addEventListener('online', render);
panel.addEventListener('keydown', event => {
if (event.key === 'Escape') {event.stopPropagation(); picking = null; controls.editor.hidden = true; setPanelOpen(false); toggle.focus();}
});
for (const element of [toggle,panel,access]) {
for (const name of ['click','dblclick','mousedown','pointerdown','touchstart']) element.addEventListener(name, event => event.stopPropagation());
}
// This is an interface-owned extension of the selected UKPN card.
// No second popup, map, GPS watch, fabricated REPD identity or data fetch.
function installAssetActions() {
const card = map?.getContainer().querySelector('[data-ukpn-detail][data-site]');
if (!card || card.querySelector('[data-satnav-asset-actions]')) return;
const site = card.dataset.site;
const actions = document.createElement('section');
actions.dataset.satnavAssetActions = '1';
const current = () => card.isConnected && actions.isConnected && card.dataset.site === site;
const output = document.createElement('div');
output.setAttribute('role','status');
const button = (label, run) => {
const el = document.createElement('button');
el.type = 'button'; el.textContent = label;
el.style.cssText = 'min-height:44px;display:block;width:100%;margin:3px 0';
el.addEventListener('click', event => {
event.stopPropagation();
if (current()) run();
});
return el;
};
const selectedOrigin = () => {
const source = map.getSource('src-ukpn_secondary');
const feature = source?.serialize()?.data?.features?.find(f => String(f.id) === site);
return feature?.geometry?.type === 'Point' ? feature.geometry.coordinates : null;
};
let gridRequest = 0;
const neon = () => window.__GRIDATLAS_NEON_LINKS__;
const clean = new MutationObserver(() => {if (!card.isConnected || card.dataset.site!==site) {++gridRequest;neon()?.clearSecondaryLinks?.(site);clean.disconnect();}});
clean.observe(map.getContainer(),{childList:true,subtree:true,attributes:true,attributeFilter:['data-site']});
actions.append(button('Ventus Grid Engine', async () => {
const request = ++gridRequest;
const valid = () => current() && request === gridRequest;
output.replaceChildren();
neon()?.clearSecondaryLinks?.();
const origin = selectedOrigin();
if (!origin) { output.textContent = 'Selected asset unavailable'; return; }
const originalCamera = [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()];
output.textContent = 'Loading higher-voltage substations…';
// Use the existing Grid Engine acquisition boundary, not a second dataset.
try {
window.__GRIDATLAS_NEON_LINKS__?.enableSubstationLayer?.();
const deadline = Date.now() + 60000;
let nodes = [];
while (valid()) {
const engine = window.__GRIDATLAS_NEON_LINKS__;
const distance = typeof engine?.measure?.distanceKm === 'function'
? (...args) => engine.measure.distanceKm(...args)
: typeof globalThis.VentusGridCompute?.distanceKm === 'function'
? (...args) => globalThis.VentusGridCompute.distanceKm(...args) : null;
if (engine?.substations?.length && distance) nodes = rankHigherVoltage(engine.substations, origin, distance);
if (nodes.length || Date.now() >= deadline) break;
await new Promise(resolve => setTimeout(resolve,250));
}
if (!valid()) return;
if (!nodes.length) { output.textContent = 'No qualifying higher-voltage sites loaded; try again'; return; }
const ok = neon()?.drawSecondaryLinks?.({site,origin,nodes});
if (!valid()) return;
renderGridNodes(nodes, origin, valid);
if (!ok) output.prepend('Neon geometry unavailable; retry. ');
else if (watch === null && [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()].every((v,i)=>v===originalCamera[i])) {
const points=[origin,...nodes.map(n=>n.at)];
const bounds=[[Math.min(...points.map(p=>p[0])),Math.min(...points.map(p=>p[1]))],[Math.max(...points.map(p=>p[0])),Math.max(...points.map(p=>p[1]))]];
map.fitBounds(bounds,{padding:Math.min(56,Math.floor(innerWidth/6),Math.floor(innerHeight/6)),maxZoom:13,duration:300});
}
} catch (error) {
if (valid()) output.textContent = 'Grid Engine unavailable; try again';
}
}), button('Vicinity', () => {
++gridRequest;
neon()?.clearSecondaryLinks?.();
const origin = selectedOrigin();
const engine = window.__GRIDATLAS_MODULES__?.ukOfftakers;
if (!origin || typeof engine?.openSecondaryVicinity !== 'function') {
output.textContent = 'Secondary Vicinity is not available in this composition'; return;
}
if (!engine.openSecondaryVicinity({site,at:origin})) {
output.textContent = 'Vicinity not ready; try again'; return;
}
notice = 'Vicinity opened for '+site;
render();
}), output);
function renderGridNodes(nodes, origin, valid) {
output.textContent = 'Mapped substations ≥33 kV · straight-line screening, not proven electrical connections or access.';
if (!nodes.length) { output.append(' No qualifying sites found.'); return; }
for (const node of nodes) {
const row = document.createElement('div');
row.textContent = node.name + ' · ' + node.kv + ' kV · ' + node.km.toFixed(2) + ' km from selected secondary';
row.append(button('Use this destination', () => {
if (!valid()) return;
const result = prepareAssetDestination(maths, fix, node.at, watch !== null, fieldState(fix).gpsState);
if (!result.ok) { notice = result.reason; render(); return; }
replacePlan(result.coordinates);
notice = 'Destination: ' + node.name;
render();
}));
output.append(row);
}
}
card.append(actions);
}
function refresh() {
const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
const dockOwnsControls = Boolean(document.getElementById('g203-native-dock')?.isConnected);
if (panel.parentElement !== host || access.parentElement !== host) host.append(panel,access);
if (!dockOwnsControls && toggle.parentElement !== host) host.append(toggle);
const mapBounds = window.__GRIDATLAS_V9_MAP__?.getContainer()?.getBoundingClientRect();
const layers = document.getElementById('gridatlas-dash-toggle')?.getBoundingClientRect();
const tray = document.getElementById('gridatlas-mobile-tray');
const mapBottom = Math.min(innerHeight,mapBounds?.bottom ?? innerHeight);
const right = Math.max(12,innerWidth-Math.min(innerWidth,mapBounds?.right ?? innerWidth)+8);
const layerAtBottom = layers?.height>0 && layers.top>innerHeight/2;
const trayBottom = Math.max(12,innerHeight-mapBottom+8,layerAtBottom?innerHeight-layers.top+6:0);
const put = (el,key,value) => {const v=Math.round(value)+'px';if(el.style.getPropertyValue(key)!==v)el.style.setProperty(key,v);};
if (tray) {
if (!dockOwnsControls && tray.parentElement!==host) host.appendChild(tray);
if (!tray.hasAttribute('data-satnav-dock')) tray.setAttribute('data-satnav-dock','');
put(tray,'--satnav-dock-right',right);put(tray,'--satnav-tray-bottom',trayBottom);
}
const trayHeight = Math.max(44,tray?.getBoundingClientRect().height||44);
const toggleBottom = trayBottom+trayHeight+6;
put(toggle,'--satnav-dock-right',right);put(toggle,'--satnav-dock-bottom',toggleBottom);
const panelBottom = toggleBottom+Math.max(44,toggle.getBoundingClientRect().height)+6;
put(panel,'--satnav-dock-right',right);put(panel,'--satnav-panel-bottom',panelBottom);
put(panel,'--satnav-panel-height',Math.max(64,innerHeight-panelBottom-Math.max(48,mapBounds?.top??0)-8));
const next = window.__GRIDATLAS_V9_MAP__;
if (next && next.getLayer('l-sat') && next !== map) {
map?.off('click',mapClick);
map?.off('dragstart',pauseFollow);
map?.off('zoomstart',pauseGesture);
map?.off('rotatestart',pauseGesture);
map?.off('pitchstart',pauseGesture);
map = next;
planDirty = positionDirty = true;
map.on('click',mapClick);
map.on('dragstart',pauseFollow);
map.on('zoomstart',pauseGesture);
map.on('rotatestart',pauseGesture);
map.on('pitchstart',pauseGesture);
map.resize();
notify('map',map);
}
if (fix && compass.fixQuality(fix) === 'stale') {setFix(null);notice = 'GPS fix is stale';}
installAssetActions();
if (!layerSearch && installUnifiedLayerSearch) {
try {layerSearch = installUnifiedLayerSearch(document);}
catch(error){installUnifiedLayerSearch=null;console.error('Optional Layers search unavailable; native Layers retained',error);}
}
render();
}
panel.satnavSurvey = Object.freeze({
getPins: () => snapshot.pins,
getEndpoints: () => [roles.from ? snapshot.pins[0].coordinate : null, roles.to ? snapshot.pins.at(-1).coordinate : null],
getMap: () => map,
getFix: () => ['usable','poor'].includes(compass.fixQuality(fix)) ? fix : null,
isTracking: () => watch !== null,
isPanelOpen: () => panelOpen,
setPanelOpen,
maths,
distanceKm: maths.distanceKm,
fixQuality: compass.fixQuality,
replacePlan,
leaveExample,
isExample: () => Boolean(localPlan),
setDestination: at => { const changed = setPin('to', at); picking = null; render(); return changed; },
isFollowing: () => followCamera,
transferSearchDestination(handle) {
const at = handle?.at;
if (!map || localPlan) return {ok:false,reason:'Return to your own plan first'};
if (watch !== null) {