Upload app.py
Browse files
app.py
CHANGED
|
@@ -202,6 +202,65 @@ def build_route(E, start_node=None):
|
|
| 202 |
return steps
|
| 203 |
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
# ---------------------------------------------------------------- outputs
|
| 206 |
def compute_stats(R, steps, repeats):
|
| 207 |
required_m = sum(d["length"] for _, _, d in R.edges(data=True))
|
|
@@ -252,6 +311,8 @@ def route_geojson(E, steps):
|
|
| 252 |
"name": s["name"],
|
| 253 |
"mi": round(s["length"] / M_PER_MI, 3),
|
| 254 |
"deadhead": s["deadhead"],
|
|
|
|
|
|
|
| 255 |
},
|
| 256 |
}
|
| 257 |
)
|
|
@@ -277,10 +338,23 @@ def turn_by_turn(steps):
|
|
| 277 |
|
| 278 |
|
| 279 |
# ---------------------------------------------------------------- one-shot
|
| 280 |
-
def solve(G, walking=False, start_lat=None, start_lon=None):
|
| 281 |
-
"""Graph in, everything out. Verifies full coverage before returning.
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
start = None
|
| 286 |
if start_lat is not None and start_lon is not None:
|
|
@@ -290,16 +364,25 @@ def solve(G, walking=False, start_lat=None, start_lon=None):
|
|
| 290 |
start = None
|
| 291 |
|
| 292 |
steps = build_route(E, start)
|
| 293 |
-
|
| 294 |
-
# Hard guarantee: every required pass really is in the route.
|
| 295 |
-
used = defaultdict(int)
|
| 296 |
for s in steps:
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
return {
|
|
|
|
| 303 |
"stats": compute_stats(R, steps, repeats),
|
| 304 |
"geojson": route_geojson(E, steps),
|
| 305 |
"directions": turn_by_turn(steps),
|
|
@@ -362,7 +445,7 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 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:
|
| 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}
|
| 368 |
#scrub::-webkit-slider-thumb{-webkit-appearance:none;width:15px;height:15px;border-radius:50%;background:var(--acc);cursor:pointer;border:2px solid #0f1115}
|
|
@@ -387,13 +470,17 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 387 |
#map.routed .leaflet-tile-pane{filter:brightness(.72) saturate(.85)}
|
| 388 |
.pin{font:700 10px sans-serif;color:#fff;text-align:center;line-height:1;text-shadow:0 1px 3px #000;white-space:nowrap}
|
| 389 |
.pin svg{display:block;margin:0 auto}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
</style>
|
| 391 |
</head>
|
| 392 |
<body>
|
| 393 |
|
| 394 |
<header>
|
| 395 |
<h1>Route Em</h1>
|
| 396 |
-
<span class="sub">The shortest
|
| 397 |
</header>
|
| 398 |
|
| 399 |
<main>
|
|
@@ -421,6 +508,10 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 421 |
<button id="clear" class="sec">Clear</button>
|
| 422 |
<label class="ck"><input type="checkbox" id="walking"> Walking</label>
|
| 423 |
<label class="ck"><input type="checkbox" id="svc"> Alleys</label>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
<button id="solve" disabled>Solve route</button>
|
| 425 |
</div>
|
| 426 |
<div class="mapwrap">
|
|
@@ -433,6 +524,10 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 433 |
</div>
|
| 434 |
<div class="legend" id="legend"></div>
|
| 435 |
<div id="play">
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
<button id="pp">▶ Play</button>
|
| 437 |
<button id="restart" class="sec">↺</button>
|
| 438 |
<input type="range" id="scrub" min="0" max="1000" value="0">
|
|
@@ -443,6 +538,7 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 443 |
<option value="4">4×</option>
|
| 444 |
<option value="8">8×</option>
|
| 445 |
</select>
|
|
|
|
| 446 |
<label class="ck"><input type="checkbox" id="follow" checked> Follow</label>
|
| 447 |
<label class="ck"><input type="checkbox" id="arrowsOn" checked> Arrows</label>
|
| 448 |
</div>
|
|
@@ -474,7 +570,8 @@ drop.addEventListener('drop', e => {
|
|
| 474 |
function showShot(f){ const img=document.createElement('img'); img.src=URL.createObjectURL(f); drop.innerHTML=''; drop.appendChild(img); }
|
| 475 |
|
| 476 |
// ===== map + basemaps =====
|
| 477 |
-
const map = L.map('map').setView([39.83, -98.58], 4);
|
|
|
|
| 478 |
const streets = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
|
| 479 |
{maxZoom:19, attribution:'© OpenStreetMap, © CARTO'});
|
| 480 |
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
|
@@ -490,7 +587,7 @@ map.createPane('routePane'); map.getPane('routePane').style.zIndex = 450;
|
|
| 490 |
const drawn = new L.FeatureGroup().addTo(map);
|
| 491 |
// all map-layer handles declared ONCE, here
|
| 492 |
let arrowLayer=null, truck=null, startMarker=null, shape=null,
|
| 493 |
-
|
| 494 |
|
| 495 |
const SHAPE_STYLE={color:'#4f8cff', weight:2, fillOpacity:.06};
|
| 496 |
const boxTool = new L.Draw.Rectangle(map, {shapeOptions:SHAPE_STYLE});
|
|
@@ -560,21 +657,25 @@ solveBtn.onclick = async () => {
|
|
| 560 |
msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
|
| 561 |
const body = Object.assign({}, shape, {
|
| 562 |
walking: document.getElementById('walking').checked,
|
| 563 |
-
include_service: document.getElementById('svc').checked
|
|
|
|
| 564 |
if (startMarker) { body.start_lat = startMarker.getLatLng().lat; body.start_lon = startMarker.getLatLng().lng; }
|
| 565 |
try {
|
| 566 |
const r = await fetch('/solve', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
|
| 567 |
const d = await r.json();
|
| 568 |
if (!r.ok) { msg(d.error, 'err'); return; }
|
| 569 |
-
render(d); msg('');
|
| 570 |
} catch (err) { msg('Solve failed: ' + err, 'err'); }
|
| 571 |
finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
|
| 572 |
};
|
| 573 |
// ===== route data =====
|
| 574 |
let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
const
|
|
|
|
|
|
|
|
|
|
| 578 |
|
| 579 |
function bearing(a, b){
|
| 580 |
const r=Math.PI/180;
|
|
@@ -582,116 +683,155 @@ function bearing(a, b){
|
|
| 582 |
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);
|
| 583 |
return (Math.atan2(y,x)*180/Math.PI+360)%360;
|
| 584 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
|
| 586 |
function render(d){
|
| 587 |
-
stop();
|
| 588 |
-
[
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
|
|
|
| 592 |
const c=f.geometry.coordinates;
|
| 593 |
const a=L.latLng(c[0][1],c[0][0]), b=L.latLng(c[1][1],c[1][0]);
|
| 594 |
-
const len=map.distance(a,b);
|
| 595 |
-
|
|
|
|
| 596 |
TOTAL_M+=len;
|
| 597 |
});
|
| 598 |
DRIVE_MIN=d.stats.drive_min; STEPS=d.directions;
|
| 599 |
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
|
|
|
|
| 609 |
buildArrows();
|
| 610 |
-
startPin
|
| 611 |
-
truck
|
| 612 |
|
| 613 |
-
const bb=L.latLngBounds([]);
|
| 614 |
-
map.fitBounds(bb,
|
| 615 |
-
buildLegend();
|
| 616 |
document.getElementById('map').classList.add('routed');
|
| 617 |
document.getElementById('play').classList.add('on');
|
| 618 |
document.getElementById('hud').classList.add('on');
|
| 619 |
-
renderStats(d.stats);
|
| 620 |
-
resetTravel(); seek(0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
}
|
| 622 |
|
| 623 |
function buildArrows(){
|
| 624 |
if (arrowLayer) map.removeLayer(arrowLayer);
|
| 625 |
-
arrowLayer
|
| 626 |
-
const stride
|
| 627 |
PATH.forEach((s,i)=>{
|
| 628 |
-
if (i%stride) return;
|
| 629 |
-
if (s.len<28) return;
|
| 630 |
const mid=L.latLng((s.a.lat+s.b.lat)/2,(s.a.lng+s.b.lng)/2);
|
| 631 |
L.marker(mid,{interactive:false, icon:L.divIcon({className:'',iconSize:[16,16],iconAnchor:[8,8],
|
| 632 |
html:'<div class="arrow" style="transform:rotate('+bearing(s.a,s.b)+'deg)">'+
|
| 633 |
-
'<svg width="16" height="16" viewBox="0 0 16 16">'
|
| 634 |
-
'<path d="M8 2 L12 12 L8 9.6 L4 12 Z" fill="#111" stroke="#fff" stroke-width="1"/>'+
|
| 635 |
-
'</svg></div>'})}).addTo(arrowLayer);
|
| 636 |
});
|
| 637 |
if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
|
| 638 |
}
|
| 639 |
-
document.getElementById('arrowsOn').onchange
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
'<
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
'<div style="margin-top:-2px">'+label+'</div></div>'});
|
| 650 |
}
|
| 651 |
|
|
|
|
| 652 |
function truckIcon(deg){
|
| 653 |
-
return L.divIcon({className:'',iconSize:[
|
| 654 |
html:'<div class="truck" style="transform:rotate('+deg+'deg)">'+
|
| 655 |
-
'<svg width="
|
| 656 |
-
'<circle cx="
|
| 657 |
-
'<g transform="translate(
|
| 658 |
-
'<rect x="-
|
| 659 |
-
'<rect x="-
|
| 660 |
-
'<rect x="
|
| 661 |
-
'<rect x="
|
| 662 |
-
'<
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
'</g></svg></div>'});
|
| 664 |
}
|
| 665 |
|
| 666 |
-
function buildLegend(){
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
'<div class="lg"><span class="sw" style="background:'+
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
|
|
|
| 674 |
}
|
| 675 |
|
| 676 |
-
// =====
|
| 677 |
-
let
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
|
| 679 |
speedSel=document.getElementById('speed'), followCk=document.getElementById('follow');
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 683 |
|
| 684 |
-
function resetTravel(){
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
|
| 686 |
function play(){
|
| 687 |
if (!PATH.length) return;
|
| 688 |
-
if (pos
|
| 689 |
playing=true; pp.innerHTML='❙❙ Pause';
|
| 690 |
last=performance.now(); raf=requestAnimationFrame(tick);
|
| 691 |
}
|
| 692 |
-
function stop(){ playing=false; pp.innerHTML='▶ Play'; if
|
| 693 |
function tick(now){
|
| 694 |
-
if
|
| 695 |
const dt=Math.min((now-last)/1000,0.1); last=now;
|
| 696 |
pos += (TOTAL_M/75)*parseFloat(speedSel.value)*dt;
|
| 697 |
if (pos>=TOTAL_M){ seek(TOTAL_M); stop(); return; }
|
|
@@ -699,26 +839,32 @@ function tick(now){
|
|
| 699 |
}
|
| 700 |
|
| 701 |
function seek(m){
|
| 702 |
-
if
|
| 703 |
pos=Math.max(0,Math.min(m,TOTAL_M));
|
| 704 |
let lo=0,hi=PATH.length-1,i=0;
|
| 705 |
-
while
|
| 706 |
-
if
|
| 707 |
i=Math.min(lo,PATH.length-1); }
|
| 708 |
const s=PATH[i];
|
| 709 |
const f=s.len?Math.max(0,Math.min((pos-s.cum)/s.len,1)):0;
|
| 710 |
const here=L.latLng(s.a.lat+(s.b.lat-s.a.lat)*f, s.a.lng+(s.b.lng-s.a.lng)*f);
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 716 |
}
|
| 717 |
-
partialLine.setLatLngs([s.a, here]);
|
| 718 |
-
partialLine.setStyle({color: s.deadhead?C_DEAD:C_DONE});
|
| 719 |
truck.setLatLng(here); truck.setIcon(truckIcon(bearing(s.a,s.b)));
|
| 720 |
-
if (followCk.checked && playing && !map.getBounds().pad(-0.28).contains(here))
|
| 721 |
-
map.panTo(here,
|
| 722 |
scrub.value=Math.round((pos/TOTAL_M)*1000);
|
| 723 |
updateHud(s);
|
| 724 |
}
|
|
@@ -727,38 +873,75 @@ function updateHud(s){
|
|
| 727 |
const pct=pos/TOTAL_M;
|
| 728 |
const leg=document.getElementById('hudLeg');
|
| 729 |
leg.textContent=Math.round(pct*100)+'% driven';
|
| 730 |
-
leg.style.background=s.deadhead?C_DEAD:
|
| 731 |
document.getElementById('hudStreet').innerHTML=(s.deadhead?'<span style="color:'+C_DEAD+'">↷ </span>':'')+s.name;
|
| 732 |
document.getElementById('hudMeta').textContent=
|
| 733 |
(pos/1609.344).toFixed(2)+' / '+(TOTAL_M/1609.344).toFixed(2)+' mi · ~'+Math.round(DRIVE_MIN*pct)+' min in';
|
| 734 |
document.getElementById('hudBar').style.width=(pct*100)+'%';
|
| 735 |
-
document.getElementById('hudBar').style.background=
|
| 736 |
let acc=0,idx=0;
|
| 737 |
-
for
|
| 738 |
document.querySelectorAll('#out .street.now').forEach(r=>r.classList.remove('now'));
|
| 739 |
const row=document.querySelector('#out .street[data-step="'+(idx+1)+'"]');
|
| 740 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
}
|
|
|
|
| 742 |
|
| 743 |
-
// ===== stats
|
| 744 |
-
function renderStats(s){
|
| 745 |
const row=(l,v,c)=>'<div class="stat '+(c||'')+'"><span>'+l+'</span><b>'+v+'</b></div>';
|
| 746 |
let h='';
|
|
|
|
| 747 |
h+=row('Total route', s.total_mi.toFixed(2)+' mi','big');
|
| 748 |
h+=row('Delivering', s.min_mi.toFixed(2)+' mi','good');
|
| 749 |
-
h+=row('
|
| 750 |
h+=row('Efficiency', s.efficiency_pct.toFixed(1)+'%');
|
| 751 |
-
h+=row('
|
| 752 |
-
h+=row('Streets covered', s.streets.toLocaleString());
|
| 753 |
-
h+=row('Passes (both sides)', s.required_passes.toLocaleString());
|
| 754 |
h+=row('Est. driving time', Math.round(s.drive_min)+' min');
|
| 755 |
-
h+=
|
| 756 |
-
if (s.excluded_nodes) h+='<div class="msg info" style="display:block">'+s.excluded_nodes+' intersection(s) were unreachable and left out.</div>';
|
| 757 |
h+='<div class="hd" style="margin-top:8px">Turn-by-turn (in drive order)</div>';
|
| 758 |
STEPS.forEach(x=>{
|
| 759 |
-
const col=x.deadhead?C_DEAD:
|
| 760 |
h+='<div class="street" data-step="'+x.step+'" style="border-left-color:'+col+'"><span>'+x.step+'. '+
|
| 761 |
-
(x.deadhead?'<i style="color:'+C_DEAD+'">(
|
| 762 |
});
|
| 763 |
document.getElementById('out').innerHTML=h;
|
| 764 |
}
|
|
@@ -831,7 +1014,7 @@ def solve_route():
|
|
| 831 |
G = graph_from_bbox(b["north"], b["south"], b["east"], b["west"],
|
| 832 |
walking=walking, include_service=service)
|
| 833 |
|
| 834 |
-
return jsonify(solve(G, walking=walking,
|
| 835 |
start_lat=d.get("start_lat"), start_lon=d.get("start_lon")))
|
| 836 |
except RouteError as exc:
|
| 837 |
return jsonify({"error": str(exc)}), 400
|
|
|
|
| 202 |
return steps
|
| 203 |
|
| 204 |
|
| 205 |
+
# ---------------------------------------------------------------- pair helper
|
| 206 |
+
def _pair(u, v):
|
| 207 |
+
"""Stable key for the physical street between two nodes (both directions share it)."""
|
| 208 |
+
return "%s_%s" % (min(u, v), max(u, v))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# ---------------------------------------------------------------- drive-each-street-once
|
| 212 |
+
def solve_cpp_once(G, walking=False):
|
| 213 |
+
"""Undirected Chinese Postman: cover every street ONCE, minimal driving.
|
| 214 |
+
Returns (U_required_undirected, E_eulerian, repeat_edges)."""
|
| 215 |
+
U = nx.MultiGraph()
|
| 216 |
+
U.graph["crs"] = G.graph.get("crs", "epsg:4326")
|
| 217 |
+
for n, d in G.nodes(data=True):
|
| 218 |
+
U.add_node(n, **d)
|
| 219 |
+
|
| 220 |
+
seen = set()
|
| 221 |
+
for u, v, k, d in G.edges(keys=True, data=True):
|
| 222 |
+
if (v, u, k) in seen: # reverse of an already-added two-way street
|
| 223 |
+
continue
|
| 224 |
+
seen.add((u, v, k))
|
| 225 |
+
name = d.get("name", "unnamed road")
|
| 226 |
+
if isinstance(name, list):
|
| 227 |
+
name = name[0]
|
| 228 |
+
U.add_edge(u, v, length=float(d.get("length", 0.0)), name=name, required=True)
|
| 229 |
+
|
| 230 |
+
U.remove_nodes_from(list(nx.isolates(U)))
|
| 231 |
+
if U.number_of_edges() == 0:
|
| 232 |
+
raise RouteError("That area has no deliverable streets in OpenStreetMap.")
|
| 233 |
+
if not nx.is_connected(U):
|
| 234 |
+
U = U.subgraph(max(nx.connected_components(U), key=len)).copy()
|
| 235 |
+
if U.number_of_edges() > MAX_REQUIRED_PASSES:
|
| 236 |
+
raise RouteError(
|
| 237 |
+
"That area needs %d street passes (limit %d). Draw a smaller area."
|
| 238 |
+
% (U.number_of_edges(), MAX_REQUIRED_PASSES))
|
| 239 |
+
|
| 240 |
+
# make it Eulerian: min-weight matching of odd-degree nodes, duplicate those paths
|
| 241 |
+
import itertools
|
| 242 |
+
|
| 243 |
+
odd = [n for n, deg in U.degree() if deg % 2 == 1]
|
| 244 |
+
E = nx.MultiGraph(U)
|
| 245 |
+
repeats = []
|
| 246 |
+
if odd:
|
| 247 |
+
dist, path = {}, {}
|
| 248 |
+
for o in odd:
|
| 249 |
+
dl, pp = nx.single_source_dijkstra(U, o, weight="length")
|
| 250 |
+
dist[o], path[o] = dl, pp
|
| 251 |
+
K = nx.Graph()
|
| 252 |
+
for a, b in itertools.combinations(odd, 2):
|
| 253 |
+
if b in dist[a]:
|
| 254 |
+
K.add_edge(a, b, weight=dist[a][b])
|
| 255 |
+
for a, b in nx.min_weight_matching(K):
|
| 256 |
+
p = path[a][b]
|
| 257 |
+
for x, y in zip(p[:-1], p[1:]):
|
| 258 |
+
seg = min(U[x][y].values(), key=lambda e: e["length"])
|
| 259 |
+
E.add_edge(x, y, length=seg["length"], name=seg.get("name"), required=False)
|
| 260 |
+
repeats.append((x, y))
|
| 261 |
+
return U, E, repeats
|
| 262 |
+
|
| 263 |
+
|
| 264 |
# ---------------------------------------------------------------- outputs
|
| 265 |
def compute_stats(R, steps, repeats):
|
| 266 |
required_m = sum(d["length"] for _, _, d in R.edges(data=True))
|
|
|
|
| 311 |
"name": s["name"],
|
| 312 |
"mi": round(s["length"] / M_PER_MI, 3),
|
| 313 |
"deadhead": s["deadhead"],
|
| 314 |
+
"pair": s.get("pair"),
|
| 315 |
+
"needed": s.get("needed", 1),
|
| 316 |
},
|
| 317 |
}
|
| 318 |
)
|
|
|
|
| 338 |
|
| 339 |
|
| 340 |
# ---------------------------------------------------------------- one-shot
|
| 341 |
+
def solve(G, walking=False, start_lat=None, start_lon=None, coverage="both"):
|
| 342 |
+
"""Graph in, everything out. Verifies full coverage before returning.
|
| 343 |
+
|
| 344 |
+
coverage="both": drive both directions of every two-way street (curb-by-curb).
|
| 345 |
+
coverage="once": drive every street a single time (minimal driving, no pac-man).
|
| 346 |
+
"""
|
| 347 |
+
if coverage == "once":
|
| 348 |
+
R, E, repeats = solve_cpp_once(G, walking)
|
| 349 |
+
R.graph.setdefault("excluded_nodes", 0)
|
| 350 |
+
else:
|
| 351 |
+
R = build_both_sides(G, walking)
|
| 352 |
+
R, E, repeats = solve_dcpp(R)
|
| 353 |
+
|
| 354 |
+
# how many required passes each physical street needs (for red/yellow/green)
|
| 355 |
+
needed = defaultdict(int)
|
| 356 |
+
for u, v, d in R.edges(data=True):
|
| 357 |
+
needed[_pair(u, v)] += 1
|
| 358 |
|
| 359 |
start = None
|
| 360 |
if start_lat is not None and start_lon is not None:
|
|
|
|
| 364 |
start = None
|
| 365 |
|
| 366 |
steps = build_route(E, start)
|
|
|
|
|
|
|
|
|
|
| 367 |
for s in steps:
|
| 368 |
+
pk = _pair(s["u"], s["v"])
|
| 369 |
+
s["pair"] = pk
|
| 370 |
+
s["needed"] = 0 if s["deadhead"] else needed.get(pk, 1)
|
| 371 |
+
|
| 372 |
+
# Hard guarantee: every required pass is covered (order-independent count).
|
| 373 |
+
need_ct = defaultdict(int)
|
| 374 |
+
for u, v, d in R.edges(data=True):
|
| 375 |
+
need_ct[_pair(u, v)] += 1
|
| 376 |
+
have_ct = defaultdict(int)
|
| 377 |
+
for s in steps:
|
| 378 |
+
if not s["deadhead"]:
|
| 379 |
+
have_ct[s["pair"]] += 1
|
| 380 |
+
short = [p for p, c in need_ct.items() if have_ct[p] < c]
|
| 381 |
+
if short:
|
| 382 |
+
raise RouteError("Internal: %d streets not fully covered." % len(short))
|
| 383 |
|
| 384 |
return {
|
| 385 |
+
"coverage": coverage,
|
| 386 |
"stats": compute_stats(R, steps, repeats),
|
| 387 |
"geojson": route_geojson(E, steps),
|
| 388 |
"directions": turn_by_turn(steps),
|
|
|
|
| 445 |
.street.now{background:#ffffff14;color:var(--txt)}
|
| 446 |
.empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
|
| 447 |
.mapwrap{position:relative;flex:1;display:flex;min-height:0}
|
| 448 |
+
#play{position:absolute;left:50%;transform:translateX(-50%);bottom:16px;z-index:1000;background:#0f1115f2;border:1px solid var(--line);border-radius:12px;padding:8px 12px;display:none;gap:9px;align-items:center;flex-wrap:wrap;max-width:min(620px,92%);box-shadow:0 4px 18px rgba(0,0,0,.55)}
|
| 449 |
#play.on{display:flex}
|
| 450 |
#scrub{flex:1;min-width:160px;-webkit-appearance:none;appearance:none;height:5px;border-radius:3px;background:#2b3342;outline:0;cursor:pointer}
|
| 451 |
#scrub::-webkit-slider-thumb{-webkit-appearance:none;width:15px;height:15px;border-radius:50%;background:var(--acc);cursor:pointer;border:2px solid #0f1115}
|
|
|
|
| 470 |
#map.routed .leaflet-tile-pane{filter:brightness(.72) saturate(.85)}
|
| 471 |
.pin{font:700 10px sans-serif;color:#fff;text-align:center;line-height:1;text-shadow:0 1px 3px #000;white-space:nowrap}
|
| 472 |
.pin svg{display:block;margin:0 auto}
|
| 473 |
+
.modeseg{display:flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}
|
| 474 |
+
.modeseg button{background:#252a35;border-radius:0;padding:8px 10px;font-size:12px}
|
| 475 |
+
.modeseg button.on{background:var(--acc);color:#fff}
|
| 476 |
+
#gps.on{background:var(--bad)}
|
| 477 |
</style>
|
| 478 |
</head>
|
| 479 |
<body>
|
| 480 |
|
| 481 |
<header>
|
| 482 |
<h1>Route Em</h1>
|
| 483 |
+
<span class="sub">The shortest driving loop that covers every street in your area</span>
|
| 484 |
</header>
|
| 485 |
|
| 486 |
<main>
|
|
|
|
| 508 |
<button id="clear" class="sec">Clear</button>
|
| 509 |
<label class="ck"><input type="checkbox" id="walking"> Walking</label>
|
| 510 |
<label class="ck"><input type="checkbox" id="svc"> Alleys</label>
|
| 511 |
+
<select id="coverage" title="How thoroughly to cover each street">
|
| 512 |
+
<option value="once" selected>Drive each street once</option>
|
| 513 |
+
<option value="both">Cover both sides (curb by curb)</option>
|
| 514 |
+
</select>
|
| 515 |
<button id="solve" disabled>Solve route</button>
|
| 516 |
</div>
|
| 517 |
<div class="mapwrap">
|
|
|
|
| 524 |
</div>
|
| 525 |
<div class="legend" id="legend"></div>
|
| 526 |
<div id="play">
|
| 527 |
+
<div class="modeseg">
|
| 528 |
+
<button id="mSim" class="on">▶ Simulate</button>
|
| 529 |
+
<button id="mTrack">◉ Track</button>
|
| 530 |
+
</div>
|
| 531 |
<button id="pp">▶ Play</button>
|
| 532 |
<button id="restart" class="sec">↺</button>
|
| 533 |
<input type="range" id="scrub" min="0" max="1000" value="0">
|
|
|
|
| 538 |
<option value="4">4×</option>
|
| 539 |
<option value="8">8×</option>
|
| 540 |
</select>
|
| 541 |
+
<button id="gps" class="sec" style="display:none">Start GPS</button>
|
| 542 |
<label class="ck"><input type="checkbox" id="follow" checked> Follow</label>
|
| 543 |
<label class="ck"><input type="checkbox" id="arrowsOn" checked> Arrows</label>
|
| 544 |
</div>
|
|
|
|
| 570 |
function showShot(f){ const img=document.createElement('img'); img.src=URL.createObjectURL(f); drop.innerHTML=''; drop.appendChild(img); }
|
| 571 |
|
| 572 |
// ===== map + basemaps =====
|
| 573 |
+
const map = L.map('map', {zoomControl:false}).setView([39.83, -98.58], 4);
|
| 574 |
+
L.control.zoom({position:'bottomleft'}).addTo(map);
|
| 575 |
const streets = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
|
| 576 |
{maxZoom:19, attribution:'© OpenStreetMap, © CARTO'});
|
| 577 |
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
|
|
|
| 587 |
const drawn = new L.FeatureGroup().addTo(map);
|
| 588 |
// all map-layer handles declared ONCE, here
|
| 589 |
let arrowLayer=null, truck=null, startMarker=null, shape=null,
|
| 590 |
+
partialLine=null, startPin=null;
|
| 591 |
|
| 592 |
const SHAPE_STYLE={color:'#4f8cff', weight:2, fillOpacity:.06};
|
| 593 |
const boxTool = new L.Draw.Rectangle(map, {shapeOptions:SHAPE_STYLE});
|
|
|
|
| 657 |
msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
|
| 658 |
const body = Object.assign({}, shape, {
|
| 659 |
walking: document.getElementById('walking').checked,
|
| 660 |
+
include_service: document.getElementById('svc').checked,
|
| 661 |
+
coverage: document.getElementById('coverage').value });
|
| 662 |
if (startMarker) { body.start_lat = startMarker.getLatLng().lat; body.start_lon = startMarker.getLatLng().lng; }
|
| 663 |
try {
|
| 664 |
const r = await fetch('/solve', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
|
| 665 |
const d = await r.json();
|
| 666 |
if (!r.ok) { msg(d.error, 'err'); return; }
|
| 667 |
+
render(d); msg('Ready. Press ▶ Play to drive the route \u2014 the blue TRUCK START pin is where it begins.', 'info');
|
| 668 |
} catch (err) { msg('Solve failed: ' + err, 'err'); }
|
| 669 |
finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
|
| 670 |
};
|
| 671 |
// ===== route data =====
|
| 672 |
let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
|
| 673 |
+
let routeGroup=null, segLine=[], pairSegs={}, doneCount={}, paintedUpto=0;
|
| 674 |
+
|
| 675 |
+
const C_NONE='#ef4444'; // not covered (red)
|
| 676 |
+
const C_HALF='#ffd21e'; // one side done (yellow)
|
| 677 |
+
const C_FULL='#22c55e'; // fully covered (green)
|
| 678 |
+
const C_DEAD='#9aa4b2'; // deadhead / connector (grey, dashed)
|
| 679 |
|
| 680 |
function bearing(a, b){
|
| 681 |
const r=Math.PI/180;
|
|
|
|
| 683 |
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);
|
| 684 |
return (Math.atan2(y,x)*180/Math.PI+360)%360;
|
| 685 |
}
|
| 686 |
+
function segColor(pair){
|
| 687 |
+
const need = PAIR_NEED[pair] || 1, have = doneCount[pair] || 0;
|
| 688 |
+
return have<=0 ? C_NONE : (have>=need ? C_FULL : C_HALF);
|
| 689 |
+
}
|
| 690 |
+
let PAIR_NEED={};
|
| 691 |
|
| 692 |
function render(d){
|
| 693 |
+
stop(); stopTracking();
|
| 694 |
+
[routeGroup, partialLine, truck, startPin].forEach(l => l && map.removeLayer(l));
|
| 695 |
+
|
| 696 |
+
const feats=d.geojson.features;
|
| 697 |
+
PATH=[]; TOTAL_M=0; PAIR_NEED={};
|
| 698 |
+
feats.forEach(f=>{
|
| 699 |
const c=f.geometry.coordinates;
|
| 700 |
const a=L.latLng(c[0][1],c[0][0]), b=L.latLng(c[1][1],c[1][0]);
|
| 701 |
+
const len=map.distance(a,b), p=f.properties;
|
| 702 |
+
if (!p.deadhead && p.needed) PAIR_NEED[p.pair]=p.needed;
|
| 703 |
+
PATH.push({a,b,len,cum:TOTAL_M,name:p.name,deadhead:p.deadhead,pair:p.pair,needed:p.needed,order:p.order});
|
| 704 |
TOTAL_M+=len;
|
| 705 |
});
|
| 706 |
DRIVE_MIN=d.stats.drive_min; STEPS=d.directions;
|
| 707 |
|
| 708 |
+
// draw one polyline per segment (required = red base, deadhead = grey dashed), keep refs
|
| 709 |
+
routeGroup=L.layerGroup([], {pane:'routePane'}).addTo(map);
|
| 710 |
+
segLine=[]; pairSegs={};
|
| 711 |
+
PATH.forEach((s,i)=>{
|
| 712 |
+
L.polyline([s.a,s.b],{pane:'routePane',color:'#05070c',weight:s.deadhead?6:8.5,opacity:.55,lineCap:'round'}).addTo(routeGroup);
|
| 713 |
+
const ln=L.polyline([s.a,s.b],{pane:'routePane',
|
| 714 |
+
color:s.deadhead?C_DEAD:C_NONE, weight:s.deadhead?3.5:5.5, opacity:.95,
|
| 715 |
+
lineCap:'round', dashArray:s.deadhead?'2,7':null}).addTo(routeGroup);
|
| 716 |
+
ln.bindTooltip('#'+s.order+' '+s.name+(s.deadhead?' — connector (no delivery)':''));
|
| 717 |
+
segLine[i]=ln;
|
| 718 |
+
if (!s.deadhead){ (pairSegs[s.pair]=pairSegs[s.pair]||[]).push(i); }
|
| 719 |
+
});
|
| 720 |
|
| 721 |
+
partialLine=L.polyline([],{pane:'routePane',color:C_HALF,weight:6.5,opacity:1,lineCap:'round'}).addTo(map);
|
| 722 |
buildArrows();
|
| 723 |
+
startPin=L.marker(PATH[0].a,{zIndexOffset:1100, icon:flagIcon()}).addTo(map);
|
| 724 |
+
truck=L.marker(PATH[0].a,{icon:truckIcon(0), zIndexOffset:1200, interactive:false}).addTo(map);
|
| 725 |
|
| 726 |
+
const bb=L.latLngBounds([]); PATH.forEach(s=>{bb.extend(s.a); bb.extend(s.b);});
|
| 727 |
+
map.fitBounds(bb,{padding:[30,30]});
|
| 728 |
+
buildLegend(d.coverage);
|
| 729 |
document.getElementById('map').classList.add('routed');
|
| 730 |
document.getElementById('play').classList.add('on');
|
| 731 |
document.getElementById('hud').classList.add('on');
|
| 732 |
+
renderStats(d.stats, d.coverage);
|
| 733 |
+
setMode('sim'); resetTravel(); seek(0);
|
| 734 |
+
msg('Ready. Press ▶ Play (or switch to Track). Checkered flag = start/finish.', 'info');
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
function recolorPair(pair){
|
| 738 |
+
const c=segColor(pair);
|
| 739 |
+
(pairSegs[pair]||[]).forEach(i => segLine[i].setStyle({color:c}));
|
| 740 |
}
|
| 741 |
|
| 742 |
function buildArrows(){
|
| 743 |
if (arrowLayer) map.removeLayer(arrowLayer);
|
| 744 |
+
arrowLayer=L.layerGroup();
|
| 745 |
+
const stride=Math.max(1,Math.ceil(PATH.length/80));
|
| 746 |
PATH.forEach((s,i)=>{
|
| 747 |
+
if (i%stride || s.len<28) return;
|
|
|
|
| 748 |
const mid=L.latLng((s.a.lat+s.b.lat)/2,(s.a.lng+s.b.lng)/2);
|
| 749 |
L.marker(mid,{interactive:false, icon:L.divIcon({className:'',iconSize:[16,16],iconAnchor:[8,8],
|
| 750 |
html:'<div class="arrow" style="transform:rotate('+bearing(s.a,s.b)+'deg)">'+
|
| 751 |
+
'<svg width="16" height="16" viewBox="0 0 16 16"><path d="M8 2 L12 12 L8 9.6 L4 12 Z" fill="#111" stroke="#fff" stroke-width="1"/></svg></div>'})}).addTo(arrowLayer);
|
|
|
|
|
|
|
| 752 |
});
|
| 753 |
if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
|
| 754 |
}
|
| 755 |
+
document.getElementById('arrowsOn').onchange=e=>{ if(!arrowLayer)return; e.target.checked?arrowLayer.addTo(map):map.removeLayer(arrowLayer); };
|
| 756 |
+
|
| 757 |
+
function flagIcon(){
|
| 758 |
+
let sq='';
|
| 759 |
+
for (let r=0;r<3;r++) for (let c=0;c<4;c++) if ((r+c)%2===0) sq+='<rect x="'+(6+c*4)+'" y="'+(3+r*4)+'" width="4" height="4" fill="#111"/>';
|
| 760 |
+
return L.divIcon({className:'',iconSize:[64,40],iconAnchor:[6,34],html:
|
| 761 |
+
'<div class="pin"><svg width="26" height="34" viewBox="0 0 26 34">'+
|
| 762 |
+
'<rect x="4" y="2" width="2" height="30" fill="#e7eaf0"/>'+
|
| 763 |
+
'<rect x="6" y="3" width="16" height="12" fill="#fff" stroke="#05070c" stroke-width="1"/>'+sq+
|
| 764 |
+
'</svg><div style="margin-top:-3px">START / FINISH</div></div>'});
|
|
|
|
| 765 |
}
|
| 766 |
|
| 767 |
+
// garbage truck, nose points the drive direction
|
| 768 |
function truckIcon(deg){
|
| 769 |
+
return L.divIcon({className:'',iconSize:[40,40],iconAnchor:[20,20],
|
| 770 |
html:'<div class="truck" style="transform:rotate('+deg+'deg)">'+
|
| 771 |
+
'<svg width="40" height="40" viewBox="0 0 40 40">'+
|
| 772 |
+
'<circle cx="20" cy="20" r="17" fill="#05070c" opacity=".55"/>'+
|
| 773 |
+
'<g transform="translate(20,20) rotate(90)">'+
|
| 774 |
+
'<rect x="-11" y="-7" width="12" height="14" rx="1.5" fill="#3ea34a"/>'+ /* refuse body */
|
| 775 |
+
'<rect x="-12.5" y="-7" width="2.5" height="14" fill="#2f8038"/>'+ /* rear */
|
| 776 |
+
'<rect x="1" y="-6" width="8" height="13" rx="1.5" fill="#dfe8ff"/>'+ /* cab */
|
| 777 |
+
'<rect x="6.5" y="-5" width="3.5" height="5" rx="1" fill="#9fc2ff"/>'+ /* windshield */
|
| 778 |
+
'<rect x="-9" y="-8.5" width="9" height="2" rx="1" fill="#2f8038"/>'+ /* lid */
|
| 779 |
+
'<circle cx="-6" cy="8" r="2.4" fill="#111"/>'+
|
| 780 |
+
'<circle cx="5" cy="8" r="2.4" fill="#111"/>'+
|
| 781 |
+
'<circle cx="-6" cy="-8" r="2.4" fill="#111"/>'+
|
| 782 |
+
'<circle cx="5" cy="-8" r="2.4" fill="#111"/>'+
|
| 783 |
'</g></svg></div>'});
|
| 784 |
}
|
| 785 |
|
| 786 |
+
function buildLegend(cov){
|
| 787 |
+
const both = cov==='both';
|
| 788 |
+
let h='<div class="ttl">Coverage</div>'+
|
| 789 |
+
'<div class="lg"><span class="sw" style="background:'+C_NONE+'"></span>not covered</div>';
|
| 790 |
+
if (both) h+='<div class="lg"><span class="sw" style="background:'+C_HALF+'"></span>one side done</div>';
|
| 791 |
+
h+='<div class="lg"><span class="sw" style="background:'+C_FULL+'"></span>'+(both?'both sides done':'covered')+'</div>'+
|
| 792 |
+
'<div class="lg"><span class="sw" style="background:'+C_DEAD+'"></span>connector (no delivery)</div>'+
|
| 793 |
+
'<div class="lg" style="margin-top:5px"><span class="sw" style="background:#fff"></span>start / finish (checkered)</div>';
|
| 794 |
+
const el=document.getElementById('legend'); el.innerHTML=h; el.style.display='block';
|
| 795 |
}
|
| 796 |
|
| 797 |
+
// ===== Simulate vs Track (real GPS) =====
|
| 798 |
+
let mode='sim', watchId=null, maxReached=0, gpsMark=null;
|
| 799 |
+
const mSim=document.getElementById('mSim'), mTrack=document.getElementById('mTrack'), gpsBtn=document.getElementById('gps');
|
| 800 |
+
|
| 801 |
+
// ===== animation =====
|
| 802 |
+
let pos=0, playing=false, raf=null, last=0;
|
| 803 |
const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
|
| 804 |
speedSel=document.getElementById('speed'), followCk=document.getElementById('follow');
|
| 805 |
+
const simControls=[pp, document.getElementById('restart'), scrub, speedSel];
|
| 806 |
+
pp.onclick=()=>playing?stop():play();
|
| 807 |
+
document.getElementById('restart').onclick=()=>{ seek(0); play(); };
|
| 808 |
+
scrub.oninput=()=>{ stop(); seek(TOTAL_M*(scrub.value/1000)); };
|
| 809 |
+
|
| 810 |
+
function setMode(m){
|
| 811 |
+
mode=m;
|
| 812 |
+
mSim.classList.toggle('on', m==='sim');
|
| 813 |
+
mTrack.classList.toggle('on', m==='track');
|
| 814 |
+
if (m==='sim'){ stopTracking(); gpsBtn.style.display='none'; simControls.forEach(el=>el.style.display=''); }
|
| 815 |
+
else { stop(); gpsBtn.style.display=''; simControls.forEach(el=>el.style.display='none'); }
|
| 816 |
+
}
|
| 817 |
+
mSim.onclick=()=>setMode('sim');
|
| 818 |
+
mTrack.onclick=()=>setMode('track');
|
| 819 |
|
| 820 |
+
function resetTravel(){
|
| 821 |
+
doneCount={}; paintedUpto=0; maxReached=0;
|
| 822 |
+
PATH.forEach((s,i)=>{ if(segLine[i]) segLine[i].setStyle({color:s.deadhead?C_DEAD:C_NONE}); });
|
| 823 |
+
if (partialLine) partialLine.setLatLngs([]);
|
| 824 |
+
}
|
| 825 |
|
| 826 |
function play(){
|
| 827 |
if (!PATH.length) return;
|
| 828 |
+
if (pos>=TOTAL_M-0.5){ pos=0; resetTravel(); }
|
| 829 |
playing=true; pp.innerHTML='❙❙ Pause';
|
| 830 |
last=performance.now(); raf=requestAnimationFrame(tick);
|
| 831 |
}
|
| 832 |
+
function stop(){ playing=false; pp.innerHTML='▶ Play'; if(raf)cancelAnimationFrame(raf); raf=null; }
|
| 833 |
function tick(now){
|
| 834 |
+
if(!playing) return;
|
| 835 |
const dt=Math.min((now-last)/1000,0.1); last=now;
|
| 836 |
pos += (TOTAL_M/75)*parseFloat(speedSel.value)*dt;
|
| 837 |
if (pos>=TOTAL_M){ seek(TOTAL_M); stop(); return; }
|
|
|
|
| 839 |
}
|
| 840 |
|
| 841 |
function seek(m){
|
| 842 |
+
if(!PATH.length) return;
|
| 843 |
pos=Math.max(0,Math.min(m,TOTAL_M));
|
| 844 |
let lo=0,hi=PATH.length-1,i=0;
|
| 845 |
+
while(lo<=hi){ const mid=(lo+hi)>>1,s=PATH[mid];
|
| 846 |
+
if(pos<s.cum)hi=mid-1; else if(pos>s.cum+s.len)lo=mid+1; else {i=mid;break;}
|
| 847 |
i=Math.min(lo,PATH.length-1); }
|
| 848 |
const s=PATH[i];
|
| 849 |
const f=s.len?Math.max(0,Math.min((pos-s.cum)/s.len,1)):0;
|
| 850 |
const here=L.latLng(s.a.lat+(s.b.lat-s.a.lat)*f, s.a.lng+(s.b.lng-s.a.lng)*f);
|
| 851 |
+
|
| 852 |
+
if (i<paintedUpto) resetTravel();
|
| 853 |
+
while (paintedUpto<i){
|
| 854 |
+
const p=PATH[paintedUpto];
|
| 855 |
+
if (!p.deadhead){ doneCount[p.pair]=(doneCount[p.pair]||0)+1; recolorPair(p.pair); }
|
| 856 |
+
paintedUpto++;
|
| 857 |
+
}
|
| 858 |
+
// current segment: show the part covered so far, tinted to its FUTURE state
|
| 859 |
+
if (s.deadhead){ partialLine.setLatLngs([]); }
|
| 860 |
+
else {
|
| 861 |
+
const willHave=(doneCount[s.pair]||0)+1, need=PAIR_NEED[s.pair]||1;
|
| 862 |
+
partialLine.setStyle({color: willHave>=need ? C_FULL : C_HALF});
|
| 863 |
+
partialLine.setLatLngs([s.a, here]);
|
| 864 |
}
|
|
|
|
|
|
|
| 865 |
truck.setLatLng(here); truck.setIcon(truckIcon(bearing(s.a,s.b)));
|
| 866 |
+
if (followCk.checked && (playing||mode==='track') && !map.getBounds().pad(-0.28).contains(here))
|
| 867 |
+
map.panTo(here,{animate:true,duration:.5});
|
| 868 |
scrub.value=Math.round((pos/TOTAL_M)*1000);
|
| 869 |
updateHud(s);
|
| 870 |
}
|
|
|
|
| 873 |
const pct=pos/TOTAL_M;
|
| 874 |
const leg=document.getElementById('hudLeg');
|
| 875 |
leg.textContent=Math.round(pct*100)+'% driven';
|
| 876 |
+
leg.style.background=s.deadhead?C_DEAD:C_FULL;
|
| 877 |
document.getElementById('hudStreet').innerHTML=(s.deadhead?'<span style="color:'+C_DEAD+'">↷ </span>':'')+s.name;
|
| 878 |
document.getElementById('hudMeta').textContent=
|
| 879 |
(pos/1609.344).toFixed(2)+' / '+(TOTAL_M/1609.344).toFixed(2)+' mi · ~'+Math.round(DRIVE_MIN*pct)+' min in';
|
| 880 |
document.getElementById('hudBar').style.width=(pct*100)+'%';
|
| 881 |
+
document.getElementById('hudBar').style.background=C_FULL;
|
| 882 |
let acc=0,idx=0;
|
| 883 |
+
for(let k=0;k<STEPS.length;k++){ acc+=STEPS[k].mi*1609.344; idx=k; if(pos<=acc)break; }
|
| 884 |
document.querySelectorAll('#out .street.now').forEach(r=>r.classList.remove('now'));
|
| 885 |
const row=document.querySelector('#out .street[data-step="'+(idx+1)+'"]');
|
| 886 |
+
if(row){ row.classList.add('now'); if(playing)row.scrollIntoView({block:'nearest'}); }
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
// ===== GPS tracking =====
|
| 890 |
+
function projectToRoute(ll){
|
| 891 |
+
let best=Infinity,bestCum=0;
|
| 892 |
+
for(const s of PATH){
|
| 893 |
+
const latR=(s.a.lat+s.b.lat)/2*Math.PI/180,k=Math.cos(latR)*111320;
|
| 894 |
+
const bx=(s.b.lng-s.a.lng)*k,by=(s.b.lat-s.a.lat)*111320;
|
| 895 |
+
const px=(ll.lng-s.a.lng)*k,py=(ll.lat-s.a.lat)*111320;
|
| 896 |
+
const L2=bx*bx+by*by||1e-9; let t=(px*bx+py*by)/L2; t=Math.max(0,Math.min(1,t));
|
| 897 |
+
const dx=px-bx*t,dy=py-by*t,dd=Math.hypot(dx,dy);
|
| 898 |
+
if(dd<best){best=dd;bestCum=s.cum+t*s.len;}
|
| 899 |
+
}
|
| 900 |
+
return {dist:best,cum:bestCum};
|
| 901 |
+
}
|
| 902 |
+
function startTracking(){
|
| 903 |
+
if(!('geolocation' in navigator)){ msg('This device has no location support.','err'); return; }
|
| 904 |
+
if(!PATH.length){ msg('Solve a route first.','err'); return; }
|
| 905 |
+
resetTravel();
|
| 906 |
+
gpsBtn.textContent='Stop GPS'; gpsBtn.classList.add('on');
|
| 907 |
+
msg('Tracking your location — drive the route, streets fill in as you cover them.','info');
|
| 908 |
+
watchId=navigator.geolocation.watchPosition(onPos,onGpsErr,{enableHighAccuracy:true,maximumAge:1000,timeout:20000});
|
| 909 |
+
}
|
| 910 |
+
function stopTracking(){
|
| 911 |
+
if(watchId!=null){ navigator.geolocation.clearWatch(watchId); watchId=null; }
|
| 912 |
+
if(gpsMark){ map.removeLayer(gpsMark); gpsMark=null; }
|
| 913 |
+
gpsBtn.textContent='Start GPS'; gpsBtn.classList.remove('on');
|
| 914 |
+
}
|
| 915 |
+
gpsBtn.onclick=()=>(watchId==null?startTracking():stopTracking());
|
| 916 |
+
function onPos(p){
|
| 917 |
+
if(!PATH.length) return;
|
| 918 |
+
const ll=L.latLng(p.coords.latitude,p.coords.longitude);
|
| 919 |
+
const pr=projectToRoute(ll);
|
| 920 |
+
if(pr.cum>maxReached) maxReached=pr.cum;
|
| 921 |
+
seek(maxReached);
|
| 922 |
+
if(!gpsMark) gpsMark=L.circleMarker(ll,{radius:6,color:'#fff',weight:2,fillColor:'#3b82f6',fillOpacity:.9,pane:'routePane'}).addTo(map);
|
| 923 |
+
else gpsMark.setLatLng(ll);
|
| 924 |
+
if(followCk.checked) map.panTo(ll,{animate:true,duration:.5});
|
| 925 |
}
|
| 926 |
+
function onGpsErr(e){ msg('Location error: '+e.message+'. Allow location access (page must be HTTPS).','err'); stopTracking(); }
|
| 927 |
|
| 928 |
+
// ===== stats =====
|
| 929 |
+
function renderStats(s, cov){
|
| 930 |
const row=(l,v,c)=>'<div class="stat '+(c||'')+'"><span>'+l+'</span><b>'+v+'</b></div>';
|
| 931 |
let h='';
|
| 932 |
+
h+=row('Mode', cov==='both'?'Both sides':'Each street once');
|
| 933 |
h+=row('Total route', s.total_mi.toFixed(2)+' mi','big');
|
| 934 |
h+=row('Delivering', s.min_mi.toFixed(2)+' mi','good');
|
| 935 |
+
h+=row('Backtrack (deadhead)', s.deadhead_mi.toFixed(2)+' mi','warn');
|
| 936 |
h+=row('Efficiency', s.efficiency_pct.toFixed(1)+'%');
|
| 937 |
+
h+=row('Streets', s.streets.toLocaleString());
|
|
|
|
|
|
|
| 938 |
h+=row('Est. driving time', Math.round(s.drive_min)+' min');
|
| 939 |
+
if(s.excluded_nodes) h+='<div class="msg info" style="display:block">'+s.excluded_nodes+' intersection(s) were unreachable and left out.</div>';
|
|
|
|
| 940 |
h+='<div class="hd" style="margin-top:8px">Turn-by-turn (in drive order)</div>';
|
| 941 |
STEPS.forEach(x=>{
|
| 942 |
+
const col=x.deadhead?C_DEAD:C_FULL;
|
| 943 |
h+='<div class="street" data-step="'+x.step+'" style="border-left-color:'+col+'"><span>'+x.step+'. '+
|
| 944 |
+
(x.deadhead?'<i style="color:'+C_DEAD+'">(connector)</i> ':'')+x.name+'</span><b>'+x.mi.toFixed(2)+'</b></div>';
|
| 945 |
});
|
| 946 |
document.getElementById('out').innerHTML=h;
|
| 947 |
}
|
|
|
|
| 1014 |
G = graph_from_bbox(b["north"], b["south"], b["east"], b["west"],
|
| 1015 |
walking=walking, include_service=service)
|
| 1016 |
|
| 1017 |
+
return jsonify(solve(G, walking=walking, coverage=d.get("coverage", "both"),
|
| 1018 |
start_lat=d.get("start_lat"), start_lon=d.get("start_lon")))
|
| 1019 |
except RouteError as exc:
|
| 1020 |
return jsonify({"error": str(exc)}), 400
|