Upload app.py
Browse files
app.py
CHANGED
|
@@ -2,11 +2,8 @@
|
|
| 2 |
"""
|
| 3 |
Route Em -- Hugging Face Space (Docker SDK).
|
| 4 |
|
| 5 |
-
Shortest closed route covering every road on BOTH sides
|
| 6 |
-
|
| 7 |
-
solved exactly via min-cost flow (provably optimal, not a heuristic).
|
| 8 |
-
|
| 9 |
-
Runs on 0.0.0.0:$PORT (HF sets PORT=7860).
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os
|
|
@@ -15,8 +12,8 @@ import traceback
|
|
| 15 |
import requests
|
| 16 |
from flask import Flask, jsonify, render_template_string, request
|
| 17 |
|
| 18 |
-
# HF Space containers only allow writes to /tmp
|
| 19 |
-
#
|
| 20 |
os.environ.setdefault("HOME", "/tmp")
|
| 21 |
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
|
| 22 |
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache")
|
|
@@ -37,6 +34,27 @@ class RouteError(Exception):
|
|
| 37 |
"""Something the user can fix -- shown in the UI as a friendly message."""
|
| 38 |
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
# ---------------------------------------------------------------- load
|
| 41 |
def graph_from_bbox(north, south, east, west, walking=False, include_service=False):
|
| 42 |
net = "walk" if walking else "drive"
|
|
@@ -279,7 +297,7 @@ def solve(G, walking=False, start_lat=None, start_lon=None):
|
|
| 279 |
used[(s["u"], s["v"])] += 1
|
| 280 |
missing = [(u, v) for u, v in R.edges() if used[(u, v)] < 1]
|
| 281 |
if missing:
|
| 282 |
-
raise RouteError(
|
| 283 |
|
| 284 |
return {
|
| 285 |
"stats": compute_stats(R, steps, repeats),
|
|
@@ -288,7 +306,7 @@ def solve(G, walking=False, start_lat=None, start_lon=None):
|
|
| 288 |
}
|
| 289 |
|
| 290 |
|
| 291 |
-
# Keep osmnx's HTTP cache in /tmp
|
| 292 |
ox.settings.cache_folder = "/tmp/osmnx_cache"
|
| 293 |
ox.settings.use_cache = True
|
| 294 |
ox.settings.log_console = False
|
|
@@ -306,47 +324,66 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 306 |
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
| 307 |
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
|
| 308 |
<style>
|
| 309 |
-
:root{--bg:#0f1115;--panel:#171a21;--line:#262b36;--txt:#e7eaf0;--dim:#98a1b3;--acc:#4f8cff;--ok:#2ecc71;--bad:#d7263d}
|
| 310 |
*{box-sizing:border-box}
|
| 311 |
-
body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--txt);height:100vh;display:flex;flex-direction:column}
|
| 312 |
-
header{padding:12px 18px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:16px}
|
| 313 |
-
h1{margin:0;font-size:16px;font-weight:650
|
| 314 |
.sub{color:var(--dim);font-size:12px}
|
| 315 |
-
main{flex:1;display:grid;grid-template-columns:
|
| 316 |
.pane{border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
|
| 317 |
.pane:last-child{border-right:0;border-left:1px solid var(--line);overflow-y:auto}
|
| 318 |
-
.hd{padding:10px 14px;font-size:11px;text-transform:uppercase;letter-spacing:.9px;color:var(--dim);border-bottom:1px solid var(--line)}
|
| 319 |
-
#drop{flex:1;margin:14px;border:2px dashed var(--line);border-radius:10px;display:flex;align-items:center;justify-content:center;text-align:center;color:var(--dim);cursor:pointer;overflow:hidden;
|
| 320 |
#drop:hover,#drop.hot{border-color:var(--acc);background:#4f8cff10}
|
| 321 |
#drop img{width:100%;height:100%;object-fit:contain}
|
| 322 |
#drop .ph{padding:24px}
|
| 323 |
#drop .ph b{color:var(--txt);display:block;margin-bottom:6px;font-size:15px}
|
| 324 |
#map{flex:1}
|
| 325 |
-
.ctl{padding:
|
| 326 |
-
input[type=text]{flex:1;min-width:
|
| 327 |
input[type=text]:focus{outline:0;border-color:var(--acc)}
|
| 328 |
button{background:var(--acc);color:#fff;border:0;padding:9px 15px;border-radius:7px;font-weight:600;cursor:pointer;font-size:13px}
|
| 329 |
button:hover{filter:brightness(1.12)}
|
| 330 |
-
button:disabled{opacity:.
|
| 331 |
button.sec{background:#252a35}
|
| 332 |
-
|
|
|
|
| 333 |
.msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
|
| 334 |
.msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
|
| 335 |
.msg.info{display:block;background:#4f8cff18;border:1px solid #4f8cff44;color:#bcd4ff}
|
| 336 |
-
.stat{padding:
|
| 337 |
.stat span{color:var(--dim);font-size:12px}
|
| 338 |
.stat b{font-size:15px;font-variant-numeric:tabular-nums}
|
| 339 |
.stat.big b{font-size:24px;color:var(--acc)}
|
| 340 |
.stat.good b{color:var(--ok)}
|
| 341 |
.stat.warn b{color:var(--bad)}
|
| 342 |
-
.street{padding:6px 14px;display:flex;justify-content:space-between;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028}
|
| 343 |
.street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
|
|
|
|
| 344 |
.empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
|
| 345 |
-
.
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
.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}
|
| 348 |
@keyframes s{to{transform:rotate(360deg)}}
|
| 349 |
-
.
|
|
|
|
| 350 |
</style>
|
| 351 |
</head>
|
| 352 |
<body>
|
|
@@ -363,32 +400,56 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 363 |
<div class="ph">
|
| 364 |
<b>Drag your map screenshot here</b>
|
| 365 |
Or click to choose a file.<br>
|
| 366 |
-
It stays on your machine — it's your
|
| 367 |
</div>
|
| 368 |
<input type="file" id="file" accept="image/*" hidden>
|
| 369 |
</div>
|
| 370 |
</div>
|
| 371 |
|
| 372 |
<div class="pane">
|
| 373 |
-
<div class="hd">2 Find the area, then
|
| 374 |
<div class="ctl">
|
| 375 |
<input type="text" id="q" placeholder="ZIP code, address, or neighborhood...">
|
| 376 |
<button id="find" class="sec">Find</button>
|
| 377 |
</div>
|
| 378 |
<div class="ctl">
|
|
|
|
| 379 |
<button id="box" class="sec">Draw box</button>
|
| 380 |
<button id="clear" class="sec">Clear</button>
|
| 381 |
-
<label class="ck"><input type="checkbox" id="walking"> Walking
|
| 382 |
-
<label class="ck"><input type="checkbox" id="svc">
|
| 383 |
<button id="solve" disabled>Solve route</button>
|
| 384 |
</div>
|
| 385 |
<div class="mapwrap">
|
| 386 |
<div id="map"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
<div class="legend" id="legend">
|
| 388 |
<span class="sw" style="background:#2860e6"></span>route start<br>
|
| 389 |
<span class="sw" style="background:#e6c85a"></span>route end<br>
|
| 390 |
<span class="sw" style="background:#d7263d"></span>deadhead (repeat pass)<br>
|
| 391 |
-
<span style="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
</div>
|
| 393 |
</div>
|
| 394 |
</div>
|
|
@@ -398,7 +459,7 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 398 |
<div id="msg" class="msg"></div>
|
| 399 |
<div id="out">
|
| 400 |
<div class="empty">
|
| 401 |
-
Drop a screenshot, find the area,<br>
|
| 402 |
</div>
|
| 403 |
</div>
|
| 404 |
</div>
|
|
@@ -407,45 +468,68 @@ PAGE = r'''<!DOCTYPE html>
|
|
| 407 |
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
| 408 |
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
|
| 409 |
<script>
|
| 410 |
-
//
|
| 411 |
const drop = document.getElementById('drop'), file = document.getElementById('file');
|
| 412 |
drop.onclick = () => file.click();
|
| 413 |
-
file.onchange = e => e.target.files[0] &&
|
| 414 |
['dragenter','dragover'].forEach(t => drop.addEventListener(t, e => {
|
| 415 |
-
e.preventDefault(); drop.classList.add('hot');
|
| 416 |
-
}));
|
| 417 |
['dragleave','drop'].forEach(t => drop.addEventListener(t, e => {
|
| 418 |
-
e.preventDefault(); drop.classList.remove('hot');
|
| 419 |
-
}));
|
| 420 |
drop.addEventListener('drop', e => {
|
| 421 |
const f = e.dataTransfer.files[0];
|
| 422 |
-
if (f && f.type.startsWith('image/'))
|
| 423 |
else msg('That file is not an image.', 'err');
|
| 424 |
});
|
| 425 |
-
function
|
| 426 |
const img = document.createElement('img');
|
| 427 |
img.src = URL.createObjectURL(f);
|
| 428 |
drop.innerHTML = ''; drop.appendChild(img);
|
| 429 |
}
|
| 430 |
|
| 431 |
-
//
|
| 432 |
const map = L.map('map').setView([39.83, -98.58], 4);
|
| 433 |
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
|
| 434 |
{maxZoom: 19, attribution: '© OpenStreetMap, © CARTO'}).addTo(map);
|
| 435 |
|
| 436 |
const drawn = new L.FeatureGroup().addTo(map);
|
| 437 |
-
let routeLayer = null,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
map.on(L.Draw.Event.CREATED, e => {
|
| 443 |
drawn.clearLayers();
|
| 444 |
drawn.addLayer(e.layer);
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
document.getElementById('solve').disabled = false;
|
| 448 |
-
msg('
|
| 449 |
});
|
| 450 |
|
| 451 |
map.on('click', e => {
|
|
@@ -455,18 +539,20 @@ map.on('click', e => {
|
|
| 455 |
});
|
| 456 |
|
| 457 |
document.getElementById('clear').onclick = () => {
|
|
|
|
| 458 |
drawn.clearLayers();
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
bounds = null;
|
| 462 |
document.getElementById('solve').disabled = true;
|
|
|
|
|
|
|
| 463 |
document.getElementById('legend').style.display = 'none';
|
| 464 |
document.getElementById('out').innerHTML =
|
| 465 |
-
'<div class="empty">
|
| 466 |
msg('');
|
| 467 |
};
|
| 468 |
|
| 469 |
-
//
|
| 470 |
const q = document.getElementById('q');
|
| 471 |
document.getElementById('find').onclick = find;
|
| 472 |
q.onkeydown = e => { if (e.key === 'Enter') find(); };
|
|
@@ -481,24 +567,23 @@ async function find(){
|
|
| 481 |
if (!r.ok) return msg(d.error, 'err');
|
| 482 |
map.fitBounds([[d.bounds.south, d.bounds.west], [d.bounds.north, d.bounds.east]]);
|
| 483 |
if (map.getZoom() > 16) map.setZoom(16);
|
| 484 |
-
msg('Found ' + d.label + '. Now
|
| 485 |
} catch (err) { msg('Lookup failed: ' + err, 'err'); }
|
| 486 |
}
|
| 487 |
|
| 488 |
-
//
|
| 489 |
const solveBtn = document.getElementById('solve');
|
| 490 |
solveBtn.onclick = async () => {
|
| 491 |
-
if (!
|
| 492 |
const orig = solveBtn.innerHTML;
|
| 493 |
solveBtn.disabled = true;
|
| 494 |
solveBtn.innerHTML = '<span class="spin"></span>Solving...';
|
| 495 |
msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
|
| 496 |
|
| 497 |
-
const body = {
|
| 498 |
-
bounds: bounds,
|
| 499 |
walking: document.getElementById('walking').checked,
|
| 500 |
include_service: document.getElementById('svc').checked
|
| 501 |
-
};
|
| 502 |
if (startMarker) {
|
| 503 |
body.start_lat = startMarker.getLatLng().lat;
|
| 504 |
body.start_lon = startMarker.getLatLng().lng;
|
|
@@ -506,9 +591,7 @@ solveBtn.onclick = async () => {
|
|
| 506 |
|
| 507 |
try {
|
| 508 |
const r = await fetch('/solve', {
|
| 509 |
-
method:
|
| 510 |
-
headers: {'Content-Type': 'application/json'},
|
| 511 |
-
body: JSON.stringify(body)
|
| 512 |
});
|
| 513 |
const d = await r.json();
|
| 514 |
if (!r.ok) { msg(d.error, 'err'); return; }
|
|
@@ -522,20 +605,27 @@ solveBtn.onclick = async () => {
|
|
| 522 |
}
|
| 523 |
};
|
| 524 |
|
| 525 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
function render(d){
|
| 527 |
-
|
| 528 |
-
|
| 529 |
|
|
|
|
|
|
|
|
|
|
| 530 |
routeLayer = L.geoJSON(d.geojson, {
|
| 531 |
style: f => {
|
| 532 |
const p = f.properties;
|
| 533 |
-
if (p.deadhead)
|
| 534 |
-
return {color:'#d7263d', weight:3, opacity:.95, dashArray:'6,8'};
|
| 535 |
const t = (p.order - 1) / Math.max(n - 1, 1);
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
return {color:c, weight:5, opacity:.85};
|
| 539 |
},
|
| 540 |
onEachFeature: (f, l) => {
|
| 541 |
const p = f.properties;
|
|
@@ -543,12 +633,202 @@ function render(d){
|
|
| 543 |
(p.deadhead ? ' (deadhead, no delivery)' : ''));
|
| 544 |
}
|
| 545 |
}).addTo(map);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
map.fitBounds(routeLayer.getBounds(), {padding:[24,24]});
|
| 547 |
document.getElementById('legend').style.display = 'block';
|
|
|
|
|
|
|
| 548 |
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
|
| 553 |
let h = '';
|
| 554 |
h += row('Total route', s.total_mi.toFixed(2) + ' mi', 'big');
|
|
@@ -570,8 +850,8 @@ function render(d){
|
|
| 570 |
});
|
| 571 |
|
| 572 |
h += '<div class="hd" style="margin-top:8px">Directions</div>';
|
| 573 |
-
|
| 574 |
-
h += '<div class="street"><span>' + x.step + '. ' +
|
| 575 |
(x.deadhead ? '<i style="color:#d7263d">(deadhead)</i> ' : '') +
|
| 576 |
x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
|
| 577 |
});
|
|
@@ -592,7 +872,7 @@ function msg(t, cls){
|
|
| 592 |
|
| 593 |
# ============================================================ web app
|
| 594 |
app = Flask(__name__)
|
| 595 |
-
UA = {"User-Agent": "
|
| 596 |
|
| 597 |
|
| 598 |
@app.route("/")
|
|
@@ -614,8 +894,7 @@ def geocode():
|
|
| 614 |
r = requests.get(
|
| 615 |
"https://nominatim.openstreetmap.org/search",
|
| 616 |
params={"q": q, "format": "json", "limit": 1, "countrycodes": "us"},
|
| 617 |
-
headers=UA,
|
| 618 |
-
timeout=20,
|
| 619 |
)
|
| 620 |
r.raise_for_status()
|
| 621 |
hits = r.json()
|
|
@@ -636,27 +915,24 @@ def geocode():
|
|
| 636 |
|
| 637 |
@app.route("/solve", methods=["POST"])
|
| 638 |
def solve_route():
|
|
|
|
| 639 |
d = request.get_json(force=True)
|
|
|
|
|
|
|
| 640 |
try:
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
)
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
return jsonify(solve(
|
| 655 |
-
G,
|
| 656 |
-
walking=bool(d.get("walking")),
|
| 657 |
-
start_lat=d.get("start_lat"),
|
| 658 |
-
start_lon=d.get("start_lon"),
|
| 659 |
-
))
|
| 660 |
except RouteError as exc:
|
| 661 |
return jsonify({"error": str(exc)}), 400
|
| 662 |
except Exception as exc:
|
|
@@ -664,14 +940,14 @@ def solve_route():
|
|
| 664 |
return jsonify({"error": "Unexpected error: %s" % exc}), 500
|
| 665 |
|
| 666 |
|
| 667 |
-
def
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
|
|
|
| 673 |
|
| 674 |
|
| 675 |
if __name__ == "__main__":
|
| 676 |
-
|
| 677 |
-
app.run(host="0.0.0.0", port=port, debug=False)
|
|
|
|
| 2 |
"""
|
| 3 |
Route Em -- Hugging Face Space (Docker SDK).
|
| 4 |
|
| 5 |
+
Shortest closed route covering every road on BOTH sides. Directed Chinese Postman,
|
| 6 |
+
solved exactly by min-cost flow. Serves on 0.0.0.0:$PORT (HF sets PORT=7860).
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
|
|
|
| 12 |
import requests
|
| 13 |
from flask import Flask, jsonify, render_template_string, request
|
| 14 |
|
| 15 |
+
# HF Space containers only allow writes to /tmp. Set this BEFORE osmnx imports,
|
| 16 |
+
# or the app dies on boot with a permission error.
|
| 17 |
os.environ.setdefault("HOME", "/tmp")
|
| 18 |
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
|
| 19 |
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache")
|
|
|
|
| 34 |
"""Something the user can fix -- shown in the UI as a friendly message."""
|
| 35 |
|
| 36 |
|
| 37 |
+
# ---------------------------------------------------------------- area guards
|
| 38 |
+
def bbox_area_sq_mi(b):
|
| 39 |
+
import math
|
| 40 |
+
|
| 41 |
+
mid = math.radians((b["north"] + b["south"]) / 2)
|
| 42 |
+
h = (b["north"] - b["south"]) * 69.0
|
| 43 |
+
w = (b["east"] - b["west"]) * 69.0 * math.cos(mid)
|
| 44 |
+
return abs(h * w)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def polygon_area_sq_mi(geojson_polygon):
|
| 48 |
+
"""Rough but adequate: scale degrees to miles at the polygon's latitude."""
|
| 49 |
+
import math
|
| 50 |
+
|
| 51 |
+
from shapely.geometry import shape
|
| 52 |
+
|
| 53 |
+
poly = shape(geojson_polygon)
|
| 54 |
+
mid = math.radians(poly.centroid.y)
|
| 55 |
+
return abs(poly.area) * 69.0 * (69.0 * math.cos(mid))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
# ---------------------------------------------------------------- load
|
| 59 |
def graph_from_bbox(north, south, east, west, walking=False, include_service=False):
|
| 60 |
net = "walk" if walking else "drive"
|
|
|
|
| 297 |
used[(s["u"], s["v"])] += 1
|
| 298 |
missing = [(u, v) for u, v in R.edges() if used[(u, v)] < 1]
|
| 299 |
if missing:
|
| 300 |
+
raise RouteError("Internal: %d required passes missing from route." % len(missing))
|
| 301 |
|
| 302 |
return {
|
| 303 |
"stats": compute_stats(R, steps, repeats),
|
|
|
|
| 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
|
| 312 |
ox.settings.log_console = False
|
|
|
|
| 324 |
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
| 325 |
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
|
| 326 |
<style>
|
| 327 |
+
:root{--bg:#0f1115;--panel:#171a21;--line:#262b36;--txt:#e7eaf0;--dim:#98a1b3;--acc:#4f8cff;--ok:#2ecc71;--bad:#d7263d;--warm:#e6c85a}
|
| 328 |
*{box-sizing:border-box}
|
| 329 |
+
body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--txt);height:100vh;display:flex;flex-direction:column;overflow:hidden}
|
| 330 |
+
header{padding:12px 18px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:16px;flex-shrink:0}
|
| 331 |
+
h1{margin:0;font-size:16px;font-weight:650}
|
| 332 |
.sub{color:var(--dim);font-size:12px}
|
| 333 |
+
main{flex:1;display:grid;grid-template-columns:320px 1fr 330px;min-height:0}
|
| 334 |
.pane{border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
|
| 335 |
.pane:last-child{border-right:0;border-left:1px solid var(--line);overflow-y:auto}
|
| 336 |
+
.hd{padding:10px 14px;font-size:11px;text-transform:uppercase;letter-spacing:.9px;color:var(--dim);border-bottom:1px solid var(--line);flex-shrink:0}
|
| 337 |
+
#drop{flex:1;margin:14px;border:2px dashed var(--line);border-radius:10px;display:flex;align-items:center;justify-content:center;text-align:center;color:var(--dim);cursor:pointer;overflow:hidden;transition:.15s}
|
| 338 |
#drop:hover,#drop.hot{border-color:var(--acc);background:#4f8cff10}
|
| 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}
|
| 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)}
|
| 346 |
button{background:var(--acc);color:#fff;border:0;padding:9px 15px;border-radius:7px;font-weight:600;cursor:pointer;font-size:13px}
|
| 347 |
button:hover{filter:brightness(1.12)}
|
| 348 |
+
button:disabled{opacity:.4;cursor:not-allowed}
|
| 349 |
button.sec{background:#252a35}
|
| 350 |
+
button.sec.on{background:var(--acc)}
|
| 351 |
+
label.ck{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:12px;cursor:pointer;white-space:nowrap}
|
| 352 |
.msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
|
| 353 |
.msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
|
| 354 |
.msg.info{display:block;background:#4f8cff18;border:1px solid #4f8cff44;color:#bcd4ff}
|
| 355 |
+
.stat{padding:10px 14px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:baseline;gap:10px}
|
| 356 |
.stat span{color:var(--dim);font-size:12px}
|
| 357 |
.stat b{font-size:15px;font-variant-numeric:tabular-nums}
|
| 358 |
.stat.big b{font-size:24px;color:var(--acc)}
|
| 359 |
.stat.good b{color:var(--ok)}
|
| 360 |
.stat.warn b{color:var(--bad)}
|
| 361 |
+
.street{padding:6px 14px;display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028}
|
| 362 |
.street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
|
| 363 |
+
.street.now{background:#4f8cff26;color:var(--txt);border-left:3px solid var(--acc)}
|
| 364 |
.empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
|
| 365 |
+
.mapwrap{position:relative;flex:1;display:flex;min-height:0}
|
| 366 |
+
|
| 367 |
+
/* ---- playback bar ---- */
|
| 368 |
+
#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}
|
| 369 |
+
#play.on{display:flex}
|
| 370 |
+
#scrub{flex:1;min-width:160px;-webkit-appearance:none;appearance:none;height:5px;border-radius:3px;background:#2b3342;outline:0;cursor:pointer}
|
| 371 |
+
#scrub::-webkit-slider-thumb{-webkit-appearance:none;width:15px;height:15px;border-radius:50%;background:var(--acc);cursor:pointer;border:2px solid #0f1115}
|
| 372 |
+
#scrub::-moz-range-thumb{width:15px;height:15px;border-radius:50%;background:var(--acc);border:2px solid #0f1115;cursor:pointer}
|
| 373 |
+
#pp{width:42px;padding:9px 0;text-align:center}
|
| 374 |
+
select{background:#252a35;color:var(--txt);border:1px solid var(--line);border-radius:7px;padding:8px;font-size:12px;cursor:pointer}
|
| 375 |
+
.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}
|
| 376 |
+
.hud.on{display:block}
|
| 377 |
+
.hud .now{font-size:15px;font-weight:650;margin-bottom:3px}
|
| 378 |
+
.hud .meta{font-size:11px;color:var(--dim);font-variant-numeric:tabular-nums}
|
| 379 |
+
.hud .bar{height:4px;background:#2b3342;border-radius:3px;margin-top:7px;overflow:hidden}
|
| 380 |
+
.hud .bar i{display:block;height:100%;background:var(--acc);width:0}
|
| 381 |
+
.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}
|
| 382 |
+
.sw{display:inline-block;width:16px;height:3px;vertical-align:middle;margin-right:6px;border-radius:2px}
|
| 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,.65))}
|
| 386 |
+
.arrow{color:#fff;opacity:.9;pointer-events:none}
|
| 387 |
</style>
|
| 388 |
</head>
|
| 389 |
<body>
|
|
|
|
| 400 |
<div class="ph">
|
| 401 |
<b>Drag your map screenshot here</b>
|
| 402 |
Or click to choose a file.<br>
|
| 403 |
+
It stays on your machine — it's your reference for matching the map.
|
| 404 |
</div>
|
| 405 |
<input type="file" id="file" accept="image/*" hidden>
|
| 406 |
</div>
|
| 407 |
</div>
|
| 408 |
|
| 409 |
<div class="pane">
|
| 410 |
+
<div class="hd">2 Find the area, then outline it</div>
|
| 411 |
<div class="ctl">
|
| 412 |
<input type="text" id="q" placeholder="ZIP code, address, or neighborhood...">
|
| 413 |
<button id="find" class="sec">Find</button>
|
| 414 |
</div>
|
| 415 |
<div class="ctl">
|
| 416 |
+
<button id="poly" class="sec">Draw shape</button>
|
| 417 |
<button id="box" class="sec">Draw box</button>
|
| 418 |
<button id="clear" class="sec">Clear</button>
|
| 419 |
+
<label class="ck"><input type="checkbox" id="walking"> Walking</label>
|
| 420 |
+
<label class="ck"><input type="checkbox" id="svc"> Alleys</label>
|
| 421 |
<button id="solve" disabled>Solve route</button>
|
| 422 |
</div>
|
| 423 |
<div class="mapwrap">
|
| 424 |
<div id="map"></div>
|
| 425 |
+
|
| 426 |
+
<div class="hud" id="hud">
|
| 427 |
+
<div class="now" id="hudStreet">—</div>
|
| 428 |
+
<div class="meta" id="hudMeta">—</div>
|
| 429 |
+
<div class="bar"><i id="hudBar"></i></div>
|
| 430 |
+
</div>
|
| 431 |
+
|
| 432 |
<div class="legend" id="legend">
|
| 433 |
<span class="sw" style="background:#2860e6"></span>route start<br>
|
| 434 |
<span class="sw" style="background:#e6c85a"></span>route end<br>
|
| 435 |
<span class="sw" style="background:#d7263d"></span>deadhead (repeat pass)<br>
|
| 436 |
+
<span class="sw" style="background:#2ecc71"></span>already driven<br>
|
| 437 |
+
<span style="color:#98a1b3">Arrows show direction of travel.</span>
|
| 438 |
+
</div>
|
| 439 |
+
|
| 440 |
+
<div id="play">
|
| 441 |
+
<button id="pp">▶</button>
|
| 442 |
+
<button id="restart" class="sec">↺</button>
|
| 443 |
+
<input type="range" id="scrub" min="0" max="1000" value="0">
|
| 444 |
+
<select id="speed">
|
| 445 |
+
<option value="0.5">0.5×</option>
|
| 446 |
+
<option value="1" selected>1×</option>
|
| 447 |
+
<option value="2">2×</option>
|
| 448 |
+
<option value="4">4×</option>
|
| 449 |
+
<option value="8">8×</option>
|
| 450 |
+
</select>
|
| 451 |
+
<label class="ck"><input type="checkbox" id="follow" checked> Follow</label>
|
| 452 |
+
<label class="ck"><input type="checkbox" id="arrowsOn" checked> Arrows</label>
|
| 453 |
</div>
|
| 454 |
</div>
|
| 455 |
</div>
|
|
|
|
| 459 |
<div id="msg" class="msg"></div>
|
| 460 |
<div id="out">
|
| 461 |
<div class="empty">
|
| 462 |
+
Drop a screenshot, find the area,<br>outline it, and hit <b>Solve route</b>.
|
| 463 |
</div>
|
| 464 |
</div>
|
| 465 |
</div>
|
|
|
|
| 468 |
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
| 469 |
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
|
| 470 |
<script>
|
| 471 |
+
// ================= screenshot drop (reference only; never uploaded) =================
|
| 472 |
const drop = document.getElementById('drop'), file = document.getElementById('file');
|
| 473 |
drop.onclick = () => file.click();
|
| 474 |
+
file.onchange = e => e.target.files[0] && showShot(e.target.files[0]);
|
| 475 |
['dragenter','dragover'].forEach(t => drop.addEventListener(t, e => {
|
| 476 |
+
e.preventDefault(); drop.classList.add('hot'); }));
|
|
|
|
| 477 |
['dragleave','drop'].forEach(t => drop.addEventListener(t, e => {
|
| 478 |
+
e.preventDefault(); drop.classList.remove('hot'); }));
|
|
|
|
| 479 |
drop.addEventListener('drop', e => {
|
| 480 |
const f = e.dataTransfer.files[0];
|
| 481 |
+
if (f && f.type.startsWith('image/')) showShot(f);
|
| 482 |
else msg('That file is not an image.', 'err');
|
| 483 |
});
|
| 484 |
+
function showShot(f){
|
| 485 |
const img = document.createElement('img');
|
| 486 |
img.src = URL.createObjectURL(f);
|
| 487 |
drop.innerHTML = ''; drop.appendChild(img);
|
| 488 |
}
|
| 489 |
|
| 490 |
+
// ================= map =================
|
| 491 |
const map = L.map('map').setView([39.83, -98.58], 4);
|
| 492 |
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
|
| 493 |
{maxZoom: 19, attribution: '© OpenStreetMap, © CARTO'}).addTo(map);
|
| 494 |
|
| 495 |
const drawn = new L.FeatureGroup().addTo(map);
|
| 496 |
+
let routeLayer = null, trailLine = null, arrowLayer = null,
|
| 497 |
+
truck = null, startMarker = null, shape = null;
|
| 498 |
+
|
| 499 |
+
const SHAPE_STYLE = {color:'#4f8cff', weight:2, fillOpacity:.06};
|
| 500 |
+
const boxTool = new L.Draw.Rectangle(map, {shapeOptions: SHAPE_STYLE});
|
| 501 |
+
const polyTool = new L.Draw.Polygon(map, {
|
| 502 |
+
shapeOptions: SHAPE_STYLE,
|
| 503 |
+
allowIntersection: false,
|
| 504 |
+
showArea: false,
|
| 505 |
+
drawError: {color:'#d7263d', message:'Edges cannot cross'}
|
| 506 |
+
});
|
| 507 |
|
| 508 |
+
document.getElementById('box').onclick = () => {
|
| 509 |
+
polyTool.disable(); drawn.clearLayers(); boxTool.enable();
|
| 510 |
+
msg('Drag a rectangle around the neighborhood.', 'info');
|
| 511 |
+
};
|
| 512 |
+
document.getElementById('poly').onclick = () => {
|
| 513 |
+
boxTool.disable(); drawn.clearLayers(); polyTool.enable();
|
| 514 |
+
msg('Click each corner of your route area. Click the first point again to close it.', 'info');
|
| 515 |
+
};
|
| 516 |
|
| 517 |
map.on(L.Draw.Event.CREATED, e => {
|
| 518 |
drawn.clearLayers();
|
| 519 |
drawn.addLayer(e.layer);
|
| 520 |
+
|
| 521 |
+
if (e.layerType === 'rectangle') {
|
| 522 |
+
const b = e.layer.getBounds();
|
| 523 |
+
shape = {kind:'bbox', bounds:{
|
| 524 |
+
north:b.getNorth(), south:b.getSouth(), east:b.getEast(), west:b.getWest()}};
|
| 525 |
+
} else {
|
| 526 |
+
// GeoJSON ring, [lng,lat], explicitly closed
|
| 527 |
+
const ring = e.layer.getLatLngs()[0].map(p => [p.lng, p.lat]);
|
| 528 |
+
ring.push(ring[0]);
|
| 529 |
+
shape = {kind:'polygon', polygon:{type:'Polygon', coordinates:[ring]}};
|
| 530 |
+
}
|
| 531 |
document.getElementById('solve').disabled = false;
|
| 532 |
+
msg('Area set. Shift-click the map to set where you start & end. Then Solve.', 'info');
|
| 533 |
});
|
| 534 |
|
| 535 |
map.on('click', e => {
|
|
|
|
| 539 |
});
|
| 540 |
|
| 541 |
document.getElementById('clear').onclick = () => {
|
| 542 |
+
stop();
|
| 543 |
drawn.clearLayers();
|
| 544 |
+
[routeLayer, trailLine, arrowLayer, truck, startMarker].forEach(l => l && map.removeLayer(l));
|
| 545 |
+
routeLayer = trailLine = arrowLayer = truck = startMarker = shape = null;
|
|
|
|
| 546 |
document.getElementById('solve').disabled = true;
|
| 547 |
+
document.getElementById('play').classList.remove('on');
|
| 548 |
+
document.getElementById('hud').classList.remove('on');
|
| 549 |
document.getElementById('legend').style.display = 'none';
|
| 550 |
document.getElementById('out').innerHTML =
|
| 551 |
+
'<div class="empty">Outline an area and hit <b>Solve route</b>.</div>';
|
| 552 |
msg('');
|
| 553 |
};
|
| 554 |
|
| 555 |
+
// ================= geocode =================
|
| 556 |
const q = document.getElementById('q');
|
| 557 |
document.getElementById('find').onclick = find;
|
| 558 |
q.onkeydown = e => { if (e.key === 'Enter') find(); };
|
|
|
|
| 567 |
if (!r.ok) return msg(d.error, 'err');
|
| 568 |
map.fitBounds([[d.bounds.south, d.bounds.west], [d.bounds.north, d.bounds.east]]);
|
| 569 |
if (map.getZoom() > 16) map.setZoom(16);
|
| 570 |
+
msg('Found ' + d.label + '. Now <b>Draw shape</b> (any outline) or <b>Draw box</b>.', 'info');
|
| 571 |
} catch (err) { msg('Lookup failed: ' + err, 'err'); }
|
| 572 |
}
|
| 573 |
|
| 574 |
+
// ================= solve =================
|
| 575 |
const solveBtn = document.getElementById('solve');
|
| 576 |
solveBtn.onclick = async () => {
|
| 577 |
+
if (!shape) return;
|
| 578 |
const orig = solveBtn.innerHTML;
|
| 579 |
solveBtn.disabled = true;
|
| 580 |
solveBtn.innerHTML = '<span class="spin"></span>Solving...';
|
| 581 |
msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
|
| 582 |
|
| 583 |
+
const body = Object.assign({}, shape, {
|
|
|
|
| 584 |
walking: document.getElementById('walking').checked,
|
| 585 |
include_service: document.getElementById('svc').checked
|
| 586 |
+
});
|
| 587 |
if (startMarker) {
|
| 588 |
body.start_lat = startMarker.getLatLng().lat;
|
| 589 |
body.start_lon = startMarker.getLatLng().lng;
|
|
|
|
| 591 |
|
| 592 |
try {
|
| 593 |
const r = await fetch('/solve', {
|
| 594 |
+
method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)
|
|
|
|
|
|
|
| 595 |
});
|
| 596 |
const d = await r.json();
|
| 597 |
if (!r.ok) { msg(d.error, 'err'); return; }
|
|
|
|
| 605 |
}
|
| 606 |
};
|
| 607 |
|
| 608 |
+
|
| 609 |
+
// ================= route rendering =================
|
| 610 |
+
let PATH = []; // [{a,b,len(m),cum(m),name,deadhead,order}]
|
| 611 |
+
let TOTAL_M = 0; // route length, meters
|
| 612 |
+
let DRIVE_MIN = 0; // estimated real-world minutes
|
| 613 |
+
let STEPS = []; // collapsed turn-by-turn
|
| 614 |
+
|
| 615 |
function render(d){
|
| 616 |
+
stop();
|
| 617 |
+
[routeLayer, trailLine, arrowLayer, truck].forEach(l => l && map.removeLayer(l));
|
| 618 |
|
| 619 |
+
const feats = d.geojson.features, n = feats.length;
|
| 620 |
+
|
| 621 |
+
// ---- base route, colored by progression
|
| 622 |
routeLayer = L.geoJSON(d.geojson, {
|
| 623 |
style: f => {
|
| 624 |
const p = f.properties;
|
| 625 |
+
if (p.deadhead) return {color:'#d7263d', weight:3.5, opacity:.9, dashArray:'6,8'};
|
|
|
|
| 626 |
const t = (p.order - 1) / Math.max(n - 1, 1);
|
| 627 |
+
return {color:'rgb(' + Math.round(40+200*t) + ',' + Math.round(90+100*t) + ',' +
|
| 628 |
+
Math.round(230-180*t) + ')', weight:5, opacity:.8};
|
|
|
|
| 629 |
},
|
| 630 |
onEachFeature: (f, l) => {
|
| 631 |
const p = f.properties;
|
|
|
|
| 633 |
(p.deadhead ? ' (deadhead, no delivery)' : ''));
|
| 634 |
}
|
| 635 |
}).addTo(map);
|
| 636 |
+
|
| 637 |
+
// ---- drivable path with cumulative distances
|
| 638 |
+
PATH = []; TOTAL_M = 0;
|
| 639 |
+
feats.forEach(f => {
|
| 640 |
+
const c = f.geometry.coordinates;
|
| 641 |
+
const a = L.latLng(c[0][1], c[0][0]), b = L.latLng(c[1][1], c[1][0]);
|
| 642 |
+
const len = map.distance(a, b);
|
| 643 |
+
PATH.push({a, b, len, cum: TOTAL_M, name: f.properties.name,
|
| 644 |
+
deadhead: f.properties.deadhead, order: f.properties.order});
|
| 645 |
+
TOTAL_M += len;
|
| 646 |
+
});
|
| 647 |
+
|
| 648 |
+
DRIVE_MIN = d.stats.drive_min;
|
| 649 |
+
STEPS = d.directions;
|
| 650 |
+
|
| 651 |
+
buildArrows();
|
| 652 |
+
|
| 653 |
+
trailLine = L.polyline([], {color:'#2ecc71', weight:7, opacity:.95}).addTo(map);
|
| 654 |
+
truck = L.marker(PATH[0].a, {icon: truckIcon(0), zIndexOffset: 1000,
|
| 655 |
+
interactive: false}).addTo(map);
|
| 656 |
+
|
| 657 |
map.fitBounds(routeLayer.getBounds(), {padding:[24,24]});
|
| 658 |
document.getElementById('legend').style.display = 'block';
|
| 659 |
+
document.getElementById('play').classList.add('on');
|
| 660 |
+
document.getElementById('hud').classList.add('on');
|
| 661 |
|
| 662 |
+
renderStats(d.stats);
|
| 663 |
+
seek(0);
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
// ---- direction arrows, rotated to the way you drive
|
| 667 |
+
function buildArrows(){
|
| 668 |
+
if (arrowLayer) map.removeLayer(arrowLayer);
|
| 669 |
+
arrowLayer = L.layerGroup();
|
| 670 |
+
|
| 671 |
+
const stride = Math.max(1, Math.ceil(PATH.length / 400)); // cap the marker count
|
| 672 |
+
PATH.forEach((s, i) => {
|
| 673 |
+
if (i % stride) return;
|
| 674 |
+
if (s.len < 12) return; // skip tiny stubs
|
| 675 |
+
const mid = L.latLng((s.a.lat + s.b.lat)/2, (s.a.lng + s.b.lng)/2);
|
| 676 |
+
L.marker(mid, {
|
| 677 |
+
interactive: false,
|
| 678 |
+
icon: L.divIcon({
|
| 679 |
+
className: '',
|
| 680 |
+
iconSize: [14, 14],
|
| 681 |
+
iconAnchor: [7, 7],
|
| 682 |
+
html: '<div class="arrow" style="transform:rotate(' + bearing(s.a, s.b) + 'deg)">' +
|
| 683 |
+
'<svg width="14" height="14" viewBox="0 0 14 14">' +
|
| 684 |
+
'<path d="M7 1 L11 11 L7 8.6 L3 11 Z" fill="' +
|
| 685 |
+
(s.deadhead ? '#ff8a97' : '#ffffff') + '" stroke="#0f1115" stroke-width="1"/>' +
|
| 686 |
+
'</svg></div>'
|
| 687 |
+
})
|
| 688 |
+
}).addTo(arrowLayer);
|
| 689 |
+
});
|
| 690 |
+
if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
document.getElementById('arrowsOn').onchange = e => {
|
| 694 |
+
if (!arrowLayer) return;
|
| 695 |
+
e.target.checked ? arrowLayer.addTo(map) : map.removeLayer(arrowLayer);
|
| 696 |
+
};
|
| 697 |
+
|
| 698 |
+
// compass bearing, 0 = north
|
| 699 |
+
function bearing(a, b){
|
| 700 |
+
const r = Math.PI/180;
|
| 701 |
+
const y = Math.sin((b.lng-a.lng)*r) * Math.cos(b.lat*r);
|
| 702 |
+
const x = Math.cos(a.lat*r)*Math.sin(b.lat*r) -
|
| 703 |
+
Math.sin(a.lat*r)*Math.cos(b.lat*r)*Math.cos((b.lng-a.lng)*r);
|
| 704 |
+
return (Math.atan2(y, x) * 180/Math.PI + 360) % 360;
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
function truckIcon(deg){
|
| 708 |
+
return L.divIcon({
|
| 709 |
+
className: '',
|
| 710 |
+
iconSize: [30, 30],
|
| 711 |
+
iconAnchor: [15, 15],
|
| 712 |
+
html: '<div class="truck" style="transform:rotate(' + deg + 'deg)">' +
|
| 713 |
+
'<svg width="30" height="30" viewBox="0 0 30 30">' +
|
| 714 |
+
'<circle cx="15" cy="15" r="13" fill="#0f1115" opacity=".55"/>' +
|
| 715 |
+
'<g transform="translate(15,15)">' +
|
| 716 |
+
'<rect x="-6" y="-8" width="12" height="16" rx="2.5" fill="#4f8cff"/>' +
|
| 717 |
+
'<rect x="-6" y="-8" width="12" height="5.5" rx="2" fill="#dfe8ff"/>' +
|
| 718 |
+
'<rect x="-7.5" y="-2" width="3" height="6" rx="1" fill="#2b3342"/>' +
|
| 719 |
+
'<rect x="4.5" y="-2" width="3" height="6" rx="1" fill="#2b3342"/>' +
|
| 720 |
+
'<path d="M0 -12 L4 -8 L-4 -8 Z" fill="#e6c85a"/>' +
|
| 721 |
+
'</g>' +
|
| 722 |
+
'</svg></div>'
|
| 723 |
+
});
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
// ================= animation =================
|
| 727 |
+
let pos = 0; // meters travelled
|
| 728 |
+
let playing = false;
|
| 729 |
+
let raf = null, last = 0;
|
| 730 |
+
|
| 731 |
+
const pp = document.getElementById('pp');
|
| 732 |
+
const scrub = document.getElementById('scrub');
|
| 733 |
+
const speedSel = document.getElementById('speed');
|
| 734 |
+
const followCk = document.getElementById('follow');
|
| 735 |
+
|
| 736 |
+
pp.onclick = () => playing ? stop() : play();
|
| 737 |
+
document.getElementById('restart').onclick = () => { seek(0); play(); };
|
| 738 |
+
scrub.oninput = () => { stop(); seek(TOTAL_M * (scrub.value / 1000)); };
|
| 739 |
+
|
| 740 |
+
function play(){
|
| 741 |
+
if (!PATH.length) return;
|
| 742 |
+
if (pos >= TOTAL_M - 0.5) pos = 0;
|
| 743 |
+
playing = true;
|
| 744 |
+
pp.innerHTML = '❙❙';
|
| 745 |
+
last = performance.now();
|
| 746 |
+
raf = requestAnimationFrame(tick);
|
| 747 |
+
}
|
| 748 |
+
|
| 749 |
+
function stop(){
|
| 750 |
+
playing = false;
|
| 751 |
+
pp.innerHTML = '▶';
|
| 752 |
+
if (raf) cancelAnimationFrame(raf);
|
| 753 |
+
raf = null;
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
function tick(now){
|
| 757 |
+
if (!playing) return;
|
| 758 |
+
const dt = Math.min((now - last) / 1000, 0.1); // tab-switch shouldn't teleport the truck
|
| 759 |
+
last = now;
|
| 760 |
+
|
| 761 |
+
// 1x = whole route in 90s of wall clock
|
| 762 |
+
pos += (TOTAL_M / 90) * parseFloat(speedSel.value) * dt;
|
| 763 |
+
|
| 764 |
+
if (pos >= TOTAL_M) { seek(TOTAL_M); stop(); return; }
|
| 765 |
+
seek(pos);
|
| 766 |
+
raf = requestAnimationFrame(tick);
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
// put the truck / trail / HUD at `m` meters along the route
|
| 770 |
+
function seek(m){
|
| 771 |
+
if (!PATH.length) return;
|
| 772 |
+
pos = Math.max(0, Math.min(m, TOTAL_M));
|
| 773 |
+
|
| 774 |
+
// binary search for the segment containing pos
|
| 775 |
+
let lo = 0, hi = PATH.length - 1, i = 0;
|
| 776 |
+
while (lo <= hi) {
|
| 777 |
+
const mid = (lo + hi) >> 1, s = PATH[mid];
|
| 778 |
+
if (pos < s.cum) hi = mid - 1;
|
| 779 |
+
else if (pos > s.cum + s.len) lo = mid + 1;
|
| 780 |
+
else { i = mid; break; }
|
| 781 |
+
i = Math.min(lo, PATH.length - 1);
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
const s = PATH[i];
|
| 785 |
+
const f = s.len ? Math.max(0, Math.min((pos - s.cum) / s.len, 1)) : 0;
|
| 786 |
+
const here = L.latLng(s.a.lat + (s.b.lat - s.a.lat) * f,
|
| 787 |
+
s.a.lng + (s.b.lng - s.a.lng) * f);
|
| 788 |
+
|
| 789 |
+
truck.setLatLng(here);
|
| 790 |
+
truck.setIcon(truckIcon(bearing(s.a, s.b)));
|
| 791 |
+
|
| 792 |
+
const tr = [];
|
| 793 |
+
for (let k = 0; k < i; k++) tr.push(PATH[k].a);
|
| 794 |
+
tr.push(s.a, here);
|
| 795 |
+
trailLine.setLatLngs(tr);
|
| 796 |
+
|
| 797 |
+
if (followCk.checked && playing && !map.getBounds().pad(-0.18).contains(here))
|
| 798 |
+
map.panTo(here, {animate:true, duration:.4});
|
| 799 |
+
|
| 800 |
+
scrub.value = Math.round((pos / TOTAL_M) * 1000);
|
| 801 |
+
updateHud(s);
|
| 802 |
+
}
|
| 803 |
+
|
| 804 |
+
function updateHud(s){
|
| 805 |
+
const pct = pos / TOTAL_M;
|
| 806 |
+
document.getElementById('hudStreet').innerHTML =
|
| 807 |
+
(s.deadhead ? '<span style="color:#d7263d">↷ </span>' : '') + s.name;
|
| 808 |
+
document.getElementById('hudMeta').textContent =
|
| 809 |
+
(pos/1609.344).toFixed(2) + ' / ' + (TOTAL_M/1609.344).toFixed(2) + ' mi · step ' +
|
| 810 |
+
s.order + ' of ' + PATH.length + ' · ~' + Math.round(DRIVE_MIN * pct) + ' min in';
|
| 811 |
+
document.getElementById('hudBar').style.width = (pct * 100) + '%';
|
| 812 |
+
|
| 813 |
+
// highlight the matching turn-by-turn row
|
| 814 |
+
let acc = 0, idx = 0;
|
| 815 |
+
for (let k = 0; k < STEPS.length; k++) {
|
| 816 |
+
acc += STEPS[k].mi * 1609.344;
|
| 817 |
+
idx = k;
|
| 818 |
+
if (pos <= acc) break;
|
| 819 |
+
}
|
| 820 |
+
document.querySelectorAll('#out .street.now').forEach(r => r.classList.remove('now'));
|
| 821 |
+
const row = document.querySelector('#out .street[data-step="' + (idx + 1) + '"]');
|
| 822 |
+
if (row) {
|
| 823 |
+
row.classList.add('now');
|
| 824 |
+
if (playing) row.scrollIntoView({block:'nearest'});
|
| 825 |
+
}
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
// ================= stats panel =================
|
| 829 |
+
function renderStats(s){
|
| 830 |
+
const row = (l, v, c) =>
|
| 831 |
+
'<div class="stat ' + (c||'') + '"><span>' + l + '</span><b>' + v + '</b></div>';
|
| 832 |
|
| 833 |
let h = '';
|
| 834 |
h += row('Total route', s.total_mi.toFixed(2) + ' mi', 'big');
|
|
|
|
| 850 |
});
|
| 851 |
|
| 852 |
h += '<div class="hd" style="margin-top:8px">Directions</div>';
|
| 853 |
+
STEPS.forEach(x => {
|
| 854 |
+
h += '<div class="street" data-step="' + x.step + '"><span>' + x.step + '. ' +
|
| 855 |
(x.deadhead ? '<i style="color:#d7263d">(deadhead)</i> ' : '') +
|
| 856 |
x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
|
| 857 |
});
|
|
|
|
| 872 |
|
| 873 |
# ============================================================ web app
|
| 874 |
app = Flask(__name__)
|
| 875 |
+
UA = {"User-Agent": "route-em/1.0 (personal delivery route tool)"}
|
| 876 |
|
| 877 |
|
| 878 |
@app.route("/")
|
|
|
|
| 894 |
r = requests.get(
|
| 895 |
"https://nominatim.openstreetmap.org/search",
|
| 896 |
params={"q": q, "format": "json", "limit": 1, "countrycodes": "us"},
|
| 897 |
+
headers=UA, timeout=20,
|
|
|
|
| 898 |
)
|
| 899 |
r.raise_for_status()
|
| 900 |
hits = r.json()
|
|
|
|
| 915 |
|
| 916 |
@app.route("/solve", methods=["POST"])
|
| 917 |
def solve_route():
|
| 918 |
+
"""Accepts either {"kind":"bbox","bounds":{...}} or {"kind":"polygon","polygon":{geojson}}."""
|
| 919 |
d = request.get_json(force=True)
|
| 920 |
+
walking = bool(d.get("walking"))
|
| 921 |
+
service = bool(d.get("include_service"))
|
| 922 |
try:
|
| 923 |
+
if d.get("kind") == "polygon" or "polygon" in d:
|
| 924 |
+
poly = d["polygon"]
|
| 925 |
+
area = polygon_area_sq_mi(poly)
|
| 926 |
+
_check_area(area)
|
| 927 |
+
G = graph_from_polygon(poly, walking=walking, include_service=service)
|
| 928 |
+
else:
|
| 929 |
+
b = d["bounds"]
|
| 930 |
+
_check_area(bbox_area_sq_mi(b))
|
| 931 |
+
G = graph_from_bbox(b["north"], b["south"], b["east"], b["west"],
|
| 932 |
+
walking=walking, include_service=service)
|
| 933 |
+
|
| 934 |
+
return jsonify(solve(G, walking=walking,
|
| 935 |
+
start_lat=d.get("start_lat"), start_lon=d.get("start_lon")))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 936 |
except RouteError as exc:
|
| 937 |
return jsonify({"error": str(exc)}), 400
|
| 938 |
except Exception as exc:
|
|
|
|
| 940 |
return jsonify({"error": "Unexpected error: %s" % exc}), 500
|
| 941 |
|
| 942 |
|
| 943 |
+
def _check_area(area):
|
| 944 |
+
if area > MAX_AREA_SQ_MI:
|
| 945 |
+
raise RouteError(
|
| 946 |
+
"That area is about %.0f sq mi -- too big to solve (limit %.0f). "
|
| 947 |
+
"Outline something smaller; a paper route is usually well under 1 sq mi."
|
| 948 |
+
% (area, MAX_AREA_SQ_MI)
|
| 949 |
+
)
|
| 950 |
|
| 951 |
|
| 952 |
if __name__ == "__main__":
|
| 953 |
+
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), debug=False)
|
|
|