3hstack commited on
Commit
5a58093
·
verified ·
1 Parent(s): 4c4118f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -423
app.py CHANGED
@@ -306,81 +306,6 @@ def solve(G, walking=False, start_lat=None, start_lon=None):
306
  }
307
 
308
 
309
- # ---------------------------------------------------------------- how many houses?
310
- # OSM address coverage is patchy even where building coverage is excellent (Michigan
311
- # suburbs are typically 100% buildings, ~40-60% housenumbers). So we report BOTH and
312
- # let the user judge: address points are exact but undercount; dwellings are complete
313
- # but are inferred. Garages/sheds/pools are excluded or they'd inflate the count badly.
314
- OVERPASS_URL = "https://overpass-api.de/api/interpreter"
315
-
316
- NON_DWELLING = (
317
- "garage|garages|shed|carport|roof|greenhouse|hut|barn|stable|silo|"
318
- "service|container|bunker|cabin|tent|conservatory|pergola"
319
- )
320
-
321
-
322
- def _overpass_filter(shape):
323
- """bbox -> (s,w,n,e) filter; polygon -> (poly:"lat lon lat lon ...") filter."""
324
- if shape.get("kind") == "polygon" or "polygon" in shape:
325
- ring = shape["polygon"]["coordinates"][0]
326
- pts = " ".join("%.6f %.6f" % (lat, lng) for lng, lat in ring)
327
- return '(poly:"%s")' % pts
328
- b = shape["bounds"]
329
- return "(%.6f,%.6f,%.6f,%.6f)" % (b["south"], b["west"], b["north"], b["east"])
330
-
331
-
332
- def count_addresses(shape, timeout=90):
333
- """One Overpass request -> address points, dwellings, and all buildings."""
334
- import requests
335
-
336
- f = _overpass_filter(shape)
337
- query = (
338
- "[out:json][timeout:%d];"
339
- '(node["addr:housenumber"]%s;way["addr:housenumber"]%s;)->.addr;'
340
- '(way["building"]%s;relation["building"]%s;)->.bld;'
341
- '(way["building"]["building"!~"^(%s)$"]%s;'
342
- ' relation["building"]["building"!~"^(%s)$"]%s;)->.dwell;'
343
- ".addr out count;.bld out count;.dwell out count;"
344
- % (timeout, f, f, f, f, NON_DWELLING, f, NON_DWELLING, f)
345
- )
346
-
347
- try:
348
- r = requests.post(
349
- OVERPASS_URL,
350
- data={"data": query},
351
- timeout=timeout + 20,
352
- headers={"User-Agent": "route-em/1.0 (personal delivery route tool)"},
353
- )
354
- except Exception as exc:
355
- raise RouteError("Address lookup failed: %s" % exc)
356
-
357
- if r.status_code == 429:
358
- raise RouteError(
359
- "OpenStreetMap's address server is rate-limiting right now. "
360
- "Wait a minute and hit Count again -- the route itself is unaffected."
361
- )
362
- if r.status_code != 200:
363
- raise RouteError("Address lookup failed (HTTP %d)." % r.status_code)
364
-
365
- try:
366
- totals = [int(e["tags"]["total"]) for e in r.json()["elements"]]
367
- except Exception:
368
- raise RouteError("Could not read the address response from OpenStreetMap.")
369
-
370
- if len(totals) < 3:
371
- raise RouteError("Incomplete address response from OpenStreetMap.")
372
-
373
- addr, buildings, dwellings = totals[0], totals[1], totals[2]
374
- return {
375
- "address_points": addr,
376
- "dwellings": dwellings,
377
- "buildings": buildings,
378
- "outbuildings": max(buildings - dwellings, 0),
379
- # how much of the building stock actually carries a house number in OSM
380
- "addr_coverage_pct": (addr / dwellings * 100) if dwellings else 0.0,
381
- }
382
-
383
-
384
  # Keep osmnx's HTTP cache in /tmp -- the only writable path on a Space.
385
  ox.settings.cache_folder = "/tmp/osmnx_cache"
386
  ox.settings.use_cache = True
@@ -414,7 +339,7 @@ PAGE = r'''<!DOCTYPE html>
414
  #drop img{width:100%;height:100%;object-fit:contain}
415
  #drop .ph{padding:24px}
416
  #drop .ph b{color:var(--txt);display:block;margin-bottom:6px;font-size:15px}
417
- #map{flex:1}
418
  .ctl{padding:10px 14px;border-bottom:1px solid var(--line);display:flex;gap:8px;flex-wrap:wrap;align-items:center;flex-shrink:0}
419
  input[type=text]{flex:1;min-width:140px;background:#0b0d11;border:1px solid var(--line);color:var(--txt);padding:9px 11px;border-radius:7px;font-size:13px}
420
  input[type=text]:focus{outline:0;border-color:var(--acc)}
@@ -422,7 +347,6 @@ PAGE = r'''<!DOCTYPE html>
422
  button:hover{filter:brightness(1.12)}
423
  button:disabled{opacity:.4;cursor:not-allowed}
