GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

SatNav Waypoint Map and 1 more file

A JavaScript file in the atlas folder of GridAtlas that refreshes guidance (`refreshGuidance`), sets pin (`setPin`) and restores local plan (`restoreLocalPlan`).

700 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 540 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. SatNav Gate Walk geodesy · gridatlas / atlas/modules/202611281800-satnav-gate-walk.js lines 1–287
  2. SatNav Waypoint Map geodesy · gridatlas / atlas/modules/202611281800-satnav-waypoint-map.js lines 1–413

SatNav Gate Walk

A JavaScript file in the atlas folder of GridAtlas that attaches map (`attachMap`), syncs plan (`syncPlan`) and reads inputs for SatNav walk mode.

geodesygridatlas / atlas/modules/202611281800-satnav-gate-walk.js · lines 1–287 of 287 · version 2026-11-28 18:00 · Not reached from any entry point (candidate for review) · pattern clearHeader (shared by 10 files)

What it does
It maps its content. Defines 13 functions or classes, including mount, choose, distance, bearing, clearHeader. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): 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.
Inputs & outputs
In: form fields (user input).
What it achieves
It attaches map (`attachMap`), syncs plan (`syncPlan`) and stops walk (`stopWalk`). Explicit walking on the existing field map. It responds to resize, fullscreenchange and webkitfullscreenchange events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
mount, choose, distance, bearing, clearHeader, draw, attachMap, clearRoute, calculate, syncPlan, liveRoute, render
Defines here
mount, choose, distance, bearing, clearHeader, draw, attachMap, clearRoute, calculate, syncPlan, liveRoute, render, stopWalk
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/202611281800-satnav-gate-walk.js:1-287 · blob f5c14a55d8af5b5efa7340495c80d3d8fbf401e0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* Explicit walking on the existing field map. Location is owned by the waypoint cartridge. */
void async function () {
  const root = new URL('../../../', location.href);
  const [{createDirectWalk,walkTargets}, compass, {createRouteFollower}, {mountGateControls}, {prepareGateJob}] = await Promise.all([
    import(new URL('tools/satnav/walk/direct.mjs',root)),
    import(new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs',root)),
    import(new URL('tools/satnav/line/route-follower.mjs',root)),
    import(new URL('tools/satnav/walk/gate/jobs/controls.mjs',root)),
    import(new URL('tools/satnav/walk/gate/jobs/plan.mjs',root)),
  ]);
  let mounted = false;
  function mount() {
    const panel = document.getElementById('satnav-compact');
    const api = panel?.satnavSurvey;
    if (mounted || !api) return;
    mounted = true;
    const css = document.createElement('style');
    css.textContent = `
      #satnav-compact{--satnav-walk-top:max(env(safe-area-inset-top,0px),var(--gridatlas-menu-bar-clear,8px),var(--satnav-measured-menu-bottom,8px));top:var(--satnav-walk-top)!important;max-height:calc(100dvh - var(--satnav-walk-top) - 42px)!important}
      #gridatlas-menu-bar{z-index:10045!important}
      body:has(#gridatlas-menu-bar .gm-open) #satnav-compact{visibility:hidden}
      #satnav-compact #satnav-guide{display:none!important}
      #satnav-walk-actions{display:grid;grid-template-columns:1fr 1fr;gap:4px}
      #satnav-walk-actions select{min-height:44px;min-width:0;width:100%;border:1px solid #367078;border-radius:6px;background:#081820;color:#e4f7f7;font:inherit}
      #satnav-walk-actions #satnav-walk-start{border-color:#60d6d9}
      #satnav-walk-guidance{background:#081820ed;color:#b2faf7;margin:0;padding:4px 7px;border-radius:4px;font-size:12px;line-height:1.35}
      #satnav-walk-guidance:empty{display:none}
      #satnav-walk-source{background:#081820ed;padding:4px 7px;border-radius:4px;font-size:11px}
      #satnav-gate-actions{padding:3px 7px;background:#081820ed;color:#b2faf7}
      #satnav-gate-actions[hidden]{display:none}
      #satnav-gate-actions button{min-height:44px;padding:4px 8px}
      #satnav-gate-actions output:not(:empty){display:block;padding:4px 0}
      #satnav-compact .satnav-job-name{display:none}
      #satnav-compact .satnav-job-endpoint[aria-pressed=false] span{display:none}
      #satnav-compact .satnav-job-endpoint[aria-pressed=false] .satnav-job-name{display:inline-block;max-width:calc(100% - 46px);vertical-align:middle;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
      #satnav-gate-switch{margin:0;padding:4px 7px;background:#081820ed;color:#b2faf7;font-size:12px}
      #satnav-walk-source a{color:#8bf7f7}
    `;
    document.head.append(css);
    const row = document.createElement('div');
    row.id = 'satnav-walk-actions';
    row.innerHTML = '<select id="satnav-walk-mode" aria-label="Guidance mode"><option value="direct">Direct to pin</option><option value="walking">Walking route</option></select><button id="satnav-walk-start" type="button">Start walk</button><button id="satnav-walk-stop" type="button" hidden>Stop walk</button>';
    const message = document.createElement('p');
    message.id = 'satnav-walk-guidance';
    message.setAttribute('role','status');
    const sourceNote = document.createElement('details');
    sourceNote.id = 'satnav-walk-source';sourceNote.hidden = true;
    sourceNote.innerHTML = '<summary>Footpath source and restrictions</summary><span></span> <a target="_blank" rel="noopener">Council closures</a> · <a target="_blank" rel="noopener">Licence</a>';
    document.getElementById('satnav-to').after(row,message,sourceNote);
    const start = row.querySelector('#satnav-walk-start'), stop = row.querySelector('#satnav-walk-stop');
    const mode = row.querySelector('select');
    const gps = panel.querySelector('#satnav-location'), stopGps = panel.querySelector('#satnav-stop');
    const choose = () => panel.querySelector('[data-loop]')?.getAttribute('aria-pressed') === 'true';
    const direct = createDirectWalk(api.maths,compass);
    const distance = m => m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(2) + ' km';
    const bearing = n => Math.round(n) % 360 + '° true';
    const lineId = 'satnav-active-walking-route';
    let active = false, stopped = false, targets = [], walkingOrigin = null;
    let routerPromise = null, key = '', request = 0, routeState = 'none', geometry = null, follow = null;
    let routeMap = null, drawn = null, arrived = false;

    // Only the built-in replay is temporary. A file the crew opens is their plan.
    const gateApi = {...api, replacePlan: points => api.replacePlan(points, {example: mode.value === 'gate'})};
    const gate = mountGateControls({api:gateApi, compass, message, start, mode, render, isActive:() => active});

    panel.openSatnavGateJob = doc => {
      const job = prepareGateJob(doc, api.maths, compass);
      if (active) stop.click();
      if (choose()) panel.querySelector('[data-loop]').click();
      stopped = false;
      walkingOrigin = null;
      arrived = false;
      direct.restart();
      gate.useJob(job);
      syncPlan();
      const {name, widthM} = job.plan.gate;
      return [name + ' · ' + widthM + ' m opening', job.plan.assetName, job.warning].filter(Boolean).join(' · ');
    };

    let observedMenu = null;
    function clearHeader() {
      const menu = document.getElementById('gridatlas-menu-bar');
      if (observedMenu !== menu) {
        if (observedMenu) menuSize?.unobserve(observedMenu);
        observedMenu = menu;
        if (menu) menuSize?.observe(menu);
      }
      const px = Math.ceil(menu?.getBoundingClientRect().bottom ?? 0) + 8;
      panel.style.setProperty('--satnav-measured-menu-bottom',px + 'px');
    }
    const menuSize = typeof ResizeObserver === 'function' ? new ResizeObserver(clearHeader) : null;
    clearHeader();
    // The existing GridAtlas bar can mount after the SatNav cartridge.
    if (!observedMenu) {
      const discovery = new MutationObserver(() => {clearHeader();if (observedMenu) discovery.disconnect();});
      discovery.observe(document.body,{subtree:true,childList:true});
    }
    window.addEventListener('resize',clearHeader);
    window.visualViewport?.addEventListener('resize',clearHeader);
    document.addEventListener('fullscreenchange',clearHeader);
    document.addEventListener('webkitfullscreenchange',clearHeader);
    panel.addEventListener('click', event => {
      const control = event.target.closest?.('button');
      if (control && ['satnav-from','satnav-to','satnav-add','satnav-replace'].includes(control.id)
          && control.getAttribute('aria-pressed') !== 'true') {
        const zoom = api.getMap()?.doubleClickZoom;
        // A deliberate toolbar selection interrupts the previous map tap pair.
        if (zoom?.isEnabled()) {zoom.disable();zoom.enable();}
      }
    },true);

    function draw() {
      if (!routeMap?.getLayer('l-sat')) return;
      let source = routeMap.getSource(lineId);
      const data = {type:'FeatureCollection',features:geometry ?
        [{type:'Feature',properties:{kind:'mapped-footpath'},geometry}] : []};
      if (!source) {routeMap.addSource(lineId,{type:'geojson',data});source = routeMap.getSource(lineId);}
      else if (drawn !== geometry) source.setData(data);
      if (!routeMap.getLayer(lineId)) routeMap.addLayer({id:lineId,type:'line',source:lineId,paint:{'line-color':'#77ed91','line-width':5}},
        routeMap.getLayer('gridatlas-satnav-waypoints-via') ? 'gridatlas-satnav-waypoints-via' : undefined);
      drawn = geometry;
    }
    function attachMap() {
      gate.attachMap();
      const next = api.getMap();
      if (next !== routeMap) {
        routeMap?.off('style.load',draw);routeMap = next;
        routeMap?.on('style.load',draw);drawn = null;
      }
      draw();
      clearHeader();
    }
    function clearRoute(status) {
      routeState = status;geometry = null;follow = null;arrived = false;sourceNote.hidden = true;draw();
    }
    async function calculate(points, revision) {
      try {
        routerPromise ??= import(new URL('tools/satnav/walk/council/council-router.mjs',root))
          .then(module => module.loadPedestrianRouter(api.maths)).catch(error => {routerPromise = null;throw error;});
        const route = await routerPromise;
        if (request !== revision) return;
        const coordinates = [];
        let publication;
        for (let i = 1; i < points.length; i++) {
          const result = route(points[i-1],points[i]);
          if (result.status !== 'mapped') {
            if (result.reason === 'footpath-data-unavailable') routerPromise = null;
            clearRoute('unavailable');render();return;
          }
          publication = result;
          const leg = result.geometry.coordinates;
          if (i > 1 && api.maths.distanceKm(...coordinates.at(-1),...leg[0]) > 0.0001) {
            clearRoute('unavailable');render();return;
          }
          for (let j = i === 1 ? 0 : 1; j < leg.length; j++) coordinates.push(leg[j]);
          if (coordinates.length > 20_000) {clearRoute('unavailable');render();return;}
        }
        geometry = {type:'LineString',coordinates};
        follow = createRouteFollower(geometry,api.maths);
        sourceNote.querySelector('span').textContent = publication.attribution + ' ';
        const [closures,licence] = sourceNote.querySelectorAll('a');
        closures.href = publication.closureNotices;licence.href = publication.licence;sourceNote.hidden = false;
        routeState = 'mapped';draw();render();
      } catch {
        if (request === revision) {clearRoute('unavailable');render();}
      }
    }
    function syncPlan() {
      if (gate.selected() && (!gate.matchesPlan() || choose() || (mode.value === 'gate' && !api.isExample()))) {
        mode.value = 'direct';
        gate.select();
        api.leaveExample();
      }
      const pins = api.getPins(), [from] = api.getEndpoints();
      targets = walkTargets(pins,from,choose());
      direct.setTargets(targets);
      if (mode.value === 'walking') {
        const fix = api.getFix();
        if (!from && !walkingOrigin && compass.fixQuality(fix) === 'usable') walkingOrigin = [fix.longitude,fix.latitude];
        const origin = from ?? walkingOrigin;
        const points = origin && targets.length ? [origin,...targets.map(pin => pin.coordinate)] : [];
        const next = JSON.stringify(points);
        if (key !== next) {
          key = next;const revision = ++request;
          clearRoute(points.length >= 2 ? 'loading' : 'none');
          if (points.length >= 2) void calculate(points,revision);
        }
      } else if (key) {key = '';request++;clearRoute('none');}
      render();
    }
    function liveRoute(fix) {
      const now = Date.now();
      const projection = follow(fix,now);
      if (projection.status !== 'ok') return 'Position on mapped path uncertain';
      if (projection.offRoute) return 'Away from mapped footpath';
      const end = geometry.coordinates.at(-1);
      if (projection.remainingM <= 15 && api.maths.distanceKm(fix.longitude,fix.latitude,...end) * 1000 + fix.accuracyM <= 15) arrived = true;
      if (arrived) return 'Arrived at mapped path end';
      const next = geometry.coordinates[projection.segmentIndex + 1];
      const forward = compass.guide(fix,{coordinates:next},now);
      const parts = [distance(projection.remainingM) + ' remaining'];
      if (Number.isFinite(forward?.bearingDeg)) parts.push(bearing(forward.bearingDeg));
      return parts.join(' · ');
    }
    function render() {
      start.hidden = active;stop.hidden = !active;
      const isPath = mode.value === 'walking';
      const label = isPath ? 'Walking route' : 'Direct to pin';
      let text = '';
      if (gate.selected()) text = gate.describe(active, stopped);
      else if (stopped && !active) text = 'Walk stopped';
      else if (isPath && routeState === 'unavailable') text = 'Walking route unavailable here · choose Direct to pin';
      else if (isPath && routeState === 'loading') text = 'Checking mapped footpaths';
      else if (active) {
        const sample = api.getFix();
        const quality = compass.fixQuality(sample);
        if (!targets.length) text = label + ' · Tap TO, then tap your destination on the map';
        else if (quality !== 'usable') text = label + ' · ' + (quality === 'poor' ? 'Waiting for more accurate GPS' : 'Waiting for a fresh GPS fix');
        else if (isPath) text = routeState === 'mapped' ? label + ' · ' + liveRoute(sample) + ' · check current access' : 'Waiting for route origin';
        else {
          const guidance = direct.locate(sample);
          if (guidance.status === 'complete') text = label + ' · Arrived';
          else if (guidance.status === 'guiding') {
            const [, destination] = api.getEndpoints();
            const parts = [label];
            if (targets.length > 1) {
              if (destination) {
                const metres = api.maths.distanceKm(sample.longitude, sample.latitude, ...destination) * 1000;
                parts.push(distance(metres) + ' straight to destination');
              }
              parts.push('Waypoint ' + (guidance.targetIndex + 1) + ' of ' + targets.length, distance(guidance.distanceM) + ' to waypoint');
            } else {
              parts.push(distance(guidance.distanceM) + (destination ? ' to destination' : ' to waypoint'));
            }
            if (Number.isFinite(guidance.bearingDeg)) parts.push(bearing(guidance.bearingDeg));
            if (targets.length > 1) parts.push(distance(guidance.remainingM) + ' remaining via pins');
            text = parts.join(' · ');
          } else text = label + ' · Waiting for a fresh GPS fix';
        }
      } else if (isPath && routeState === 'mapped') text = 'Walking route ready · check current access';
      if (message.textContent !== text) message.textContent = text;
    }
    start.onclick = () => {
      active = true;stopped = false;arrived = false;walkingOrigin = null;direct.restart();
      // This is the UI's existing user-initiated watch. It freezes a missing
      // FROM on the first usable fix and preserves an imported or hand-picked FROM.
      if (!api.isTracking()) gps.click();
      if (!api.isTracking()) {active = false;stopped = true;}
      if (active) gate.begin();
      syncPlan();
    };
    function stopWalk(reason) {
      gate.end(typeof reason === 'string' ? reason : 'location stopped');
      active = false;stopped = true;walkingOrigin = null;
      request++;key = '';clearRoute('none');direct.restart();render();
    }
    stop.onclick = () => {stopWalk('stop walk');if (api.isTracking()) stopGps.click();};
    mode.onchange = () => {
      walkingOrigin = null;stopped = false;arrived = false;direct.restart();
      gate.select();
      if (!gate.selected()) api.leaveExample();
      syncPlan();
    };
    panel.addEventListener('satnav:fix',() => {
      if (stopped && !active) {render();return;}
      if (mode.value === 'walking' && !walkingOrigin && !api.getEndpoints()[0]) syncPlan();
      else render();
    });
    panel.addEventListener('satnav:stop',stopWalk);
    panel.addEventListener('satnav:pins',syncPlan);
    panel.addEventListener('satnav:map',attachMap);
    panel.addEventListener('click',event => {if (event.target.closest?.('[data-loop]')) syncPlan();});
    document.addEventListener('visibilitychange',render);
    window.addEventListener('online',() => {
      if (mode.value === 'walking' && routeState === 'unavailable') {routerPromise = null;key = '';syncPlan();}
    });
    window.addEventListener('pagehide',stopWalk);
    attachMap();
    if (!api.getPins().length && new URLSearchParams(location.search).has('pilot')) {
      mode.value = 'gate';
      gate.select();
    }
    syncPlan();
  }
  document.addEventListener('satnav:ready',mount);
  mount();
}().catch(error => console.error('SatNav walking controls failed',error));

SatNav Waypoint Map

A JavaScript file in the atlas folder of GridAtlas that refreshes guidance (`refreshGuidance`), sets pin (`setPin`) and restores local plan (`restoreLocalPlan`).

geodesygridatlas / atlas/modules/202611281800-satnav-waypoint-map.js · lines 1–413 of 478 · version 2026-11-28 18:00 · Not reached from any entry point (candidate for review) · pattern restoreLocalPlan (shared by 7 files)

What it does
It maps its content. Defines 25 functions or classes, including notify, updateText, distanceText, bearingText, collection. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): 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.
What it achieves
It updates text (`updateText`), refreshes guidance (`refreshGuidance`) and sets pin (`setPin`). Based on the immutable PR113 compact map and GPS lifecycle. It responds to visibilitychange, offline and online events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
notify, updateText, distanceText, bearingText, collection, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample
Defines here
notify, updateText, distanceText, bearingText, collection, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample, replacePlan, undo, setFix, fieldState, refreshSources, guidanceText, render, arm, mapClick, selectedIndex, stopTracking, centreOnFix
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/202611281800-satnav-waypoint-map.js:1-413 · blob f965563e512aeb203ce5da6d3ef21c3cfa5d5aa5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* GridAtlas waypoint map. Based on the immutable PR113 compact map and GPS lifecycle. */
void async function () {
  const root = new URL('../../../', location.href);
  const vendor = new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/', root);
  const [maths, compass, { point }, { createWaypointState }, { createWaypointGuidance }, { assessFieldState }] = 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.mjs', root)),
    import(new URL('tools/satnav/field-reliability/state.mjs', root)),
  ]);

  const style = document.createElement('style');
  style.textContent = `
    body .dashboard{position:fixed!important;inset:0!important;height:100dvh!important;width:100vw!important;padding:0!important;display:block!important}
    body #map-container{position:absolute!important;inset:0!important;width:100%!important;height:100%!important;border:0!important;border-radius:0!important}
    body .hud-header,body .scada-wrapper,body .podcast-shoutout,body .search-bar-wrapper,body .map-controls,body #btn-fullscreen,body #fs-curtain-tab,body #fs-letterhead{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{top:max(8px,env(safe-area-inset-top));width:min(204px,calc(100vw - 20px));display:grid;gap:4px;max-height:calc(100dvh - 68px);overflow:auto;overscroll-behavior:contain}
    #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>
    <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>';
  document.body.append(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 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 length = maths.distanceKm(...previous, ...pin.coordinate);
      planDistance += length * 1000;
      if (length > 1) { longLegs++; continue; }
      if (Math.abs(previous[0] - pin.coordinate[0]) > 180) { dateLineLegs++; continue; }
      if (length > 0) features.push({type:'Feature', properties:{role:'selected-section'}, geometry:{type:'LineString',coordinates:[previous,pin.coordinate]}});
    }
    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]});
    }
    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 !== '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(' · ');
  }
  function render() {
    refreshSources();
    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 ? 'Centre GPS' : 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('Lines shown for legs up to 1 km');
    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(' · '));
    updateText(controls.guide, guidanceText());
  }
  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;
    lastFixMs = -Infinity;
    pendingLocation = false;
    notice = message;
    setFix(null);
    notify('stop');
    render();
  }
  function centreOnFix() {
    if (!pendingLocation || compass.fixQuality(fix) !== 'usable') return;
    pendingLocation = false;
    const at = [fix.longitude,fix.latitude];
    // An imported or hand-picked start belongs to the plan. Starting the GPS
    // centres the map. Only an empty FROM field takes this first measured fix.
    try { if (!roles.from) setPin('from', at, true); }
    catch (error) { notice = error.message; return; }
    map?.jumpTo({center:at,zoom:Math.max(15,map.getZoom())});
  }
  controls.location.onclick = () => {
    if (!isSecureContext || !navigator.geolocation) {notice = 'Location needs HTTPS and device GPS';render();return;}
    pendingLocation = true;
    permissionDenied = false;
    picking = null;
    notice = 'Waiting for GPS';
    if (watch !== null) {
      if (compass.fixQuality(fix) === 'usable') {notice = '';centreOnFix();}
      render();
      return;
    }
    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:1000,timeout:10000});
      notify('watch');
    } catch {stopTracking('Location could not start');}
    render();
  };