Upload app.py
Browse files
app.py
CHANGED
|
@@ -306,6 +306,81 @@ def solve(G, walking=False, start_lat=None, start_lon=None):
|
|
| 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
|
|
@@ -489,8 +564,37 @@ function showShot(f){
|
|
| 489 |
|
| 490 |
// ================= map =================
|
| 491 |
const map = L.map('map').setView([39.83, -98.58], 4);
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
|
| 495 |
const drawn = new L.FeatureGroup().addTo(map);
|
| 496 |
let routeLayer = null, trailLine = null, arrowLayer = null,
|
|
@@ -661,6 +765,67 @@ function render(d){
|
|
| 661 |
|
| 662 |
renderStats(d.stats);
|
| 663 |
seek(0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
}
|
| 665 |
|
| 666 |
// ---- direction arrows, rotated to the way you drive
|
|
@@ -844,6 +1009,9 @@ function renderStats(s){
|
|
| 844 |
h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
|
| 845 |
' intersection(s) were unreachable from the main network and left out.</div>';
|
| 846 |
|
|
|
|
|
|
|
|
|
|
| 847 |
h += '<div class="hd" style="margin-top:8px">Longest streets</div>';
|
| 848 |
s.longest.forEach(x => {
|
| 849 |
h += '<div class="street"><span>' + x.name + '</span><b>' + x.mi.toFixed(2) + ' mi</b></div>';
|
|
@@ -857,6 +1025,7 @@ function renderStats(s){
|
|
| 857 |
});
|
| 858 |
|
| 859 |
document.getElementById('out').innerHTML = h;
|
|
|
|
| 860 |
}
|
| 861 |
|
| 862 |
function msg(t, cls){
|
|
@@ -940,6 +1109,20 @@ def solve_route():
|
|
| 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(
|
|
|
|
| 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
|
|
|
|
| 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: '© OpenStreetMap, © 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 © 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,
|
|
|
|
| 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> — 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
|
|
|
|
| 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>';
|
|
|
|
| 1025 |
});
|
| 1026 |
|
| 1027 |
document.getElementById('out').innerHTML = h;
|
| 1028 |
+
renderHouses();
|
| 1029 |
}
|
| 1030 |
|
| 1031 |
function msg(t, cls){
|
|
|
|
| 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(
|