424
  button.sec{background:#252a35}
425
- button.sec.on{background:var(--acc)}
426
  label.ck{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:12px;cursor:pointer;white-space:nowrap}
427
  .msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
428
  .msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
@@ -433,13 +357,11 @@ PAGE = r'''<!DOCTYPE html>
433
  .stat.big b{font-size:24px;color:var(--acc)}
434
  .stat.good b{color:var(--ok)}
435
  .stat.warn b{color:var(--bad)}
436
- .street{padding:6px 14px;display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028}
437
  .street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
438
- .street.now{background:#4f8cff26;color:var(--txt);border-left:3px solid var(--acc)}
439
  .empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
440
  .mapwrap{position:relative;flex:1;display:flex;min-height:0}
441
-
442
- /* ---- playback bar ---- */
443
  #play{position:absolute;left:0;right:0;bottom:0;z-index:900;background:#0f1115f2;border-top:1px solid var(--line);padding:10px 14px;display:none;gap:10px;align-items:center;flex-wrap:wrap}
444
  #play.on{display:flex}
445
  #scrub{flex:1;min-width:160px;-webkit-appearance:none;appearance:none;height:5px;border-radius:3px;background:#2b3342;outline:0;cursor:pointer}
@@ -447,18 +369,22 @@ PAGE = r'''<!DOCTYPE html>
447
  #scrub::-moz-range-thumb{width:15px;height:15px;border-radius:50%;background:var(--acc);border:2px solid #0f1115;cursor:pointer}
448
  #pp{width:42px;padding:9px 0;text-align:center}
449
  select{background:#252a35;color:var(--txt);border:1px solid var(--line);border-radius:7px;padding:8px;font-size:12px;cursor:pointer}
450
- .hud{position:absolute;top:12px;left:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);border-radius:9px;padding:10px 13px;min-width:190px;display:none}
451
  .hud.on{display:block}
452
  .hud .now{font-size:15px;font-weight:650;margin-bottom:3px}
 
453
  .hud .meta{font-size:11px;color:var(--dim);font-variant-numeric:tabular-nums}
454
  .hud .bar{height:4px;background:#2b3342;border-radius:3px;margin-top:7px;overflow:hidden}
455
  .hud .bar i{display:block;height:100%;background:var(--acc);width:0}
456
- .legend{position:absolute;top:12px;right:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);padding:9px 11px;border-radius:8px;font-size:11px;line-height:1.85;display:none}
457
- .sw{display:inline-block;width:16px;height:3px;vertical-align:middle;margin-right:6px;border-radius:2px}
 
 
458
  .spin{width:14px;height:14px;border:2px solid #ffffff44;border-top-color:#fff;border-radius:50%;display:inline-block;animation:s .7s linear infinite;vertical-align:-2px;margin-right:7px}
459
  @keyframes s{to{transform:rotate(360deg)}}
460
- .truck{filter:drop-shadow(0 2px 5px rgba(0,0,0,.65))}
461
- .arrow{color:#fff;opacity:.9;pointer-events:none}
 
462
  </style>
463
  </head>
464
  <body>
@@ -497,21 +423,13 @@ PAGE = r'''<!DOCTYPE html>
497
  </div>
498
  <div class="mapwrap">
499
  <div id="map"></div>
500
-
501
  <div class="hud" id="hud">
 
502
  <div class="now" id="hudStreet">&mdash;</div>
503
  <div class="meta" id="hudMeta">&mdash;</div>
504
  <div class="bar"><i id="hudBar"></i></div>
505
  </div>
506
-
507
- <div class="legend" id="legend">
508
- <span class="sw" style="background:#2860e6"></span>route start<br>
509
- <span class="sw" style="background:#e6c85a"></span>route end<br>
510
- <span class="sw" style="background:#d7263d"></span>deadhead (repeat pass)<br>
511
- <span class="sw" style="background:#2ecc71"></span>already driven<br>
512
- <span style="color:#98a1b3">Arrows show direction of travel.</span>
513
- </div>
514
-
515
  <div id="play">
516
  <button id="pp">&#9654;</button>
517
  <button id="restart" class="sec">&#8634;</button>
@@ -533,9 +451,7 @@ PAGE = r'''<!DOCTYPE html>
533
  <div class="hd">3 &nbsp;Your route</div>
534
  <div id="msg" class="msg"></div>
535
  <div id="out">
536
- <div class="empty">
537
- Drop a screenshot, find the area,<br>outline it, and hit <b>Solve route</b>.
538
- </div>
539
  </div>
540
  </div>
541
  </main>
@@ -562,74 +478,42 @@ function showShot(f){
562
  drop.innerHTML = ''; drop.appendChild(img);
563
  }
564
 
565
- // ================= map =================
566
  const map = L.map('map').setView([39.83, -98.58], 4);
567
-
568
- // ---- basemaps: street vs satellite (Esri imagery is free, no API key)
569
  const streets = L.tileLayer(
570
  'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
571
- {maxZoom: 19, attribution: '&copy; OpenStreetMap, &copy; CARTO'});
572
-
573
  const satellite = L.tileLayer(
574
  'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
575
- {maxZoom: 19, maxNativeZoom: 19, attribution: 'Imagery &copy; Esri, Maxar, Earthstar Geographics'});
576
-
577
- // Street names drawn ON TOP of the imagery -- raw satellite has no labels, and you
578
- // can't follow a paper route without street names. (Stamen's label tiles are dead as
579
- // of 2023, so these are Esri's, which need no API key.)
580
  const ESRI = 'https://server.arcgisonline.com/ArcGIS/rest/services/Reference/';
581
- const roadLabels = L.tileLayer(ESRI + 'World_Transportation/MapServer/tile/{z}/{y}/{x}',
582
- {maxZoom: 19, attribution: ''});
583
- const placeLabels = L.tileLayer(ESRI + 'World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}',
584
- {maxZoom: 19, attribution: ''});
585
  const satHybrid = L.layerGroup([satellite, roadLabels, placeLabels]);
586
-
587
  streets.addTo(map);
588
-
589
- L.control.layers(
590
- {'Street': streets, 'Satellite': satHybrid},
591
- {},
592
- {position: 'topright', collapsed: false}
593
- ).addTo(map);
594
-
595
- // keep the route, arrows and truck above whichever basemap is active
596
- map.createPane('routePane');
597
- map.getPane('routePane').style.zIndex = 450;
598
 
599
  const drawn = new L.FeatureGroup().addTo(map);
600
- let routeLayer = null, trailLine = null, arrowLayer = null,
601
- truck = null, startMarker = null, shape = null;
602
 
603
  const SHAPE_STYLE = {color:'#4f8cff', weight:2, fillOpacity:.06};
604
- const boxTool = new L.Draw.Rectangle(map, {shapeOptions: SHAPE_STYLE});
605
- const polyTool = new L.Draw.Polygon(map, {
606
- shapeOptions: SHAPE_STYLE,
607
- allowIntersection: false,
608
- showArea: false,
609
- drawError: {color:'#d7263d', message:'Edges cannot cross'}
610
- });
611
 
612
- document.getElementById('box').onclick = () => {
613
- polyTool.disable(); drawn.clearLayers(); boxTool.enable();
614
- msg('Drag a rectangle around the neighborhood.', 'info');
615
- };
616
- document.getElementById('poly').onclick = () => {
617
- boxTool.disable(); drawn.clearLayers(); polyTool.enable();
618
- msg('Click each corner of your route area. Click the first point again to close it.', 'info');
619
- };
620
 
621
  map.on(L.Draw.Event.CREATED, e => {
622
- drawn.clearLayers();
623
- drawn.addLayer(e.layer);
624
-
625
  if (e.layerType === 'rectangle') {
626
  const b = e.layer.getBounds();
627
- shape = {kind:'bbox', bounds:{
628
- north:b.getNorth(), south:b.getSouth(), east:b.getEast(), west:b.getWest()}};
629
  } else {
630
- // GeoJSON ring, [lng,lat], explicitly closed
631
- const ring = e.layer.getLatLngs()[0].map(p => [p.lng, p.lat]);
632
- ring.push(ring[0]);
633
  shape = {kind:'polygon', polygon:{type:'Polygon', coordinates:[ring]}};
634
  }
635
  document.getElementById('solve').disabled = false;
@@ -643,16 +527,14 @@ map.on('click', e => {
643
  });
644
 
645
  document.getElementById('clear').onclick = () => {
646
- stop();
647
- drawn.clearLayers();
648
  [routeLayer, trailLine, arrowLayer, truck, startMarker].forEach(l => l && map.removeLayer(l));
649
  routeLayer = trailLine = arrowLayer = truck = startMarker = shape = null;
650
  document.getElementById('solve').disabled = true;
651
  document.getElementById('play').classList.remove('on');
652
  document.getElementById('hud').classList.remove('on');
653
  document.getElementById('legend').style.display = 'none';
654
- document.getElementById('out').innerHTML =
655
- '<div class="empty">Outline an area and hit <b>Solve route</b>.</div>';
656
  msg('');
657
  };
658
 
@@ -660,18 +542,16 @@ document.getElementById('clear').onclick = () => {
660
  const q = document.getElementById('q');
661
  document.getElementById('find').onclick = find;
662
  q.onkeydown = e => { if (e.key === 'Enter') find(); };
663
-
664
  async function find(){
665
- const term = q.value.trim();
666
- if (!term) return;
667
  msg('Looking up "' + term + '"...', 'info');
668
  try {
669
  const r = await fetch('/geocode?q=' + encodeURIComponent(term));
670
  const d = await r.json();
671
  if (!r.ok) return msg(d.error, 'err');
672
- map.fitBounds([[d.bounds.south, d.bounds.west], [d.bounds.north, d.bounds.east]]);
673
  if (map.getZoom() > 16) map.setZoom(16);
674
- msg('Found ' + d.label + '. Now <b>Draw shape</b> (any outline) or <b>Draw box</b>.', 'info');
675
  } catch (err) { msg('Lookup failed: ' + err, 'err'); }
676
  }
677
 
@@ -680,321 +560,224 @@ const solveBtn = document.getElementById('solve');
680
  solveBtn.onclick = async () => {
681
  if (!shape) return;
682
  const orig = solveBtn.innerHTML;
683
- solveBtn.disabled = true;
684
- solveBtn.innerHTML = '<span class="spin"></span>Solving...';
685
  msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
686
-
687
  const body = Object.assign({}, shape, {
688
  walking: document.getElementById('walking').checked,
689
- include_service: document.getElementById('svc').checked
690
- });
691
- if (startMarker) {
692
- body.start_lat = startMarker.getLatLng().lat;
693
- body.start_lon = startMarker.getLatLng().lng;
694
- }
695
-
696
  try {
697
- const r = await fetch('/solve', {
698
- method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)
699
- });
700
  const d = await r.json();
701
  if (!r.ok) { msg(d.error, 'err'); return; }
702
- render(d);
703
- msg('');
704
- } catch (err) {
705
- msg('Solve failed: ' + err, 'err');
706
- } finally {
707
- solveBtn.disabled = false;
708
- solveBtn.innerHTML = orig;
709
- }
710
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
 
712
-
713
- // ================= route rendering =================
714
- let PATH = []; // [{a,b,len(m),cum(m),name,deadhead,order}]
715
- let TOTAL_M = 0; // route length, meters
716
- let DRIVE_MIN = 0; // estimated real-world minutes
717
- let STEPS = []; // collapsed turn-by-turn
 
 
 
 
 
 
 
 
 
 
718
 
719
  function render(d){
720
  stop();
721
  [routeLayer, trailLine, arrowLayer, truck].forEach(l => l && map.removeLayer(l));
 
722
 
723
- const feats = d.geojson.features, n = feats.length;
724
-
725
- // ---- base route, colored by progression
726
- routeLayer = L.geoJSON(d.geojson, {
727
- style: f => {
728
- const p = f.properties;
729
- if (p.deadhead) return {color:'#d7263d', weight:3.5, opacity:.9, dashArray:'6,8'};
730
- const t = (p.order - 1) / Math.max(n - 1, 1);
731
- return {color:'rgb(' + Math.round(40+200*t) + ',' + Math.round(90+100*t) + ',' +
732
- Math.round(230-180*t) + ')', weight:5, opacity:.8};
733
- },
734
- onEachFeature: (f, l) => {
735
- const p = f.properties;
736
- l.bindTooltip('#' + p.order + ' ' + p.name + ' &mdash; ' + p.mi + ' mi' +
737
- (p.deadhead ? ' (deadhead, no delivery)' : ''));
738
- }
739
- }).addTo(map);
740
-
741
- // ---- drivable path with cumulative distances
742
  PATH = []; TOTAL_M = 0;
743
  feats.forEach(f => {
744
  const c = f.geometry.coordinates;
745
  const a = L.latLng(c[0][1], c[0][0]), b = L.latLng(c[1][1], c[1][0]);
746
  const len = map.distance(a, b);
747
- PATH.push({a, b, len, cum: TOTAL_M, name: f.properties.name,
 
748
  deadhead: f.properties.deadhead, order: f.properties.order});
749
  TOTAL_M += len;
750
  });
751
 
752
- DRIVE_MIN = d.stats.drive_min;
753
- STEPS = d.directions;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754
 
755
  buildArrows();
 
 
756
 
757
- trailLine = L.polyline([], {color:'#2ecc71', weight:7, opacity:.95}).addTo(map);
758
- truck = L.marker(PATH[0].a, {icon: truckIcon(0), zIndexOffset: 1000,
759
- interactive: false}).addTo(map);
760
-
761
- map.fitBounds(routeLayer.getBounds(), {padding:[24,24]});
762
- document.getElementById('legend').style.display = 'block';
763
  document.getElementById('play').classList.add('on');
764
  document.getElementById('hud').classList.add('on');
765
-
766
  renderStats(d.stats);
767
  seek(0);
768
- countHouses();
769
- }
770
-
771
- // ================= how many houses? =================
772
- // Separate request from /solve: Overpass rate-limits, and a 429 here must not
773
- // throw away a route you already waited for.
774
- let COUNTS = null;
775
-
776
- async function countHouses(){
777
- if (!shape) return;
778
- COUNTS = 'loading';
779
- renderHouses();
780
- try {
781
- const r = await fetch('/count', {
782
- method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(shape)
783
- });
784
- const d = await r.json();
785
- COUNTS = r.ok ? d : {error: d.error};
786
- } catch (err) {
787
- COUNTS = {error: 'Count failed: ' + err};
788
- }
789
- renderHouses();
790
- }
791
-
792
- function renderHouses(){
793
- const el = document.getElementById('houses');
794
- if (!el) return;
795
-
796
- if (COUNTS === 'loading') {
797
- el.innerHTML = '<div class="street"><span><span class="spin"></span>' +
798
- 'Counting houses...</span></div>';
799
- return;
800
- }
801
- if (!COUNTS) { el.innerHTML = ''; return; }
802
- if (COUNTS.error) {
803
- el.innerHTML = '<div class="msg err" style="display:block;margin:10px 14px">' +
804
- COUNTS.error + ' <a href="#" id="recount" style="color:#ffb3bd">' +
805
- 'Try again</a></div>';
806
- const a = document.getElementById('recount');
807
- if (a) a.onclick = e => { e.preventDefault(); countHouses(); };
808
- return;
809
- }
810
-
811
- const c = COUNTS;
812
- const perMi = TOTAL_M ? c.dwellings / (TOTAL_M / 1609.344) : 0;
813
- const row = (l, v, cls) =>
814
- '<div class="stat ' + (cls||'') + '"><span>' + l + '</span><b>' + v + '</b></div>';
815
-
816
- let h = '';
817
- h += row('Houses / buildings', c.dwellings.toLocaleString(), 'big');
818
- h += row('With a street number', c.address_points.toLocaleString(), 'good');
819
- h += row('Sheds, garages (skipped)', c.outbuildings.toLocaleString());
820
- h += row('Papers per mile driven', perMi.toFixed(0));
821
- h += '<div style="padding:9px 14px;font-size:11px;color:var(--dim);line-height:1.55;' +
822
- 'border-bottom:1px solid var(--line)">' +
823
- 'OpenStreetMap has <b>' + c.dwellings.toLocaleString() + '</b> buildings here but a ' +
824
- 'street number on only <b>' + c.addr_coverage_pct.toFixed(0) + '%</b> of them. ' +
825
- 'The building count is the better estimate of doors; treat it as <b>close, ' +
826
- 'not exact</b> &mdash; it can include duplexes as one and misses new construction.' +
827
- '</div>';
828
- el.innerHTML = h;
829
  }
830
 
831
- // ---- direction arrows, rotated to the way you drive
832
  function buildArrows(){
833
  if (arrowLayer) map.removeLayer(arrowLayer);
834
  arrowLayer = L.layerGroup();
835
-
836
- const stride = Math.max(1, Math.ceil(PATH.length / 400)); // cap the marker count
837
  PATH.forEach((s, i) => {
838
  if (i % stride) return;
839
- if (s.len < 12) return; // skip tiny stubs
840
- const mid = L.latLng((s.a.lat + s.b.lat)/2, (s.a.lng + s.b.lng)/2);
841
- L.marker(mid, {
842
- interactive: false,
843
- icon: L.divIcon({
844
- className: '',
845
- iconSize: [14, 14],
846
- iconAnchor: [7, 7],
847
- html: '<div class="arrow" style="transform:rotate(' + bearing(s.a, s.b) + 'deg)">' +
848
- '<svg width="14" height="14" viewBox="0 0 14 14">' +
849
- '<path d="M7 1 L11 11 L7 8.6 L3 11 Z" fill="' +
850
- (s.deadhead ? '#ff8a97' : '#ffffff') + '" stroke="#0f1115" stroke-width="1"/>' +
851
- '</svg></div>'
852
- })
853
- }).addTo(arrowLayer);
854
  });
855
  if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
856
  }
857
-
858
  document.getElementById('arrowsOn').onchange = e => {
859
  if (!arrowLayer) return;
860
  e.target.checked ? arrowLayer.addTo(map) : map.removeLayer(arrowLayer);
861
  };
862
 
863
- // compass bearing, 0 = north
864
- function bearing(a, b){
865
- const r = Math.PI/180;
866
- const y = Math.sin((b.lng-a.lng)*r) * Math.cos(b.lat*r);
867
- const x = Math.cos(a.lat*r)*Math.sin(b.lat*r) -
868
- Math.sin(a.lat*r)*Math.cos(b.lat*r)*Math.cos((b.lng-a.lng)*r);
869
- return (Math.atan2(y, x) * 180/Math.PI + 360) % 360;
 
 
 
 
 
 
870
  }
871
 
872
  function truckIcon(deg){
873
- return L.divIcon({
874
- className: '',
875
- iconSize: [30, 30],
876
- iconAnchor: [15, 15],
877
- html: '<div class="truck" style="transform:rotate(' + deg + 'deg)">' +
878
- '<svg width="30" height="30" viewBox="0 0 30 30">' +
879
- '<circle cx="15" cy="15" r="13" fill="#0f1115" opacity=".55"/>' +
880
- '<g transform="translate(15,15)">' +
881
- '<rect x="-6" y="-8" width="12" height="16" rx="2.5" fill="#4f8cff"/>' +
882
- '<rect x="-6" y="-8" width="12" height="5.5" rx="2" fill="#dfe8ff"/>' +
883
- '<rect x="-7.5" y="-2" width="3" height="6" rx="1" fill="#2b3342"/>' +
884
- '<rect x="4.5" y="-2" width="3" height="6" rx="1" fill="#2b3342"/>' +
885
- '<path d="M0 -12 L4 -8 L-4 -8 Z" fill="#e6c85a"/>' +
886
- '</g>' +
887
- '</svg></div>'
888
- });
889
  }
890
-
891
  // ================= animation =================
892
- let pos = 0; // meters travelled
893
- let playing = false;
894
- let raf = null, last = 0;
895
-
896
- const pp = document.getElementById('pp');
897
- const scrub = document.getElementById('scrub');
898
- const speedSel = document.getElementById('speed');
899
- const followCk = document.getElementById('follow');
900
-
901
  pp.onclick = () => playing ? stop() : play();
902
  document.getElementById('restart').onclick = () => { seek(0); play(); };
903
- scrub.oninput = () => { stop(); seek(TOTAL_M * (scrub.value / 1000)); };
904
 
905
  function play(){
906
  if (!PATH.length) return;
907
  if (pos >= TOTAL_M - 0.5) pos = 0;
908
- playing = true;
909
- pp.innerHTML = '&#10073;&#10073;';
910
- last = performance.now();
911
- raf = requestAnimationFrame(tick);
912
- }
913
-
914
- function stop(){
915
- playing = false;
916
- pp.innerHTML = '&#9654;';
917
- if (raf) cancelAnimationFrame(raf);
918
- raf = null;
919
  }
920
-
921
  function tick(now){
922
  if (!playing) return;
923
- const dt = Math.min((now - last) / 1000, 0.1); // tab-switch shouldn't teleport the truck
924
- last = now;
925
-
926
- // 1x = whole route in 90s of wall clock
927
  pos += (TOTAL_M / 90) * parseFloat(speedSel.value) * dt;
928
-
929
  if (pos >= TOTAL_M) { seek(TOTAL_M); stop(); return; }
930
- seek(pos);
931
- raf = requestAnimationFrame(tick);
932
  }
933
 
934
- // put the truck / trail / HUD at `m` meters along the route
935
  function seek(m){
936
  if (!PATH.length) return;
937
  pos = Math.max(0, Math.min(m, TOTAL_M));
938
-
939
- // binary search for the segment containing pos
940
- let lo = 0, hi = PATH.length - 1, i = 0;
941
- while (lo <= hi) {
942
- const mid = (lo + hi) >> 1, s = PATH[mid];
943
- if (pos < s.cum) hi = mid - 1;
944
- else if (pos > s.cum + s.len) lo = mid + 1;
945
- else { i = mid; break; }
946
- i = Math.min(lo, PATH.length - 1);
947
- }
948
-
949
  const s = PATH[i];
950
- const f = s.len ? Math.max(0, Math.min((pos - s.cum) / s.len, 1)) : 0;
951
- const here = L.latLng(s.a.lat + (s.b.lat - s.a.lat) * f,
952
- s.a.lng + (s.b.lng - s.a.lng) * f);
953
-
954
- truck.setLatLng(here);
955
- truck.setIcon(truckIcon(bearing(s.a, s.b)));
956
-
957
- const tr = [];
958
- for (let k = 0; k < i; k++) tr.push(PATH[k].a);
959
- tr.push(s.a, here);
960
  trailLine.setLatLngs(tr);
961
-
962
  if (followCk.checked && playing && !map.getBounds().pad(-0.18).contains(here))
963
  map.panTo(here, {animate:true, duration:.4});
964
-
965
- scrub.value = Math.round((pos / TOTAL_M) * 1000);
966
  updateHud(s);
967
  }
968
 
969
  function updateHud(s){
970
- const pct = pos / TOTAL_M;
 
 
 
971
  document.getElementById('hudStreet').innerHTML =
972
- (s.deadhead ? '<span style="color:#d7263d">&#8631; </span>' : '') + s.name;
973
  document.getElementById('hudMeta').textContent =
974
- (pos/1609.344).toFixed(2) + ' / ' + (TOTAL_M/1609.344).toFixed(2) + ' mi · step ' +
975
- s.order + ' of ' + PATH.length + ' · ~' + Math.round(DRIVE_MIN * pct) + ' min in';
976
- document.getElementById('hudBar').style.width = (pct * 100) + '%';
977
-
978
- // highlight the matching turn-by-turn row
979
- let acc = 0, idx = 0;
980
- for (let k = 0; k < STEPS.length; k++) {
981
- acc += STEPS[k].mi * 1609.344;
982
- idx = k;
983
- if (pos <= acc) break;
984
- }
985
  document.querySelectorAll('#out .street.now').forEach(r => r.classList.remove('now'));
986
- const row = document.querySelector('#out .street[data-step="' + (idx + 1) + '"]');
987
- if (row) {
988
- row.classList.add('now');
989
- if (playing) row.scrollIntoView({block:'nearest'});
990
- }
991
  }
992
 
993
  // ================= stats panel =================
994
  function renderStats(s){
995
- const row = (l, v, c) =>
996
- '<div class="stat ' + (c||'') + '"><span>' + l + '</span><b>' + v + '</b></div>';
997
-
998
  let h = '';
999
  h += row('Total route', s.total_mi.toFixed(2) + ' mi', 'big');
1000
  h += row('Delivering', s.min_mi.toFixed(2) + ' mi', 'good');
@@ -1008,30 +791,21 @@ function renderStats(s){
1008
  if (s.excluded_nodes)
1009
  h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
1010
  ' intersection(s) were unreachable from the main network and left out.</div>';
1011
-
1012
- h += '<div class="hd" style="margin-top:8px">Houses in this area</div>';
1013
- h += '<div id="houses"></div>';
1014
-
1015
- h += '<div class="hd" style="margin-top:8px">Longest streets</div>';
1016
- s.longest.forEach(x => {
1017
- h += '<div class="street"><span>' + x.name + '</span><b>' + x.mi.toFixed(2) + ' mi</b></div>';
1018
- });
1019
-
1020
- h += '<div class="hd" style="margin-top:8px">Directions</div>';
1021
  STEPS.forEach(x => {
1022
- h += '<div class="street" data-step="' + x.step + '"><span>' + x.step + '. ' +
1023
- (x.deadhead ? '<i style="color:#d7263d">(deadhead)</i> ' : '') +
 
 
1024
  x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
1025
  });
1026
-
1027
  document.getElementById('out').innerHTML = h;
1028
- renderHouses();
1029
  }
1030
 
1031
  function msg(t, cls){
1032
  const m = document.getElementById('msg');
1033
- m.innerHTML = t || '';
1034
- m.className = 'msg' + (t ? ' ' + cls : '');
1035
  }
1036
  </script>
1037
  </body>
@@ -1109,20 +883,6 @@ def solve_route():
1109
  return jsonify({"error": "Unexpected error: %s" % exc}), 500
1110
 
1111
 
1112
- @app.route("/count", methods=["POST"])
1113
- def count_route():
1114
- """Separate from /solve on purpose: Overpass rate-limits, and a 429 here
1115
- must not throw away a route the user already waited for."""
1116
- d = request.get_json(force=True)
1117
- try:
1118
- return jsonify(count_addresses(d))
1119
- except RouteError as exc:
1120
- return jsonify({"error": str(exc)}), 400
1121
- except Exception as exc:
1122
- traceback.print_exc()
1123
- return jsonify({"error": "Unexpected error: %s" % exc}), 500
1124
-
1125
-
1126
  def _check_area(area):
1127
  if area > MAX_AREA_SQ_MI:
1128
  raise RouteError(
 
306
  }
307
 
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  # Keep osmnx's HTTP cache in /tmp -- the only writable path on a Space.
310
  ox.settings.cache_folder = "/tmp/osmnx_cache"
311
  ox.settings.use_cache = True
 
339
  #drop img{width:100%;height:100%;object-fit:contain}
340
  #drop .ph{padding:24px}
341
  #drop .ph b{color:var(--txt);display:block;margin-bottom:6px;font-size:15px}
342
+ #map{flex:1;background:#0b0d11}
343
  .ctl{padding:10px 14px;border-bottom:1px solid var(--line);display:flex;gap:8px;flex-wrap:wrap;align-items:center;flex-shrink:0}
344
  input[type=text]{flex:1;min-width:140px;background:#0b0d11;border:1px solid var(--line);color:var(--txt);padding:9px 11px;border-radius:7px;font-size:13px}
345
  input[type=text]:focus{outline:0;border-color:var(--acc)}
 
347
  button:hover{filter:brightness(1.12)}
348
  button:disabled{opacity:.4;cursor:not-allowed}
349
  button.sec{background:#252a35}
 
350
  label.ck{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:12px;cursor:pointer;white-space:nowrap}
351
  .msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
352
  .msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
 
357
  .stat.big b{font-size:24px;color:var(--acc)}
358
  .stat.good b{color:var(--ok)}
359
  .stat.warn b{color:var(--bad)}
360
+ .street{padding:6px 14px;display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028;border-left:3px solid transparent}
361
  .street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
362
+ .street.now{background:#ffffff14;color:var(--txt)}
363
  .empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
364
  .mapwrap{position:relative;flex:1;display:flex;min-height:0}
 
 
365
  #play{position:absolute;left:0;right:0;bottom:0;z-index:900;background:#0f1115f2;border-top:1px solid var(--line);padding:10px 14px;display:none;gap:10px;align-items:center;flex-wrap:wrap}
366
  #play.on{display:flex}
367
  #scrub{flex:1;min-width:160px;-webkit-appearance:none;appearance:none;height:5px;border-radius:3px;background:#2b3342;outline:0;cursor:pointer}
 
369
  #scrub::-moz-range-thumb{width:15px;height:15px;border-radius:50%;background:var(--acc);border:2px solid #0f1115;cursor:pointer}
370
  #pp{width:42px;padding:9px 0;text-align:center}
371
  select{background:#252a35;color:var(--txt);border:1px solid var(--line);border-radius:7px;padding:8px;font-size:12px;cursor:pointer}
372
+ .hud{position:absolute;top:12px;left:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);border-radius:9px;padding:10px 13px;min-width:200px;display:none}
373
  .hud.on{display:block}
374
  .hud .now{font-size:15px;font-weight:650;margin-bottom:3px}
375
+ .hud .leg{display:inline-block;font-size:10px;font-weight:700;padding:1px 7px;border-radius:9px;color:#05070c;margin-bottom:5px}
376
  .hud .meta{font-size:11px;color:var(--dim);font-variant-numeric:tabular-nums}
377
  .hud .bar{height:4px;background:#2b3342;border-radius:3px;margin-top:7px;overflow:hidden}
378
  .hud .bar i{display:block;height:100%;background:var(--acc);width:0}
379
+ .legend{position:absolute;top:12px;right:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);padding:10px 12px;border-radius:9px;font-size:11px;line-height:1.7;display:none;max-width:190px}
380
+ .legend .ttl{font-weight:700;color:var(--txt);margin-bottom:5px;font-size:11px;text-transform:uppercase;letter-spacing:.6px}
381
+ .legend .lg{display:flex;align-items:center;gap:7px;color:var(--dim)}
382
+ .sw{display:inline-block;width:16px;height:4px;border-radius:2px;flex-shrink:0}
383
  .spin{width:14px;height:14px;border:2px solid #ffffff44;border-top-color:#fff;border-radius:50%;display:inline-block;animation:s .7s linear infinite;vertical-align:-2px;margin-right:7px}
384
  @keyframes s{to{transform:rotate(360deg)}}
385
+ .truck{filter:drop-shadow(0 2px 5px rgba(0,0,0,.7))}
386
+ .arrow{pointer-events:none}
387
+ .dimbase{filter:brightness(.62) saturate(.7)}
388
  </style>
389
  </head>
390
  <body>
 
423
  </div>
424
  <div class="mapwrap">
425
  <div id="map"></div>
 
426
  <div class="hud" id="hud">
427
+ <div class="leg" id="hudLeg">Leg 1</div>
428
  <div class="now" id="hudStreet">&mdash;</div>
429
  <div class="meta" id="hudMeta">&mdash;</div>
430
  <div class="bar"><i id="hudBar"></i></div>
431
  </div>
432
+ <div class="legend" id="legend"></div>
 
 
 
 
 
 
 
 
433
  <div id="play">
434
  <button id="pp">&#9654;</button>
435
  <button id="restart" class="sec">&#8634;</button>
 
451
  <div class="hd">3 &nbsp;Your route</div>
452
  <div id="msg" class="msg"></div>
453
  <div id="out">
454
+ <div class="empty">Drop a screenshot, find the area,<br>outline it, and hit <b>Solve route</b>.</div>
 
 
455
  </div>
456
  </div>
457
  </main>
 
478
  drop.innerHTML = ''; drop.appendChild(img);
479
  }
480
 
481
+ // ================= map + basemaps =================
482
  const map = L.map('map').setView([39.83, -98.58], 4);
 
 
483
  const streets = L.tileLayer(
484
  'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
485
+ {maxZoom:19, attribution:'&copy; OpenStreetMap, &copy; CARTO', className:'dimbase'});
 
486
  const satellite = L.tileLayer(
487
  'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
488
+ {maxZoom:19, maxNativeZoom:19, attribution:'Imagery &copy; Esri'});
 
 
 
 
489
  const ESRI = 'https://server.arcgisonline.com/ArcGIS/rest/services/Reference/';
490
+ const roadLabels = L.tileLayer(ESRI + 'World_Transportation/MapServer/tile/{z}/{y}/{x}', {maxZoom:19});
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);
498
+ let routeLayer=null, trailLine=null, arrowLayer=null, truck=null, startMarker=null, shape=null;
 
499
 
500
  const SHAPE_STYLE = {color:'#4f8cff', weight:2, fillOpacity:.06};
501
+ const boxTool = new L.Draw.Rectangle(map, {shapeOptions:SHAPE_STYLE});
502
+ const polyTool = new L.Draw.Polygon(map, {shapeOptions:SHAPE_STYLE, allowIntersection:false,
503
+ showArea:false, drawError:{color:'#d7263d', message:'Edges cannot cross'}});
 
 
 
 
504
 
505
+ document.getElementById('box').onclick = () => { polyTool.disable(); drawn.clearLayers(); boxTool.enable();
506
+ msg('Drag a rectangle around the neighborhood.', 'info'); };
507
+ document.getElementById('poly').onclick = () => { boxTool.disable(); drawn.clearLayers(); polyTool.enable();
508
+ msg('Click each corner of your area. Click the first point again to close it.', 'info'); };
 
 
 
 
509
 
510
  map.on(L.Draw.Event.CREATED, e => {
511
+ drawn.clearLayers(); drawn.addLayer(e.layer);
 
 
512
  if (e.layerType === 'rectangle') {
513
  const b = e.layer.getBounds();
514
+ shape = {kind:'bbox', bounds:{north:b.getNorth(), south:b.getSouth(), east:b.getEast(), west:b.getWest()}};
 
515
  } else {
516
+ const ring = e.layer.getLatLngs()[0].map(p => [p.lng, p.lat]); ring.push(ring[0]);
 
 
517
  shape = {kind:'polygon', polygon:{type:'Polygon', coordinates:[ring]}};
518
  }
519
  document.getElementById('solve').disabled = false;
 
527
  });
528
 
529
  document.getElementById('clear').onclick = () => {
530
+ stop(); drawn.clearLayers();
 
531
  [routeLayer, trailLine, arrowLayer, truck, startMarker].forEach(l => l && map.removeLayer(l));
532
  routeLayer = trailLine = arrowLayer = truck = startMarker = shape = null;
533
  document.getElementById('solve').disabled = true;
534
  document.getElementById('play').classList.remove('on');
535
  document.getElementById('hud').classList.remove('on');
536
  document.getElementById('legend').style.display = 'none';
537
+ document.getElementById('out').innerHTML = '<div class="empty">Outline an area and hit <b>Solve route</b>.</div>';
 
538
  msg('');
539
  };
540
 
 
542
  const q = document.getElementById('q');
543
  document.getElementById('find').onclick = find;
544
  q.onkeydown = e => { if (e.key === 'Enter') find(); };
 
545
  async function find(){
546
+ const term = q.value.trim(); if (!term) return;
 
547
  msg('Looking up "' + term + '"...', 'info');
548
  try {
549
  const r = await fetch('/geocode?q=' + encodeURIComponent(term));
550
  const d = await r.json();
551
  if (!r.ok) return msg(d.error, 'err');
552
+ map.fitBounds([[d.bounds.south, d.bounds.west],[d.bounds.north, d.bounds.east]]);
553
  if (map.getZoom() > 16) map.setZoom(16);
554
+ msg('Found ' + d.label + '. Now <b>Draw shape</b> or <b>Draw box</b>.', 'info');
555
  } catch (err) { msg('Lookup failed: ' + err, 'err'); }
556
  }
557
 
 
560
  solveBtn.onclick = async () => {
561
  if (!shape) return;
562
  const orig = solveBtn.innerHTML;
563
+ solveBtn.disabled = true; solveBtn.innerHTML = '<span class="spin"></span>Solving...';
 
564
  msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
 
565
  const body = Object.assign({}, shape, {
566
  walking: document.getElementById('walking').checked,
567
+ include_service: document.getElementById('svc').checked });
568
+ if (startMarker) { body.start_lat = startMarker.getLatLng().lat; body.start_lon = startMarker.getLatLng().lng; }
 
 
 
 
 
569
  try {
570
+ const r = await fetch('/solve', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
 
 
571
  const d = await r.json();
572
  if (!r.ok) { msg(d.error, 'err'); return; }
573
+ render(d); msg('');
574
+ } catch (err) { msg('Solve failed: ' + err, 'err'); }
575
+ finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
 
 
 
 
 
576
  };
577
+ // ================= route data + PHASES =================
578
+ let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
579
+ let PHASES=[]; // [{color, name, startM, endM}]
580
+ const NPHASE_M = 402; // ~0.25 mi per phase target
581
+
582
+ // distinct, high-contrast leg colors (cycled if a route has many legs)
583
+ const PHASE_COLORS = ['#3b82f6','#06b6d4','#22c55e','#eab308','#f97316','#ef4444',
584
+ '#a855f7','#ec4899','#14b8a6','#84cc16'];
585
+
586
+ function phaseCount(totalM){ return Math.max(3, Math.min(10, Math.round(totalM / NPHASE_M))); }
587
+ function phaseOf(m){ // which leg does distance m fall in
588
+ const n = PHASES.length;
589
+ let i = Math.floor(m / TOTAL_M * n);
590
+ return Math.max(0, Math.min(i, n - 1));
591
+ }
592
 
593
+ // shift a segment ~6 m to the RIGHT of travel so both curbs of a two-way street show
594
+ const CURB_OFFSET_M = 6;
595
+ function offsetRight(a, b, meters){
596
+ const latR = (a.lat + b.lat) / 2 * Math.PI / 180;
597
+ const dxE = (b.lng - a.lng) * Math.cos(latR), dyN = (b.lat - a.lat);
598
+ const mag = Math.hypot(dxE, dyN) || 1e-9;
599
+ const pe = dyN / mag, pn = -dxE / mag;
600
+ const dLat = pn * meters / 111320, dLng = pe * meters / (111320 * Math.cos(latR));
601
+ return [L.latLng(a.lat + dLat, a.lng + dLng), L.latLng(b.lat + dLat, b.lng + dLng)];
602
+ }
603
+ function bearing(a, b){
604
+ const r = Math.PI/180;
605
+ const y = Math.sin((b.lng-a.lng)*r) * Math.cos(b.lat*r);
606
+ const x = Math.cos(a.lat*r)*Math.sin(b.lat*r) - Math.sin(a.lat*r)*Math.cos(b.lat*r)*Math.cos((b.lng-a.lng)*r);
607
+ return (Math.atan2(y, x) * 180/Math.PI + 360) % 360;
608
+ }
609
 
610
  function render(d){
611
  stop();
612
  [routeLayer, trailLine, arrowLayer, truck].forEach(l => l && map.removeLayer(l));
613
+ const feats = d.geojson.features;
614
 
615
+ // build centre-line path + offset draw coords + cumulative distance
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  PATH = []; TOTAL_M = 0;
617
  feats.forEach(f => {
618
  const c = f.geometry.coordinates;
619
  const a = L.latLng(c[0][1], c[0][0]), b = L.latLng(c[1][1], c[1][0]);
620
  const len = map.distance(a, b);
621
+ const [oa, ob] = offsetRight(a, b, CURB_OFFSET_M);
622
+ PATH.push({a, b, oa, ob, len, cum: TOTAL_M, name: f.properties.name,
623
  deadhead: f.properties.deadhead, order: f.properties.order});
624
  TOTAL_M += len;
625
  });
626
 
627
+ // define phases (equal-distance legs)
628
+ const np = phaseCount(TOTAL_M);
629
+ PHASES = [];
630
+ for (let k = 0; k < np; k++)
631
+ PHASES.push({color: PHASE_COLORS[k % PHASE_COLORS.length],
632
+ name: 'Leg ' + (k+1),
633
+ startM: TOTAL_M * k / np, endM: TOTAL_M * (k+1) / np});
634
+
635
+ DRIVE_MIN = d.stats.drive_min; STEPS = d.directions;
636
+
637
+ // draw route: dark casing under a phase-colored line, each pass offset
638
+ routeLayer = L.layerGroup([], {pane:'routePane'});
639
+ PATH.forEach(s => {
640
+ const line = [s.oa, s.ob];
641
+ const mid = s.cum + s.len/2;
642
+ const col = s.deadhead ? '#ff3355' : PHASES[phaseOf(mid)].color;
643
+ L.polyline(line, {pane:'routePane', color:'#05070c', weight: s.deadhead ? 6 : 8.5,
644
+ opacity:.6, lineCap:'round'}).addTo(routeLayer);
645
+ L.polyline(line, {pane:'routePane', color:col, weight: s.deadhead ? 4 : 5.5,
646
+ opacity:.98, lineCap:'round',
647
+ dashArray: s.deadhead ? '3,7' : null}).addTo(routeLayer)
648
+ .bindTooltip('#' + s.order + ' ' + s.name + ' — ' + (s.len/1609.344).toFixed(2) + ' mi' +
649
+ (s.deadhead ? ' (deadhead, no delivery)' : ''));
650
+ });
651
+ routeLayer.addTo(map);
652
 
653
  buildArrows();
654
+ trailLine = L.polyline([], {pane:'routePane', color:'#ffffff', weight:9, opacity:.85, lineCap:'round'}).addTo(map);
655
+ truck = L.marker(PATH[0].a, {icon: truckIcon(0), zIndexOffset:1000, interactive:false}).addTo(map);
656
 
657
+ const bb = L.latLngBounds([]); PATH.forEach(s => { bb.extend(s.oa); bb.extend(s.ob); });
658
+ map.fitBounds(bb, {padding:[28,28]});
659
+ buildLegend();
 
 
 
660
  document.getElementById('play').classList.add('on');
661
  document.getElementById('hud').classList.add('on');
 
662
  renderStats(d.stats);
663
  seek(0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664
  }
665
 
666
+ // arrows: normal size, colored to match their phase, pointing the drive direction
667
  function buildArrows(){
668
  if (arrowLayer) map.removeLayer(arrowLayer);
669
  arrowLayer = L.layerGroup();
670
+ const stride = Math.max(1, Math.ceil(PATH.length / 350));
 
671
  PATH.forEach((s, i) => {
672
  if (i % stride) return;
673
+ if (s.len < 14) return;
674
+ const mid = L.latLng((s.oa.lat+s.ob.lat)/2, (s.oa.lng+s.ob.lng)/2);
675
+ const col = s.deadhead ? '#ff8a97' : PHASES[phaseOf(s.cum + s.len/2)].color;
676
+ L.marker(mid, {interactive:false, icon: L.divIcon({className:'', iconSize:[16,16], iconAnchor:[8,8],
677
+ html:'<div class="arrow" style="transform:rotate(' + bearing(s.a, s.b) + 'deg)">' +
678
+ '<svg width="16" height="16" viewBox="0 0 16 16">' +
679
+ '<path d="M8 1 L12.5 12 L8 9.4 L3.5 12 Z" fill="' + col + '" stroke="#05070c" stroke-width="1.1"/>' +
680
+ '</svg></div>'})}).addTo(arrowLayer);
 
 
 
 
 
 
 
681
  });
682
  if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
683
  }
 
684
  document.getElementById('arrowsOn').onchange = e => {
685
  if (!arrowLayer) return;
686
  e.target.checked ? arrowLayer.addTo(map) : map.removeLayer(arrowLayer);
687
  };
688
 
689
+ function buildLegend(){
690
+ const el = document.getElementById('legend');
691
+ let h = '<div class="ttl">Route legs (in order)</div>';
692
+ PHASES.forEach(p => {
693
+ h += '<div class="lg"><span class="sw" style="background:' + p.color + '"></span>' +
694
+ p.name + ' &middot; ' + (p.startM/1609.344).toFixed(1) + '–' +
695
+ (p.endM/1609.344).toFixed(1) + ' mi</div>';
696
+ });
697
+ h += '<div class="lg" style="margin-top:5px"><span class="sw" style="background:#ff3355"></span>' +
698
+ 'deadhead (repeat)</div>';
699
+ h += '<div class="lg"><span class="sw" style="background:#ffffff"></span>already driven</div>';
700
+ el.innerHTML = h;
701
+ el.style.display = 'block';
702
  }
703
 
704
  function truckIcon(deg){
705
+ return L.divIcon({className:'', iconSize:[32,32], iconAnchor:[16,16],
706
+ html:'<div class="truck" style="transform:rotate(' + deg + 'deg)">' +
707
+ '<svg width="32" height="32" viewBox="0 0 32 32">' +
708
+ '<circle cx="16" cy="16" r="14" fill="#05070c" opacity=".6"/>' +
709
+ '<g transform="translate(16,16)">' +
710
+ '<rect x="-6.5" y="-8.5" width="13" height="17" rx="2.5" fill="#ffffff"/>' +
711
+ '<rect x="-6.5" y="-8.5" width="13" height="6" rx="2" fill="#3b82f6"/>' +
712
+ '<rect x="-8" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
713
+ '<rect x="5" y="-2" width="3" height="6" rx="1" fill="#1b2130"/>' +
714
+ '<path d="M0 -13 L4.5 -8.5 L-4.5 -8.5 Z" fill="#eab308"/>' +
715
+ '</g></svg></div>'});
 
 
 
 
 
716
  }
 
717
  // ================= animation =================
718
+ let pos=0, playing=false, raf=null, last=0;
719
+ const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
720
+ speedSel=document.getElementById('speed'), followCk=document.getElementById('follow');
 
 
 
 
 
 
721
  pp.onclick = () => playing ? stop() : play();
722
  document.getElementById('restart').onclick = () => { seek(0); play(); };
723
+ scrub.oninput = () => { stop(); seek(TOTAL_M * (scrub.value/1000)); };
724
 
725
  function play(){
726
  if (!PATH.length) return;
727
  if (pos >= TOTAL_M - 0.5) pos = 0;
728
+ playing = true; pp.innerHTML = '&#10073;&#10073;';
729
+ last = performance.now(); raf = requestAnimationFrame(tick);
 
 
 
 
 
 
 
 
 
730
  }
731
+ function stop(){ playing = false; pp.innerHTML = '&#9654;'; if (raf) cancelAnimationFrame(raf); raf = null; }
732
  function tick(now){
733
  if (!playing) return;
734
+ const dt = Math.min((now - last)/1000, 0.1); last = now;
 
 
 
735
  pos += (TOTAL_M / 90) * parseFloat(speedSel.value) * dt;
 
736
  if (pos >= TOTAL_M) { seek(TOTAL_M); stop(); return; }
737
+ seek(pos); raf = requestAnimationFrame(tick);
 
738
  }
739
 
 
740
  function seek(m){
741
  if (!PATH.length) return;
742
  pos = Math.max(0, Math.min(m, TOTAL_M));
743
+ let lo=0, hi=PATH.length-1, i=0;
744
+ while (lo <= hi){ const mid=(lo+hi)>>1, s=PATH[mid];
745
+ if (pos < s.cum) hi = mid-1; else if (pos > s.cum+s.len) lo = mid+1; else { i=mid; break; }
746
+ i = Math.min(lo, PATH.length-1); }
 
 
 
 
 
 
 
747
  const s = PATH[i];
748
+ const f = s.len ? Math.max(0, Math.min((pos-s.cum)/s.len, 1)) : 0;
749
+ const here = L.latLng(s.a.lat+(s.b.lat-s.a.lat)*f, s.a.lng+(s.b.lng-s.a.lng)*f);
750
+ truck.setLatLng(here); truck.setIcon(truckIcon(bearing(s.a, s.b)));
751
+ const tr = []; for (let k=0;k<i;k++) tr.push(PATH[k].a); tr.push(s.a, here);
 
 
 
 
 
 
752
  trailLine.setLatLngs(tr);
 
753
  if (followCk.checked && playing && !map.getBounds().pad(-0.18).contains(here))
754
  map.panTo(here, {animate:true, duration:.4});
755
+ scrub.value = Math.round((pos/TOTAL_M)*1000);
 
756
  updateHud(s);
757
  }
758
 
759
  function updateHud(s){
760
+ const pct = pos/TOTAL_M, ph = PHASES[phaseOf(pos)];
761
+ const leg = document.getElementById('hudLeg');
762
+ leg.textContent = ph.name + ' of ' + PHASES.length;
763
+ leg.style.background = ph.color;
764
  document.getElementById('hudStreet').innerHTML =
765
+ (s.deadhead ? '<span style="color:#ff3355">&#8631; </span>' : '') + s.name;
766
  document.getElementById('hudMeta').textContent =
767
+ (pos/1609.344).toFixed(2) + ' / ' + (TOTAL_M/1609.344).toFixed(2) + ' mi · ~' +
768
+ Math.round(DRIVE_MIN*pct) + ' min in';
769
+ document.getElementById('hudBar').style.width = (pct*100) + '%';
770
+ document.getElementById('hudBar').style.background = ph.color;
771
+ let acc=0, idx=0;
772
+ for (let k=0;k<STEPS.length;k++){ acc += STEPS[k].mi*1609.344; idx=k; if (pos <= acc) break; }
 
 
 
 
 
773
  document.querySelectorAll('#out .street.now').forEach(r => r.classList.remove('now'));
774
+ const row = document.querySelector('#out .street[data-step="' + (idx+1) + '"]');
775
+ if (row){ row.classList.add('now'); if (playing) row.scrollIntoView({block:'nearest'}); }
 
 
 
776
  }
777
 
778
  // ================= stats panel =================
779
  function renderStats(s){
780
+ const row = (l, v, c) => '<div class="stat ' + (c||'') + '"><span>' + l + '</span><b>' + v + '</b></div>';
 
 
781
  let h = '';
782
  h += row('Total route', s.total_mi.toFixed(2) + ' mi', 'big');
783
  h += row('Delivering', s.min_mi.toFixed(2) + ' mi', 'good');
 
791
  if (s.excluded_nodes)
792
  h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
793
  ' intersection(s) were unreachable from the main network and left out.</div>';
794
+ h += '<div class="hd" style="margin-top:8px">Turn-by-turn (colored by leg)</div>';
795
+ let acc = 0;
 
 
 
 
 
 
 
 
796
  STEPS.forEach(x => {
797
+ const col = x.deadhead ? '#ff3355' : PHASES[phaseOf(acc)].color;
798
+ acc += x.mi * 1609.344;
799
+ h += '<div class="street" data-step="' + x.step + '" style="border-left-color:' + col + '">' +
800
+ '<span>' + x.step + '. ' + (x.deadhead ? '<i style="color:#ff3355">(deadhead)</i> ' : '') +
801
  x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
802
  });
 
803
  document.getElementById('out').innerHTML = h;
 
804
  }
805
 
806
  function msg(t, cls){
807
  const m = document.getElementById('msg');
808
+ m.innerHTML = t || ''; m.className = 'msg' + (t ? ' ' + cls : '');
 
809
  }
810
  </script>
811
  </body>
 
883
  return jsonify({"error": "Unexpected error: %s" % exc}), 500
884
 
885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
  def _check_area(area):
887
  if area > MAX_AREA_SQ_MI:
888
  raise RouteError(