GLOBALGRID2050 / EXPLORE CODE

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

SatNav Convergence 2km Gate Walk and 2 more files

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

656 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 590 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. G204 Gps Camera geodesy · gridatlas / atlas/modules/g204-gps-camera.js lines 651–731
  2. G204 Start Walk geodesy · gridatlas / atlas/modules/g204-start-walk.js lines 1–287
  3. SatNav Convergence 2km Gate Walk geodesy · gridatlas / atlas/modules/satnav-convergence-2km-gate-walk.js lines 1–288

G204 Gps Camera

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`).

Set aside from the main view: 98% of its lines are the same as atlas/modules/g203-03-gps-camera-candidate.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with G203 03 Gps Camera Candidate; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9766 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-03-gps-camera-candidate.js:1-735 e48c743713123f1c7d099641118d83aa4886286d
  • sha256 219589528cfeafa2fe9031fb272c29236f4f9d0df9e5cad559d2a7782d80da00
  • target sha256 198e80cfdb7ed663a5633413ee51e8f77188e3311c6fc081e1cb6b3ca1e50790
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g204-gps-camera.js · lines 651–731 of 731 (continued from section 589) · Not reached from any entry point (candidate for review) · 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.
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
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan
Defines here
none
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/g204-gps-camera.js:651-731 · blob a2f977d2bf13bf51a3cbb8e4bda0b78c9e188b0a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
    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) {
        const result = prepareAssetDestination(maths,fix,at,true,fieldState(fix).gpsState);
        if (!result.ok) return result;
        replacePlan(result.coordinates);
      } else {
        const pins = snapshot.pins.map(pin=>pin.coordinate);
        if (roles.to) pins.pop();
        const previous = pins.at(-1) || null;
        const result = validateDestinationLeg(previous,at,(a,b)=>maths.distanceKm(...a,...b));
        if (!result.ok) return result;
        if (previous && classifyDirectLeg(maths,previous,at).status === 'coincident') return {ok:false,reason:'Unsupported direct leg'};
        if (!setPin('to',at)) return {ok:false,reason:'Destination unchanged'};
      }
      picking = null; notice = 'Destination: ' + handle.label; setPanelOpen(true);
      return {ok:true};
    },
    setClosedLoop(enabled) {
      if (enabled && (!roles.from || snapshot.pins.length < 3 || snapshot.pins.length >= snapshot.maxPins)) return false;
      const previous = closed;
      closed = Boolean(enabled);
      if (closed !== previous) {refreshGuidance();render();}
      return true;
    },
  });
  refresh();
  document.dispatchEvent(new Event('satnav:ready'));
  let timer = setInterval(refresh, 500);
  window.addEventListener('pagehide', () => {clearInterval(timer); stopTracking('Location stopped');});
  window.addEventListener('pageshow', event => {if (event.persisted) {refresh();timer = setInterval(refresh, 500);}});
}().catch(error => {
  console.error('SatNav waypoint map failed', error);
  const message = document.createElement('p');
  message.setAttribute('role','alert');
  message.textContent = 'SatNav controls could not load. Reload to try again.';
  document.body.prepend(message);
});

G204 Start Walk

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

Set aside from the main view: 99% of its lines are the same as atlas/modules/202611281800-satnav-gate-walk.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with SatNav Gate Walk; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9919 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611281800-satnav-gate-walk.js:1-287 f5c14a55d8af5b5efa7340495c80d3d8fbf401e0
  • sha256 d4004dceaaeab48035911c3a108e4b61a94988e34e27c842ad99bd56a49426a9
  • target sha256 3a5b4e0b791dbec71b48d78201662932def15c8d374aff2101553624fbdd6aa9
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g204-start-walk.js · lines 1–287 of 287 · 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 'walk'): 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/g204-start-walk.js:1-287 · blob b6954d184f14d09bebc12f99cd90163a1c94c39d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
/* 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-convergence-unlimited.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 Convergence 2km 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.

Set aside from the main view: 99% of its lines are the same as atlas/modules/202611281800-satnav-gate-walk.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with SatNav Gate Walk; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9879 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611281800-satnav-gate-walk.js:1-287 f5c14a55d8af5b5efa7340495c80d3d8fbf401e0
  • sha256 3a1692a012e5c2e466bd4342d14f5f4457f16cc0226b27f3c982a40d88b93aab
  • target sha256 3a5b4e0b791dbec71b48d78201662932def15c8d374aff2101553624fbdd6aa9
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/satnav-convergence-2km-gate-walk.js · lines 1–288 of 288 · 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/satnav-convergence-2km-gate-walk.js:1-288 · blob 1821f793c562f8d0cc841994848d5bc0ea364906 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
/* 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-convergence-2km.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 === 'over-limit') text = label + ' · Direct leg exceeds 2 km · choose a nearer waypoint or destination';
          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));