3hstack commited on
Commit
34dd717
·
verified ·
1 Parent(s): 611fdac

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -89
app.py CHANGED
@@ -385,13 +385,17 @@ PAGE = r'''<!DOCTYPE html>
385
  .truck{filter:drop-shadow(0 2px 5px rgba(0,0,0,.7))}
386
  .arrow{pointer-events:none}
387
  #map.routed .leaflet-tile-pane{filter:brightness(.72) saturate(.85)}
 
 
 
 
388
  </style>
389
  </head>
390
  <body>
391
 
392
  <header>
393
  <h1>Route Em</h1>
394
- <span class="sub">Shortest closed route covering every road &mdash; both sides &mdash; solved exactly (Directed Chinese Postman)</span>
395
  </header>
396
 
397
  <main>
@@ -491,7 +495,7 @@ const roadLabels = L.tileLayer(ESRI + 'World_Transportation/MapServer/tile/{z}/{
491
  const placeLabels = L.tileLayer(ESRI + 'World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}', {maxZoom:19});
492
  const satHybrid = L.layerGroup([satellite, roadLabels, placeLabels]);
493
  streets.addTo(map);
494
- L.control.layers({'Street':streets, 'Satellite':satHybrid}, {}, {position:'topright', collapsed:false}).addTo(map);
495
  map.createPane('routePane'); map.getPane('routePane').style.zIndex = 450;
496
 
497
  const drawn = new L.FeatureGroup().addTo(map);
@@ -575,32 +579,13 @@ solveBtn.onclick = async () => {
575
  } catch (err) { msg('Solve failed: ' + err, 'err'); }
576
  finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
577
  };
578
- // ================= route data + PHASES =================
579
  let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
580
- let PHASES=[]; // [{color, name, startM, endM}]
581
- const NPHASE_M = 402; // ~0.25 mi per phase target
582
-
583
- // distinct, high-contrast leg colors (cycled if a route has many legs)
584
- const PHASE_COLORS = ['#3b82f6','#06b6d4','#22c55e','#eab308','#f97316','#ef4444',
585
- '#a855f7','#ec4899','#14b8a6','#84cc16'];
586
-
587
- function phaseCount(totalM){ return Math.max(3, Math.min(10, Math.round(totalM / NPHASE_M))); }
588
- function phaseOf(m){ // which leg does distance m fall in
589
- const n = PHASES.length;
590
- let i = Math.floor(m / TOTAL_M * n);
591
- return Math.max(0, Math.min(i, n - 1));
592
- }
593
 
594
- // shift a segment ~6 m to the RIGHT of travel so both curbs of a two-way street show
595
- const CURB_OFFSET_M = 6;
596
- function offsetRight(a, b, meters){
597
- const latR = (a.lat + b.lat) / 2 * Math.PI / 180;
598
- const dxE = (b.lng - a.lng) * Math.cos(latR), dyN = (b.lat - a.lat);
599
- const mag = Math.hypot(dxE, dyN) || 1e-9;
600
- const pe = dyN / mag, pn = -dxE / mag;
601
- const dLat = pn * meters / 111320, dLng = pe * meters / (111320 * Math.cos(latR));
602
- return [L.latLng(a.lat + dLat, a.lng + dLng), L.latLng(b.lat + dLat, b.lng + dLng)];
603
- }
604
  function bearing(a, b){
605
  const r = Math.PI/180;
606
  const y = Math.sin((b.lng-a.lng)*r) * Math.cos(b.lat*r);
@@ -610,53 +595,56 @@ function bearing(a, b){
610
 
611
  function render(d){
612
  stop();
613
- [routeLayer, trailLine, arrowLayer, truck].forEach(l => l && map.removeLayer(l));
614
- const feats = d.geojson.features;
615
 
616
- // build centre-line path + offset draw coords + cumulative distance
617
  PATH = []; TOTAL_M = 0;
618
  feats.forEach(f => {
619
  const c = f.geometry.coordinates;
620
  const a = L.latLng(c[0][1], c[0][0]), b = L.latLng(c[1][1], c[1][0]);
621
  const len = map.distance(a, b);
622
- const [oa, ob] = offsetRight(a, b, CURB_OFFSET_M);
623
- PATH.push({a, b, oa, ob, len, cum: TOTAL_M, name: f.properties.name,
624
  deadhead: f.properties.deadhead, order: f.properties.order});
625
  TOTAL_M += len;
626
  });
 
627
 
628
- // define phases (equal-distance legs)
629
- const np = phaseCount(TOTAL_M);
630
- PHASES = [];
631
- for (let k = 0; k < np; k++)
632
- PHASES.push({color: PHASE_COLORS[k % PHASE_COLORS.length],
633
- name: 'Leg ' + (k+1),
634
- startM: TOTAL_M * k / np, endM: TOTAL_M * (k+1) / np});
635
 
636
- DRIVE_MIN = d.stats.drive_min; STEPS = d.directions;
 
 
 
 
 
637
 
638
- // draw route: dark casing under a phase-colored line, each pass offset
639
- routeLayer = L.layerGroup([], {pane:'routePane'});
640
  PATH.forEach(s => {
641
- const line = [s.oa, s.ob];
642
- const mid = s.cum + s.len/2;
643
- const col = s.deadhead ? '#ff3355' : PHASES[phaseOf(mid)].color;
644
- L.polyline(line, {pane:'routePane', color:'#05070c', weight: s.deadhead ? 6 : 8.5,
645
- opacity:.6, lineCap:'round'}).addTo(routeLayer);
646
- L.polyline(line, {pane:'routePane', color:col, weight: s.deadhead ? 4 : 5.5,
647
- opacity:.98, lineCap:'round',
648
- dashArray: s.deadhead ? '3,7' : null}).addTo(routeLayer)
649
- .bindTooltip('#' + s.order + ' ' + s.name + ' — ' + (s.len/1609.344).toFixed(2) + ' mi' +
650
- (s.deadhead ? ' (deadhead, no delivery)' : ''));
651
  });
652
- routeLayer.addTo(map);
653
 
654
  buildArrows();
655
- trailLine = L.polyline([], {pane:'routePane', color:'#ffffff', weight:9, opacity:.85, lineCap:'round'}).addTo(map);
656
- truck = L.marker(PATH[0].a, {icon: truckIcon(0), zIndexOffset:1000, interactive:false}).addTo(map);
657
 
658
- const bb = L.latLngBounds([]); PATH.forEach(s => { bb.extend(s.oa); bb.extend(s.ob); });
659
- map.fitBounds(bb, {padding:[28,28]});
 
 
 
 
 
 
 
 
 
 
660
  buildLegend();
661
  document.getElementById('map').classList.add('routed');
662
  document.getElementById('play').classList.add('on');
@@ -665,20 +653,19 @@ function render(d){
665
  seek(0);
666
  }
667
 
668
- // arrows: normal size, colored to match their phase, pointing the drive direction
669
  function buildArrows(){
670
  if (arrowLayer) map.removeLayer(arrowLayer);
671
  arrowLayer = L.layerGroup();
672
- const stride = Math.max(1, Math.ceil(PATH.length / 350));
673
  PATH.forEach((s, i) => {
674
  if (i % stride) return;
675
- if (s.len < 14) return;
676
- const mid = L.latLng((s.oa.lat+s.ob.lat)/2, (s.oa.lng+s.ob.lng)/2);
677
- const col = s.deadhead ? '#ff8a97' : PHASES[phaseOf(s.cum + s.len/2)].color;
678
- L.marker(mid, {interactive:false, icon: L.divIcon({className:'', iconSize:[16,16], iconAnchor:[8,8],
679
  html:'<div class="arrow" style="transform:rotate(' + bearing(s.a, s.b) + 'deg)">' +
680
- '<svg width="16" height="16" viewBox="0 0 16 16">' +
681
- '<path d="M8 1 L12.5 12 L8 9.4 L3.5 12 Z" fill="' + col + '" stroke="#05070c" stroke-width="1.1"/>' +
682
  '</svg></div>'})}).addTo(arrowLayer);
683
  });
684
  if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
@@ -688,19 +675,13 @@ document.getElementById('arrowsOn').onchange = e => {
688
  e.target.checked ? arrowLayer.addTo(map) : map.removeLayer(arrowLayer);
689
  };
690
 
691
- function buildLegend(){
692
- const el = document.getElementById('legend');
693
- let h = '<div class="ttl">Route legs (in order)</div>';
694
- PHASES.forEach(p => {
695
- h += '<div class="lg"><span class="sw" style="background:' + p.color + '"></span>' +
696
- p.name + ' &middot; ' + (p.startM/1609.344).toFixed(1) + '–' +
697
- (p.endM/1609.344).toFixed(1) + ' mi</div>';
698
- });
699
- h += '<div class="lg" style="margin-top:5px"><span class="sw" style="background:#ff3355"></span>' +
700
- 'deadhead (repeat)</div>';
701
- h += '<div class="lg"><span class="sw" style="background:#ffffff"></span>already driven</div>';
702
- el.innerHTML = h;
703
- el.style.display = 'block';
704
  }
705
 
706
  function truckIcon(deg){
@@ -710,12 +691,24 @@ function truckIcon(deg){
710
  '<circle cx="16" cy="16" r="14" fill="#05070c" opacity=".6"/>' +
711
  '<g transform="translate(16,16)">' +
712
  '<rect x="-6.5" y="-8.5" width="13" height="17" rx="2.5" fill="#ffffff"/>' +
713
- '<rect x="-6.5" y="-8.5" width="13" height="6" rx="2" fill="#3b82f6"/>' +
714
  '<rect x="-8" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
715
  '<rect x="5" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
716
- '<path d="M0 -13 L4.5 -8.5 L-4.5 -8.5 Z" fill="#eab308"/>' +
717
  '</g></svg></div>'});
718
  }
 
 
 
 
 
 
 
 
 
 
 
 
719
  // ================= animation =================
720
  let pos=0, playing=false, raf=null, last=0;
721
  const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
@@ -759,17 +752,17 @@ function seek(m){
759
  }
760
 
761
  function updateHud(s){
762
- const pct = pos/TOTAL_M, ph = PHASES[phaseOf(pos)];
763
  const leg = document.getElementById('hudLeg');
764
- leg.textContent = ph.name + ' of ' + PHASES.length;
765
- leg.style.background = ph.color;
766
  document.getElementById('hudStreet').innerHTML =
767
- (s.deadhead ? '<span style="color:#ff3355">&#8631; </span>' : '') + s.name;
768
  document.getElementById('hudMeta').textContent =
769
  (pos/1609.344).toFixed(2) + ' / ' + (TOTAL_M/1609.344).toFixed(2) + ' mi · ~' +
770
  Math.round(DRIVE_MIN*pct) + ' min in';
771
  document.getElementById('hudBar').style.width = (pct*100) + '%';
772
- document.getElementById('hudBar').style.background = ph.color;
773
  let acc=0, idx=0;
774
  for (let k=0;k<STEPS.length;k++){ acc += STEPS[k].mi*1609.344; idx=k; if (pos <= acc) break; }
775
  document.querySelectorAll('#out .street.now').forEach(r => r.classList.remove('now'));
@@ -793,13 +786,11 @@ function renderStats(s){
793
  if (s.excluded_nodes)
794
  h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
795
  ' intersection(s) were unreachable from the main network and left out.</div>';
796
- h += '<div class="hd" style="margin-top:8px">Turn-by-turn (colored by leg)</div>';
797
- let acc = 0;
798
  STEPS.forEach(x => {
799
- const col = x.deadhead ? '#ff3355' : PHASES[phaseOf(acc)].color;
800
- acc += x.mi * 1609.344;
801
  h += '<div class="street" data-step="' + x.step + '" style="border-left-color:' + col + '">' +
802
- '<span>' + x.step + '. ' + (x.deadhead ? '<i style="color:#ff3355">(deadhead)</i> ' : '') +
803
  x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
804
  });
805
  document.getElementById('out').innerHTML = h;
 
385
  .truck{filter:drop-shadow(0 2px 5px rgba(0,0,0,.7))}
386
  .arrow{pointer-events:none}
387
  #map.routed .leaflet-tile-pane{filter:brightness(.72) saturate(.85)}
388
+ .flow{stroke-dasharray:14 12;animation:flow .9s linear infinite}
389
+ @keyframes flow{to{stroke-dashoffset:-26}}
390
+ .pin{font:700 10px sans-serif;color:#fff;text-align:center;line-height:1;text-shadow:0 1px 3px #000;white-space:nowrap}
391
+ .pin svg{display:block;margin:0 auto}
392
  </style>
393
  </head>
394
  <body>
395
 
396
  <header>
397
  <h1>Route Em</h1>
398
+ <span class="sub">The shortest possible loop that covers every street on both sides</span>
399
  </header>
400
 
401
  <main>
 
495
  const placeLabels = L.tileLayer(ESRI + 'World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}', {maxZoom:19});
496
  const satHybrid = L.layerGroup([satellite, roadLabels, placeLabels]);
497
  streets.addTo(map);
498
+ L.control.layers({'Street':streets, 'Satellite':satHybrid}, {}, {position:'bottomleft', collapsed:false}).addTo(map);
499
  map.createPane('routePane'); map.getPane('routePane').style.zIndex = 450;
500
 
501
  const drawn = new L.FeatureGroup().addTo(map);
 
579
  } catch (err) { msg('Solve failed: ' + err, 'err'); }
580
  finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
581
  };
582
+ // ================= route data =================
583
  let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
584
+ let flowCasing=null, flowLine=null, deadLayer=null, startPin=null, endPin=null;
585
+
586
+ const ROUTE_COLOR = '#22d3ee'; // one bright colour for the whole delivering route
587
+ const DEAD_COLOR = '#ff4d5e';
 
 
 
 
 
 
 
 
 
588
 
 
 
 
 
 
 
 
 
 
 
589
  function bearing(a, b){
590
  const r = Math.PI/180;
591
  const y = Math.sin((b.lng-a.lng)*r) * Math.cos(b.lat*r);
 
595
 
596
  function render(d){
597
  stop();
598
+ [flowCasing, flowLine, deadLayer, arrowLayer, trailLine, truck, startPin, endPin]
599
+ .forEach(l => l && map.removeLayer(l));
600
 
601
+ const feats = d.geojson.features;
602
  PATH = []; TOTAL_M = 0;
603
  feats.forEach(f => {
604
  const c = f.geometry.coordinates;
605
  const a = L.latLng(c[0][1], c[0][0]), b = L.latLng(c[1][1], c[1][0]);
606
  const len = map.distance(a, b);
607
+ PATH.push({a, b, len, cum: TOTAL_M, name: f.properties.name,
 
608
  deadhead: f.properties.deadhead, order: f.properties.order});
609
  TOTAL_M += len;
610
  });
611
+ DRIVE_MIN = d.stats.drive_min; STEPS = d.directions;
612
 
613
+ // continuous centre-line of the whole route, in drive order
614
+ const line = [PATH[0].a];
615
+ PATH.forEach(s => line.push(s.b));
 
 
 
 
616
 
617
+ // dark casing, then one bright animated line whose dashes FLOW the drive direction
618
+ flowCasing = L.polyline(line, {pane:'routePane', color:'#05070c', weight:9,
619
+ opacity:.6, lineCap:'round', lineJoin:'round'}).addTo(map);
620
+ flowLine = L.polyline(line, {pane:'routePane', color:ROUTE_COLOR, weight:5,
621
+ opacity:.95, lineCap:'round', lineJoin:'round',
622
+ className:'flow'}).addTo(map);
623
 
624
+ // deadhead (repeat) passes drawn on top, red + dashed, so they read as "no delivery"
625
+ deadLayer = L.layerGroup([], {pane:'routePane'});
626
  PATH.forEach(s => {
627
+ if (!s.deadhead) return;
628
+ L.polyline([s.a, s.b], {pane:'routePane', color:DEAD_COLOR, weight:4.5,
629
+ opacity:.95, dashArray:'2,8', lineCap:'round'})
630
+ .bindTooltip('#' + s.order + ' ' + s.name + ' — deadhead (no delivery)').addTo(deadLayer);
 
 
 
 
 
 
631
  });
632
+ deadLayer.addTo(map);
633
 
634
  buildArrows();
 
 
635
 
636
+ // driven-so-far trail (grows as the truck moves)
637
+ trailLine = L.polyline([], {pane:'routePane', color:'#ffffff', weight:9,
638
+ opacity:.9, lineCap:'round', lineJoin:'round'}).addTo(map);
639
+
640
+ // single START/END pin -- the route is a closed loop, so both are the same spot
641
+ startPin = L.marker(PATH[0].a, {zIndexOffset:1100,
642
+ icon: pinIcon('START / END', '#22c55e')}).addTo(map);
643
+
644
+ truck = L.marker(PATH[0].a, {icon: truckIcon(0), zIndexOffset:1200, interactive:false}).addTo(map);
645
+
646
+ const bb = L.latLngBounds([]); line.forEach(p => bb.extend(p));
647
+ map.fitBounds(bb, {padding:[30,30]});
648
  buildLegend();
649
  document.getElementById('map').classList.add('routed');
650
  document.getElementById('play').classList.add('on');
 
653
  seek(0);
654
  }
655
 
656
+ // periodic arrowheads along the route, all one colour, pointing the drive direction
657
  function buildArrows(){
658
  if (arrowLayer) map.removeLayer(arrowLayer);
659
  arrowLayer = L.layerGroup();
660
+ const stride = Math.max(1, Math.ceil(PATH.length / 90)); // fewer, cleaner
661
  PATH.forEach((s, i) => {
662
  if (i % stride) return;
663
+ if (s.len < 25) return;
664
+ const mid = L.latLng((s.a.lat+s.b.lat)/2, (s.a.lng+s.b.lng)/2);
665
+ L.marker(mid, {interactive:false, icon: L.divIcon({className:'', iconSize:[18,18], iconAnchor:[9,9],
 
666
  html:'<div class="arrow" style="transform:rotate(' + bearing(s.a, s.b) + 'deg)">' +
667
+ '<svg width="18" height="18" viewBox="0 0 18 18">' +
668
+ '<path d="M9 1.5 L14 13 L9 10.2 L4 13 Z" fill="#eafcff" stroke="#05070c" stroke-width="1.2"/>' +
669
  '</svg></div>'})}).addTo(arrowLayer);
670
  });
671
  if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
 
675
  e.target.checked ? arrowLayer.addTo(map) : map.removeLayer(arrowLayer);
676
  };
677
 
678
+ function pinIcon(label, color){
679
+ return L.divIcon({className:'', iconSize:[54,34], iconAnchor:[27,32], html:
680
+ '<div class="pin"><svg width="26" height="30" viewBox="0 0 26 30">' +
681
+ '<path d="M13 29 C13 29 24 17 24 11 A11 11 0 1 0 2 11 C2 17 13 29 13 29 Z" ' +
682
+ 'fill="' + color + '" stroke="#05070c" stroke-width="1.5"/>' +
683
+ '<circle cx="13" cy="11" r="4.5" fill="#0f1115"/></svg>' +
684
+ '<div style="margin-top:-2px">' + label + '</div></div>'});
 
 
 
 
 
 
685
  }
686
 
687
  function truckIcon(deg){
 
691
  '<circle cx="16" cy="16" r="14" fill="#05070c" opacity=".6"/>' +
692
  '<g transform="translate(16,16)">' +
693
  '<rect x="-6.5" y="-8.5" width="13" height="17" rx="2.5" fill="#ffffff"/>' +
694
+ '<rect x="-6.5" y="-8.5" width="13" height="6" rx="2" fill="#0891b2"/>' +
695
  '<rect x="-8" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
696
  '<rect x="5" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
697
+ '<path d="M0 -13 L4.5 -8.5 L-4.5 -8.5 Z" fill="#22c55e"/>' +
698
  '</g></svg></div>'});
699
  }
700
+
701
+ function buildLegend(){
702
+ const el = document.getElementById('legend');
703
+ el.innerHTML =
704
+ '<div class="ttl">Route</div>' +
705
+ '<div class="lg"><span class="sw" style="background:' + ROUTE_COLOR + '"></span>drive this way (arrows + flow)</div>' +
706
+ '<div class="lg"><span class="sw" style="background:#ffffff"></span>already driven</div>' +
707
+ '<div class="lg"><span class="sw" style="background:' + DEAD_COLOR + '"></span>deadhead (repeat, no delivery)</div>' +
708
+ '<div class="lg" style="margin-top:5px"><span class="sw" style="background:#22c55e"></span>start / end (loop)</div>';
709
+ el.style.display = 'block';
710
+ }
711
+
712
  // ================= animation =================
713
  let pos=0, playing=false, raf=null, last=0;
714
  const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
 
752
  }
753
 
754
  function updateHud(s){
755
+ const pct = pos/TOTAL_M;
756
  const leg = document.getElementById('hudLeg');
757
+ leg.textContent = Math.round(pct*100) + '% done';
758
+ leg.style.background = s.deadhead ? DEAD_COLOR : ROUTE_COLOR;
759
  document.getElementById('hudStreet').innerHTML =
760
+ (s.deadhead ? '<span style="color:' + DEAD_COLOR + '">&#8631; </span>' : '') + s.name;
761
  document.getElementById('hudMeta').textContent =
762
  (pos/1609.344).toFixed(2) + ' / ' + (TOTAL_M/1609.344).toFixed(2) + ' mi · ~' +
763
  Math.round(DRIVE_MIN*pct) + ' min in';
764
  document.getElementById('hudBar').style.width = (pct*100) + '%';
765
+ document.getElementById('hudBar').style.background = ROUTE_COLOR;
766
  let acc=0, idx=0;
767
  for (let k=0;k<STEPS.length;k++){ acc += STEPS[k].mi*1609.344; idx=k; if (pos <= acc) break; }
768
  document.querySelectorAll('#out .street.now').forEach(r => r.classList.remove('now'));
 
786
  if (s.excluded_nodes)
787
  h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
788
  ' intersection(s) were unreachable from the main network and left out.</div>';
789
+ h += '<div class="hd" style="margin-top:8px">Turn-by-turn (in drive order)</div>';
 
790
  STEPS.forEach(x => {
791
+ const col = x.deadhead ? DEAD_COLOR : ROUTE_COLOR;
 
792
  h += '<div class="street" data-step="' + x.step + '" style="border-left-color:' + col + '">' +
793
+ '<span>' + x.step + '. ' + (x.deadhead ? '<i style="color:' + DEAD_COLOR + '">(deadhead)</i> ' : '') +
794
  x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
795
  });
796
  document.getElementById('out').innerHTML = h;