Files
Michael-A-SloanandCursor 7769a4412e feat: harden maps export for CAD and improve satellite/OSM workflow
Cap zoom to real imagery, attach a BricsCAD-safe DXF IMAGE at the selected extent, and consolidate startup plus Overpass/address handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 15:43:01 -04:00

3104 lines
132 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MAPS to DXF — Standalone</title>
<style>
* { box-sizing: border-box; }
body {
font-family: 'Segoe UI', system-ui, sans-serif;
margin: 0;
padding: 20px;
background: #1e1e2e;
color: #cdd6f4;
max-width: 900px;
margin-left: auto;
margin-right: auto;
}
h1 {
font-size: 1.4rem;
margin: 0 0 16px 0;
font-weight: 600;
}
label {
display: block;
font-size: 0.9rem;
margin-bottom: 6px;
color: #a6adc8;
}
input[type="url"], input[type="text"], select {
width: 100%;
padding: 10px 12px;
font-size: 14px;
border: 1px solid #45475a;
border-radius: 8px;
background: #313244;
color: #cdd6f4;
margin-bottom: 12px;
}
input::placeholder {
color: #6c7086;
}
.row {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 12px;
}
button {
padding: 10px 18px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
background: #89b4fa;
color: #1e1e2e;
}
button:hover {
background: #b4befe;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
button.secondary {
background: #45475a;
color: #cdd6f4;
}
button.secondary:hover {
background: #585b70;
}
#status {
font-size: 13px;
color: #a6adc8;
margin-bottom: 12px;
min-height: 1.4em;
}
#status.error { color: #f38ba8; }
#status.success { color: #a6e3a1; }
#canvasWrap {
border: 1px solid #45475a;
border-radius: 8px;
overflow: hidden;
background: #313244;
margin-bottom: 12px;
}
#c {
display: block;
width: 100%;
height: 400px;
cursor: grab;
}
#c:active {
cursor: grabbing;
}
.legend {
font-size: 12px;
color: #6c7086;
}
.imageryNote {
font-size: 12px;
color: #a6adc8;
margin: 0 0 12px;
line-height: 1.4;
}
.layerSection {
margin-bottom: 12px;
border: 1px solid #45475a;
border-radius: 8px;
background: #313244;
overflow: hidden;
}
.layerSection summary {
padding: 10px 12px;
cursor: pointer;
font-size: 13px;
color: #a6adc8;
user-select: none;
}
.layerSection summary:hover { color: #cdd6f4; }
.layerGrid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 6px 16px;
padding: 10px 12px 12px;
}
.layerGrid label {
display: flex;
align-items: center;
gap: 6px;
margin: 0;
font-size: 12px;
cursor: pointer;
color: #cdd6f4;
}
.layerGrid input[type="checkbox"] { margin: 0; }
.tracePanel { margin-bottom: 12px; }
.tracePanel summary { cursor: pointer; color: #a6adc8; font-size: 0.9rem; margin-bottom: 8px; }
.sliderRow {
display: grid;
grid-template-columns: 140px 1fr 52px;
align-items: center;
gap: 10px;
margin-bottom: 8px;
font-size: 12px;
color: #cdd6f4;
}
.sliderRow input[type="range"] { width: 100%; margin: 0; }
.sliderRow output { text-align: right; color: #a6adc8; font-variant-numeric: tabular-nums; }
</style>
</head>
<body>
<h1>MAPS to DXF</h1>
<p class="legend">Paste a <strong>Google Maps pin URL</strong> for the exact building (best). Typed addresses use <strong>OpenStreetMap</strong>, not Google — they can land on the street or town. Satellite is Esri/USGS, not Google imagery.</p>
<label for="url">Address, place name, or map URL</label>
<input type="text" id="url" placeholder="Paste Google Maps pin URL, or type 141 Industrial Dr, Maysville, GA" autocomplete="off" />
<label for="areaSize">Map area to import</label>
<select id="areaSize" title="Larger areas are split into smaller Overpass requests to avoid rate limits">
<option value="auto">Auto (from map link zoom, or small)</option>
<option value="400" selected>Small — ~400 m radius (fastest)</option>
<option value="800">Medium — ~800 m radius</option>
<option value="1500">Large — ~1.5 km radius</option>
<option value="3000">Extra large — ~3 km radius</option>
</select>
<div class="row">
<button id="btnLoad">Load preview</button>
<button id="btnGoTo" class="secondary" title="Find address on map and zoom in (does not fetch OSM data until you load preview)">Go to address</button>
<button id="btnFit" class="secondary" disabled>Fit view</button>
<button id="btnExport" disabled>Export DXF</button>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;">
<input type="checkbox" id="chkSatellite" />
<span>Show satellite imagery</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Blue crosshair at the searched location. Uncheck to hide it on the map and in the DXF.">
<input type="checkbox" id="chkLocationMarker" checked />
<span>Show waypoint marker</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;">
<span>Satellite source</span>
<select id="selSatelliteSource" title="Google satellite is not available without a paid API key. Try Esri Clarity if World Imagery looks blurry.">
<option value="esri" selected>Esri World Imagery</option>
<option value="clarity">Esri Clarity (often sharper / different date)</option>
<option value="usgs">USGS NAIP (blurry when zoomed in)</option>
</select>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Vectorize imagery into the drawing">
<input type="checkbox" id="chkImageryTrace" />
<span>Generate drawing from imagery</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Use Python server to segment buildings, trees, lots (run ml_server/segment_server.py)">
<input type="checkbox" id="chkServerML" />
<span>Use server-side ML segmentation</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Use VTracer for vectorization (pip install vtracer in ml_server). Cleaner outlines when enabled.">
<input type="checkbox" id="chkVtracer" />
<span>Use VTracer (cleaner vectors)</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Brightness + contrast + threshold (NYPL map-vectorizer style). Good for line-drawing or high-contrast maps.">
<input type="checkbox" id="chkThreshold" />
<span>Threshold mode (map-style)</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Snap trace points to nearby OSM buildings and roads">
<input type="checkbox" id="chkOSMSnap" />
<span>Snap imagery trace to OSM</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Detect large bright roofs (merges HVAC units into building outline)">
<input type="checkbox" id="chkBuildingFootprints" checked />
<span>Building outlines from imagery</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Show OSM building footprints in purple when map data is loaded">
<input type="checkbox" id="chkOSMBuildingTrace" checked />
<span>Overlay OSM building footprints</span>
</label>
<label class="row" style="margin:0;align-items:center;gap:8px;cursor:pointer;" title="Trace fence lines and site boundaries from imagery (orange)">
<input type="checkbox" id="chkTraceFences" checked />
<span>Trace fences &amp; site lines</span>
</label>
</div>
<p class="imageryNote">Satellite is <strong>Esri</strong> (not Google). If it looks fuzzy, switch to <strong>Esri Clarity</strong> and zoom so the building fills more of the view. <strong>Cyan</strong> = buildings, <strong>purple</strong> = OSM, <strong>orange</strong> = fences.</p>
<details class="tracePanel" id="tracePanel">
<summary>Imagery trace tuning (brightness, contrast, edge sensitivity)</summary>
<div class="sliderRow">
<label for="traceBrightness">Brightness</label>
<input type="range" id="traceBrightness" min="-80" max="80" value="0" />
<output id="traceBrightnessVal" for="traceBrightness">0</output>
</div>
<div class="sliderRow">
<label for="traceContrast">Contrast</label>
<input type="range" id="traceContrast" min="50" max="250" value="100" />
<output id="traceContrastVal" for="traceContrast">1.0</output>
</div>
<div class="sliderRow">
<label for="traceEdge" title="Lower = more edges detected">Edge sensitivity</label>
<input type="range" id="traceEdge" min="1" max="20" value="4" />
<output id="traceEdgeVal" for="traceEdge">0.04</output>
</div>
<div class="sliderRow">
<label for="traceThreshold" title="Roof brightness cutoff in building mode; B&amp;W threshold in map mode">Roof / B&amp;W threshold</label>
<input type="range" id="traceThreshold" min="90" max="230" value="150" />
<output id="traceThresholdVal" for="traceThreshold">150</output>
</div>
<div class="row" style="margin-top:4px;">
<button type="button" id="btnRefreshTrace" class="secondary">Refresh trace preview</button>
</div>
</details>
<div class="sliderRow" style="margin-bottom:12px;">
<label for="siteZoom" title="Tight starting view — scroll out on the map to see more">Site zoom</label>
<input type="range" id="siteZoom" min="50" max="500" value="100" />
<output id="siteZoomVal" for="siteZoom">100 m</output>
</div>
<details class="layerSection">
<summary>Layers to include (uncheck to hide in preview and DXF)</summary>
<div class="layerGrid" id="layerGrid"></div>
</details>
<div class="row">
<button id="btnDrawLot" class="secondary" disabled title="Trace lot boundaries on the map">Draw lot</button>
<button id="btnCloseLot" class="secondary" disabled>Close lot</button>
<button id="btnClearLots" class="secondary" disabled>Clear lots</button>
<button id="btnEditLots" class="secondary" disabled title="Move lot vertices to correct positions">Edit lots</button>
<button id="btnDetectLots" class="secondary" disabled title="Detect lot boundaries from satellite imagery">Detect lots from imagery</button>
<button id="btnDetectBuildings" class="secondary" disabled title="Find building outlines inside the blue detection area or a drawn lot">Detect buildings in boundary</button>
<button id="btnSelectArea" class="secondary" disabled title="Draw a rectangle to limit detection to that area">Select detection area</button>
<button id="btnAddSelectionAsLot" class="secondary" disabled title="Use the blue rectangle as one lot (property boundary)">Add selection as lot</button>
<button id="btnClearArea" class="secondary" disabled title="Clear the detection area and detect on full view">Clear area</button>
<button id="btnSetImageBounds" class="secondary" disabled title="Draw a rectangle to set the satellite image extent in the DXF">Set image bounds</button>
<button id="btnClearImageBounds" class="secondary" disabled title="Use current view as image extent">Clear image bounds</button>
</div>
<p id="status"></p>
<div id="canvasWrap">
<canvas id="c"></canvas>
</div>
<p class="legend">Site-plan style: roads (light blue), buildings (purple, hatched in DXF), trees (green), open land (light green), parking (red rectangles). <strong>Generate drawing from imagery</strong> uses edge trace (optional OSM snap). <strong>Server-side ML</strong> uses Python segmentation when enabled; <strong>Threshold mode</strong> uses NYPL map-vectorizer-style brightness/contrast/threshold for line-drawing maps. <strong>Export DXF</strong> downloads a ZIP: unzip and open the DXF — the satellite image is already attached and scaled to the selected extent (orange box, or current view). Center = map origin. Zoom stops at the sharpest tile that exists. <strong>Drag to pan, scroll to zoom.</strong></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="app.js"></script>
<script>
(function() {
const urlInput = document.getElementById('url');
const btnLoad = document.getElementById('btnLoad');
const btnFit = document.getElementById('btnFit');
const btnExport = document.getElementById('btnExport');
const status = document.getElementById('status');
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
let previewData = [];
let osmData = null;
let centerOrigin = null;
let viewRadiusLatDeg = 0.002, viewRadiusLonDeg = 0.002 * 1.5;
let scale = 1, offsetX = 0, offsetY = 0;
const padding = 30;
const MIN_SCALE = 0.05, MAX_SCALE = 80;
let isDragging = false, lastCanvasX = 0, lastCanvasY = 0;
let showSatellite = false;
const tileCache = {};
const TILE_SIZE = 256;
const ADVERTISED_MAX_ZOOM = { esri: 19, clarity: 19, usgs: 16 };
const nativeMaxZoomBySource = { esri: 19, clarity: 19, usgs: 16 };
const nativeZoomHits = {};
let tileProbeGen = 0;
let clampRedrawTimer = null;
const METERS_PER_LAT = 111132.92;
let drawLotMode = false;
let editLotMode = false;
let currentLot = [];
let lots = [];
let mouseCanvas = null;
let selectedVertex = null;
const VERTEX_HIT_RADIUS = 10;
let selectAreaMode = false;
let rectStart = null;
let rectCurrent = null;
let detectionRect = null;
let imageBoundsRect = null; /* user-defined extent for satellite image in DXF; null = use view */
let imageBoundsMode = false;
let imageBoundsStart = null;
let imageBoundsCurrent = null;
let previewImageryTracePolylines = [];
let previewImageryFencePolylines = [];
let previewOsmBuildingPolylines = [];
let traceRunId = 0;
function getSatelliteSource() {
const el = document.getElementById('selSatelliteSource');
return el ? el.value : 'esri';
}
function getRawTileZoom() {
if (!centerOrigin) return 15;
const metersPerPixel = 1 / scale;
const z = Math.log2(156543.03392 * Math.cos((centerOrigin.lat * Math.PI) / 180) / metersPerPixel);
return Math.round(z);
}
/** USGS tiles stop at z16; use Esri automatically when zoomed in for sharp imagery. */
function getEffectiveTileSource() {
const preferred = getSatelliteSource();
if (preferred === 'usgs' && getRawTileZoom() > 16) return 'esri';
return preferred;
}
function clearTileCache() {
Object.keys(tileCache).forEach((k) => { delete tileCache[k]; });
}
const LAYER_LABELS = {
buildings: 'Buildings',
roads: 'Roads',
railways: 'Railways',
paths: 'Paths (footways, cycleways)',
water: 'Water',
parks: 'Parks & gardens',
landuse: 'Land use (retail, commercial)',
parkingOutline: 'Parking (outline)',
parkingSpaces: 'Parking spaces (cars)',
trees: 'Trees',
barriers: 'Barriers & fences',
power: 'Power lines',
boundary: 'Boundary',
man_made: 'Embankments & cutlines'
};
const layerGrid = document.getElementById('layerGrid');
Object.keys(DEFAULT_LAYER_OPTIONS).forEach(function(key) {
const label = document.createElement('label');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = DEFAULT_LAYER_OPTIONS[key] !== false;
cb.id = 'chkLayer_' + key;
cb.dataset.layerKey = key;
label.appendChild(cb);
label.appendChild(document.createTextNode(LAYER_LABELS[key] || key));
layerGrid.appendChild(label);
});
function getLayerOptions() {
const opts = {};
Object.keys(DEFAULT_LAYER_OPTIONS).forEach(function(key) {
const el = document.getElementById('chkLayer_' + key);
opts[key] = el ? el.checked : true;
});
opts.locationMarker = showLocationMarker();
return opts;
}
function showLocationMarker() {
const el = document.getElementById('chkLocationMarker');
return !el || el.checked;
}
function refreshPreviewFromLayers() {
if (osmData && centerOrigin) {
previewData = buildPreviewData(osmData, centerOrigin, getLayerOptions());
draw();
}
}
layerGrid.querySelectorAll('input[type="checkbox"]').forEach(function(cb) {
cb.addEventListener('change', refreshPreviewFromLayers);
});
function getMetersPerLon() {
if (!centerOrigin) return 111412.84;
return 111412.84 * Math.cos((centerOrigin.lat * Math.PI) / 180);
}
function worldToLatLon(wx, wy) {
if (!centerOrigin) return { lat: 0, lon: 0 };
const mplon = getMetersPerLon();
return {
lon: centerOrigin.lon + wx / mplon,
lat: centerOrigin.lat + wy / METERS_PER_LAT
};
}
function latLonToWorld(lat, lon) {
if (!centerOrigin) return { x: 0, y: 0 };
const mplon = getMetersPerLon();
return {
x: (lon - centerOrigin.lon) * mplon,
y: (lat - centerOrigin.lat) * METERS_PER_LAT
};
}
function advertisedMaxZoomForSource(source) {
return ADVERTISED_MAX_ZOOM[source] || 21;
}
function getMaxNativeTileZoom() {
const source = getEffectiveTileSource();
const advertised = advertisedMaxZoomForSource(source);
const n = nativeMaxZoomBySource[source];
return Math.max(1, Math.min(advertised, n != null ? n : advertised));
}
function capTileZoom(z) {
return Math.max(0, Math.min(getMaxNativeTileZoom(), z));
}
function metersPerPixelForZoom(z) {
if (!centerOrigin) return 156543.03392 / Math.pow(2, z);
return 156543.03392 * Math.cos((centerOrigin.lat * Math.PI) / 180) / Math.pow(2, z);
}
function maxScaleForNativeTiles() {
return 1 / metersPerPixelForZoom(getMaxNativeTileZoom());
}
function getMaxAllowedScale() {
if (!showSatellite || !centerOrigin) return MAX_SCALE;
return Math.min(MAX_SCALE, maxScaleForNativeTiles());
}
function clampScaleToNativeTiles() {
if (!showSatellite || !centerOrigin) return false;
const maxS = getMaxAllowedScale();
if (scale <= maxS) return false;
const mx = canvas.width / 2;
const my = canvas.height / 2;
const wx = (mx - offsetX) / scale;
const wy = (offsetY - my) / scale;
scale = maxS;
offsetX = mx - wx * scale;
offsetY = my + wy * scale;
return true;
}
function scheduleClampToNativeTiles() {
if (clampRedrawTimer) return;
clampRedrawTimer = setTimeout(function() {
clampRedrawTimer = null;
if (clampScaleToNativeTiles()) draw();
}, 0);
}
function resetTileZoomCap() {
const source = getEffectiveTileSource();
nativeMaxZoomBySource[source] = advertisedMaxZoomForSource(source);
nativeZoomHits[source] = {};
}
function noteTileZoomPresent(source, z) {
const rec = nativeZoomHits[source] || (nativeZoomHits[source] = {});
rec[z] = rec[z] || { ok: 0, miss: 0 };
rec[z].ok++;
}
function noteTileZoomMissing(source, z) {
const rec = nativeZoomHits[source] || (nativeZoomHits[source] = {});
rec[z] = rec[z] || { ok: 0, miss: 0 };
rec[z].miss++;
if (rec[z].ok > 0) return;
if (z <= nativeMaxZoomBySource[source]) {
nativeMaxZoomBySource[source] = Math.max(1, z - 1);
scheduleClampToNativeTiles();
}
}
function getTileZoom() {
if (!centerOrigin) return 15;
const mplon = getMetersPerLon();
const metersPerPixel = 1 / scale;
const z = Math.log2(156543.03392 * Math.cos((centerOrigin.lat * Math.PI) / 180) / metersPerPixel);
return capTileZoom(Math.round(z));
}
function latLonToTile(lat, lon, z) {
const latRad = (lat * Math.PI) / 180;
const x = (lon + 180) / 360;
const y = (1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2;
const n = Math.pow(2, z);
return { tx: Math.floor(x * n), ty: Math.floor(y * n) };
}
function tileToLatLonBounds(tx, ty, z) {
const n = Math.pow(2, z);
const lonMin = (tx / n) * 360 - 180;
const lonMax = ((tx + 1) / n) * 360 - 180;
const yMin = ty / n;
const yMax = (ty + 1) / n;
const latMax = (180 / Math.PI) * (2 * Math.atan(Math.exp(Math.PI * (1 - 2 * yMin))) - Math.PI / 2);
const latMin = (180 / Math.PI) * (2 * Math.atan(Math.exp(Math.PI * (1 - 2 * yMax))) - Math.PI / 2);
return { latMin, latMax, lonMin, lonMax };
}
function getTilesInView(z) {
const cw = canvas.width, ch = canvas.height;
const worldLeft = -offsetX / scale;
const worldRight = (cw - offsetX) / scale;
const worldBottom = (offsetY - ch) / scale;
const worldTop = offsetY / scale;
const tl = worldToLatLon(worldLeft, worldTop);
const br = worldToLatLon(worldRight, worldBottom);
const minT = latLonToTile(Math.max(tl.lat, br.lat), Math.min(tl.lon, br.lon), z);
const maxT = latLonToTile(Math.min(tl.lat, br.lat), Math.max(tl.lon, br.lon), z);
const tiles = [];
for (let ty = minT.ty; ty <= maxT.ty; ty++) {
for (let tx = minT.tx; tx <= maxT.tx; tx++) {
tiles.push({ tx, ty, z });
}
}
return tiles;
}
function getMapExtentInMeters() {
const mplon = getMetersPerLon();
return {
minX: -viewRadiusLonDeg * mplon,
maxX: viewRadiusLonDeg * mplon,
minY: -viewRadiusLatDeg * METERS_PER_LAT,
maxY: viewRadiusLatDeg * METERS_PER_LAT
};
}
function getVisibleExtentInMeters() {
const cw = canvas.width;
const ch = canvas.height;
return {
minX: -offsetX / scale,
maxX: (cw - offsetX) / scale,
minY: (offsetY - ch) / scale,
maxY: offsetY / scale
};
}
function getTraceExtentInMeters() {
if (imageBoundsRect) return imageBoundsRect;
return getVisibleExtentInMeters();
}
function getTileZoomForExtent(minX, maxX, minY, maxY, size) {
const w = maxX - minX, h = maxY - minY;
const metersPerPixel = Math.max(w, h) / size;
const z = Math.log2(156543.03392 * Math.cos((centerOrigin.lat * Math.PI) / 180) / metersPerPixel);
return capTileZoom(Math.round(z));
}
function getTilesInViewForExtent(minX, maxX, minY, maxY, z) {
const tl = worldToLatLon(minX, maxY);
const br = worldToLatLon(maxX, minY);
const minT = latLonToTile(Math.max(tl.lat, br.lat), Math.min(tl.lon, br.lon), z);
const maxT = latLonToTile(Math.min(tl.lat, br.lat), Math.max(tl.lon, br.lon), z);
const tiles = [];
for (let ty = minT.ty; ty <= maxT.ty; ty++) {
for (let tx = minT.tx; tx <= maxT.tx; tx++) {
tiles.push({ tx, ty, z });
}
}
return tiles;
}
function drawSatelliteForExtent(minX, maxX, minY, maxY, widthPx, heightPx) {
return new Promise((resolve) => {
if (!centerOrigin) { resolve(null); return; }
const wp = Math.max(1, Math.round(widthPx));
const hp = heightPx != null ? Math.max(1, Math.round(heightPx)) : wp;
const off = document.createElement('canvas');
off.width = wp;
off.height = hp;
const octx = off.getContext('2d');
octx.fillStyle = '#8b8b8b';
octx.fillRect(0, 0, wp, hp);
const w = maxX - minX;
const h = maxY - minY;
if (w < 1 || h < 1) { resolve(null); return; }
const z = getTileZoomForExtent(minX, maxX, minY, maxY, Math.max(wp, hp));
const tiles = getTilesInViewForExtent(minX, maxX, minY, maxY, z);
let pending = tiles.length;
let tilesDrawn = 0;
if (pending === 0) { resolve(null); return; }
function done() {
pending--;
if (pending === 0) resolve(tilesDrawn > 0 ? off : null);
}
tiles.forEach(({ tx, ty, z: zz }) => {
getTileImage(zz, tx, ty, (img) => {
if (!tileIsReady(img)) { done(); return; }
const b = tileToLatLonBounds(tx, ty, zz);
const tl = latLonToWorld(b.latMax, b.lonMin);
const br = latLonToWorld(b.latMin, b.lonMax);
const pxLeft = ((tl.x - minX) / w) * wp;
const pxTop = ((maxY - tl.y) / h) * hp;
const pxW = ((br.x - tl.x) / w) * wp;
const pxH = ((tl.y - br.y) / h) * hp;
octx.drawImage(img, 0, 0, TILE_SIZE, TILE_SIZE, pxLeft, pxTop, pxW, pxH);
tilesDrawn++;
done();
}, done);
});
});
}
function drawSatelliteToContext(targetCtx, targetWidth, targetHeight, scaleFactor) {
const sf = scaleFactor || 1;
return new Promise((resolve) => {
if (!centerOrigin) { resolve(); return; }
targetCtx.fillStyle = '#313244';
targetCtx.fillRect(0, 0, targetWidth, targetHeight);
const z = getTileZoom();
const tiles = getTilesInView(z);
let pending = tiles.length;
if (pending === 0) { resolve(); return; }
function done() {
pending--;
if (pending === 0) resolve();
}
tiles.forEach(({ tx, ty, z: zz }) => {
getTileImage(zz, tx, ty, (img) => {
if (!tileIsReady(img)) { done(); return; }
const b = tileToLatLonBounds(tx, ty, zz);
const tl = latLonToWorld(b.latMax, b.lonMin);
const br = latLonToWorld(b.latMin, b.lonMax);
const left = offsetX + tl.x * scale;
const top = offsetY - tl.y * scale;
const w = (br.x - tl.x) * scale;
const h = (tl.y - br.y) * scale;
targetCtx.drawImage(img, 0, 0, TILE_SIZE, TILE_SIZE, left * sf, top * sf, w * sf, h * sf);
done();
}, done);
});
});
}
function tileIsReady(t) {
if (!t || t.pending || t.missing) return false;
if (t.naturalWidth > 0) return true;
return t.tagName === 'CANVAS' && t.width > 0;
}
function tileIsNoDataImage(img) {
if (!img || !tileIsReady(img)) return false;
try {
const s = 32;
const c = document.createElement('canvas');
c.width = s;
c.height = s;
const ctx = c.getContext('2d', { willReadFrequently: true });
if (!ctx) return false;
ctx.drawImage(img, 0, 0, s, s);
const data = ctx.getImageData(0, 0, s, s).data;
let sum = 0;
let sum2 = 0;
let satSum = 0;
const n = s * s;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const y = 0.299 * r + 0.587 * g + 0.114 * b;
sum += y;
sum2 += y * y;
const mx = r > g ? (r > b ? r : b) : (g > b ? g : b);
const mn = r < g ? (r < b ? r : b) : (g < b ? g : b);
satSum += mx - mn;
}
const mean = sum / n;
const variance = sum2 / n - mean * mean;
const sat = satSum / n;
return sat < 22 && variance < 500 && mean > 150 && mean < 230;
} catch (e) {
return false;
}
}
function cacheDecodedTile(key, blob) {
return new Promise(function(resolve, reject) {
const img = new Image();
img.crossOrigin = 'anonymous';
const objUrl = URL.createObjectURL(blob);
img.onload = function() {
URL.revokeObjectURL(objUrl);
tileCache[key] = img;
resolve(img);
};
img.onerror = function() {
URL.revokeObjectURL(objUrl);
delete tileCache[key];
reject(new Error('tile decode failed'));
};
img.src = objUrl;
});
}
function getTileImage(z, tx, ty, onLoad, onError) {
const source = getEffectiveTileSource();
const key = source + '_' + z + '_' + tx + '_' + ty;
if (tileCache[key]) {
if (tileIsReady(tileCache[key])) onLoad(tileCache[key]);
else if (tileCache[key].pending) tileCache[key].waiters.push({ onLoad: onLoad, onError: onError });
else if (onError) onError();
return;
}
const pending = { pending: true, waiters: [{ onLoad: onLoad, onError: onError }] };
tileCache[key] = pending;
const ac = new AbortController();
const timer = setTimeout(function() { ac.abort(); }, 20000);
fetch('/api/tile/' + z + '/' + ty + '/' + tx + '?source=' + encodeURIComponent(source), { signal: ac.signal })
.then(function(r) {
clearTimeout(timer);
if (r.status === 404) {
noteTileZoomMissing(source, z);
throw new Error('missing');
}
if (!r.ok) throw new Error('tile ' + r.status);
return r.blob();
})
.then(function(blob) { return cacheDecodedTile(key, blob); })
.then(function(img) {
if (tileIsNoDataImage(img)) {
tileCache[key] = { missing: true };
noteTileZoomMissing(source, z);
pending.waiters.forEach(function(w) { if (w.onError) w.onError(); });
return;
}
noteTileZoomPresent(source, z);
pending.waiters.forEach(function(w) { w.onLoad(img); });
})
.catch(function() {
clearTimeout(timer);
if (tileIsReady(tileCache[key])) {
pending.waiters.forEach(function(w) { w.onLoad(tileCache[key]); });
return;
}
delete tileCache[key];
pending.waiters.forEach(function(w) { if (w.onError) w.onError(); });
});
}
async function probeNativeMaxZoom(force) {
if (!centerOrigin) return;
if (!showSatellite && !force) return;
const gen = ++tileProbeGen;
const source = getEffectiveTileSource();
let best = 0;
const hits = nativeZoomHits[source];
if (hits) {
Object.keys(hits).forEach(function(z) {
if (hits[z].ok > 0) best = Math.max(best, Number(z));
});
}
if (best > 0) {
nativeMaxZoomBySource[source] = best;
if (!force) {
clampScaleToNativeTiles();
draw();
}
return;
}
const advertised = advertisedMaxZoomForSource(source);
for (let z = advertised; z >= 14; z--) {
if (gen !== tileProbeGen) return;
const t = latLonToTile(centerOrigin.lat, centerOrigin.lon, z);
const key = source + '_' + z + '_' + t.tx + '_' + t.ty;
let ok = false;
try {
if (tileCache[key] && tileCache[key].missing) {
ok = false;
} else if (tileIsReady(tileCache[key])) {
if (tileIsNoDataImage(tileCache[key])) {
tileCache[key] = { missing: true };
ok = false;
} else {
ok = true;
}
} else {
const r = await fetch('/api/tile/' + z + '/' + t.ty + '/' + t.tx + '?source=' + encodeURIComponent(source));
if (gen !== tileProbeGen) return;
if (r.ok) {
const img = await cacheDecodedTile(key, await r.blob());
if (tileIsNoDataImage(img)) {
tileCache[key] = { missing: true };
ok = false;
} else {
ok = true;
}
}
}
} catch (e) {
ok = false;
}
if (ok) {
noteTileZoomPresent(source, z);
nativeMaxZoomBySource[source] = z;
if (!force) {
clampScaleToNativeTiles();
draw();
}
return;
}
noteTileZoomMissing(source, z);
}
nativeMaxZoomBySource[source] = 14;
if (!force) {
clampScaleToNativeTiles();
draw();
}
}
function drawSatelliteLayer() {
if (!centerOrigin || !showSatellite) return;
const z = getTileZoom();
const tiles = getTilesInView(z);
let pending = tiles.length;
if (pending === 0) {
drawVectorLayer();
return;
}
function done() {
pending--;
if (pending === 0) {
drawVectorLayer();
drawImageryTraceLayer();
drawLotsLayer();
}
}
tiles.forEach(({ tx, ty, z: zz }) => {
getTileImage(zz, tx, ty, (img) => {
if (!tileIsReady(img)) { done(); return; }
const b = tileToLatLonBounds(tx, ty, zz);
const tl = latLonToWorld(b.latMax, b.lonMin);
const br = latLonToWorld(b.latMin, b.lonMax);
const left = offsetX + tl.x * scale;
const top = offsetY - tl.y * scale;
const w = (br.x - tl.x) * scale;
const h = (tl.y - br.y) * scale;
ctx.drawImage(img, 0, 0, TILE_SIZE, TILE_SIZE, left, top, w, h);
done();
}, done);
});
}
function drawVectorLayer() {
if (!previewData.length) return;
previewData.forEach((cmd) => {
const c = color(cmd[cmd.length - 1]);
const code = typeof cmd[cmd.length - 1] === 'string' ? parseInt(cmd[cmd.length - 1], 10) : cmd[cmd.length - 1];
ctx.strokeStyle = c;
ctx.fillStyle = c;
ctx.lineWidth = (code === 1) ? 2.2 : 1.2;
ctx.lineCap = 'round';
if (cmd[0] === 'L') {
const p1 = toScreen(cmd[1], cmd[2]), p2 = toScreen(cmd[3], cmd[4]);
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
} else if (cmd[0] === 'C') {
const p = toScreen(cmd[1], cmd[2]);
const r = Math.max((cmd[3] || 2) * scale, 1.5);
ctx.beginPath();
ctx.arc(p.x, p.y, r, 0, Math.PI * 2);
if (code === 3) {
ctx.fillStyle = '#228B22';
ctx.fill();
ctx.strokeStyle = '#1a6b1a';
}
ctx.stroke();
} else if (cmd[0] === 'R') {
const cx = cmd[1], cy = cmd[2], hw = cmd[3], hh = cmd[4];
const tl = toScreen(cx - hw, cy + hh);
const w = 2 * hw * scale, h = 2 * hh * scale;
ctx.fillStyle = c; /* parking red from palette (original site-plan) */
ctx.fillRect(tl.x, tl.y, w, h);
ctx.strokeStyle = '#8b3a3a';
ctx.lineWidth = 1;
ctx.strokeRect(tl.x, tl.y, w, h);
}
});
}
function getCanvasCoords(e) {
const rect = canvas.getBoundingClientRect();
const sx = (e.clientX - rect.left) * (canvas.width / rect.width);
const sy = (e.clientY - rect.top) * (canvas.height / rect.height);
return { x: sx, y: sy };
}
/* Original site-plan colors: buildings purple, trees green, roads light blue, parking red, open land light green */
const aciColors = {
1: '#9370DB', /* buildings */
2: '#9ACD32', /* paths / minor roads */
3: '#228B22', /* trees, parks */
4: '#87CEEB', /* roads light blue */
5: '#4682B4', /* water */
6: '#87CEEB', /* rails / highway */
7: '#4a4a5a',
8: '#a6adc8',
9: '#C75A5A', /* parking outline (red) */
253: '#98FB98' /* landuse / open land light green */
};
function color(c) {
const key = typeof c === 'string' ? parseInt(c, 10) : c;
return aciColors[key] || '#a6adc8';
}
function getBounds() {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
previewData.forEach((cmd) => {
if (cmd[0] === 'L') {
minX = Math.min(minX, cmd[1], cmd[3]);
minY = Math.min(minY, cmd[2], cmd[4]);
maxX = Math.max(maxX, cmd[1], cmd[3]);
maxY = Math.max(maxY, cmd[2], cmd[4]);
} else if (cmd[0] === 'C') {
const r = cmd[3] || 2;
minX = Math.min(minX, cmd[1] - r);
minY = Math.min(minY, cmd[2] - r);
maxX = Math.max(maxX, cmd[1] + r);
maxY = Math.max(maxY, cmd[2] + r);
} else if (cmd[0] === 'R') {
const hw = cmd[3] || 1.25, hh = cmd[4] || 2.5;
minX = Math.min(minX, cmd[1] - hw);
minY = Math.min(minY, cmd[2] - hh);
maxX = Math.max(maxX, cmd[1] + hw);
maxY = Math.max(maxY, cmd[2] + hh);
}
});
if (minX === Infinity) {
minX = -50; minY = -50; maxX = 50; maxY = 50;
}
const w = Math.max(maxX - minX, 20), h = Math.max(maxY - minY, 20);
return { minX, minY, maxX, maxY, w, h };
}
function toScreen(x, y) {
return {
x: offsetX + x * scale,
y: offsetY - y * scale
};
}
function screenToWorld(sx, sy) {
return {
x: (sx - offsetX) / scale,
y: (offsetY - sy) / scale
};
}
function hitTestVertex(screenX, screenY) {
for (let li = 0; li < lots.length; li++) {
const poly = lots[li];
for (let vi = 0; vi < poly.length; vi++) {
const s = toScreen(poly[vi].x, poly[vi].y);
if (Math.hypot(screenX - s.x, screenY - s.y) <= VERTEX_HIT_RADIUS)
return { lotIndex: li, vertexIndex: vi };
}
}
return null;
}
function drawDetectionRectLayer() {
if (detectionRect) {
const p1 = toScreen(detectionRect.minX, detectionRect.maxY);
const p2 = toScreen(detectionRect.maxX, detectionRect.minY);
ctx.fillStyle = 'rgba(137, 180, 250, 0.2)';
ctx.fillRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.strokeStyle = '#89b4fa';
ctx.lineWidth = 2;
ctx.setLineDash([6, 4]);
ctx.strokeRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.setLineDash([]);
}
if (selectAreaMode && rectStart && rectCurrent) {
const x = Math.min(rectStart.x, rectCurrent.x);
const y = Math.min(rectStart.y, rectCurrent.y);
const w = Math.abs(rectCurrent.x - rectStart.x);
const h = Math.abs(rectCurrent.y - rectStart.y);
ctx.fillStyle = 'rgba(137, 180, 250, 0.25)';
ctx.fillRect(x, y, w, h);
ctx.strokeStyle = '#89b4fa';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, w, h);
}
/* Image bounds (satellite extent in DXF) - orange */
if (imageBoundsRect) {
const p1 = toScreen(imageBoundsRect.minX, imageBoundsRect.maxY);
const p2 = toScreen(imageBoundsRect.maxX, imageBoundsRect.minY);
ctx.fillStyle = 'rgba(249, 168, 37, 0.2)';
ctx.fillRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.strokeStyle = '#f9a825';
ctx.lineWidth = 2;
ctx.setLineDash([4, 4]);
ctx.strokeRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.setLineDash([]);
}
if (imageBoundsMode && imageBoundsStart && imageBoundsCurrent) {
const x = Math.min(imageBoundsStart.x, imageBoundsCurrent.x);
const y = Math.min(imageBoundsStart.y, imageBoundsCurrent.y);
const w = Math.abs(imageBoundsCurrent.x - imageBoundsStart.x);
const h = Math.abs(imageBoundsCurrent.y - imageBoundsStart.y);
ctx.fillStyle = 'rgba(249, 168, 37, 0.25)';
ctx.fillRect(x, y, w, h);
ctx.strokeStyle = '#f9a825';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, w, h);
}
}
function drawLotsLayer() {
drawDetectionRectLayer();
if (lots.length === 0 && currentLot.length === 0 && !detectionRect && !(selectAreaMode && rectStart) && !imageBoundsRect && !(imageBoundsMode && imageBoundsStart)) return;
ctx.strokeStyle = '#f9e2af';
ctx.fillStyle = 'rgba(249, 226, 175, 0.15)';
ctx.lineWidth = 2.5;
ctx.setLineDash([6, 4]);
lots.forEach((poly, li) => {
if (poly.length < 2) return;
ctx.beginPath();
const p0 = toScreen(poly[0].x, poly[0].y);
ctx.moveTo(p0.x, p0.y);
for (let i = 1; i < poly.length; i++) ctx.lineTo(toScreen(poly[i].x, poly[i].y).x, toScreen(poly[i].x, poly[i].y).y);
ctx.closePath();
ctx.fill();
ctx.stroke();
if (editLotMode) {
poly.forEach((pt, vi) => {
const s = toScreen(pt.x, pt.y);
const isSelected = selectedVertex && selectedVertex.lotIndex === li && selectedVertex.vertexIndex === vi;
ctx.fillStyle = isSelected ? '#a6e3a1' : '#f9e2af';
ctx.beginPath();
ctx.arc(s.x, s.y, isSelected ? 8 : 6, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#1e1e2e';
ctx.lineWidth = 1;
ctx.stroke();
ctx.strokeStyle = '#f9e2af';
ctx.lineWidth = 2.5;
});
}
});
if (currentLot.length > 0) {
ctx.beginPath();
const p0 = toScreen(currentLot[0].x, currentLot[0].y);
ctx.moveTo(p0.x, p0.y);
for (let i = 1; i < currentLot.length; i++) ctx.lineTo(toScreen(currentLot[i].x, currentLot[i].y).x, toScreen(currentLot[i].x, currentLot[i].y).y);
if (mouseCanvas) ctx.lineTo(mouseCanvas.x, mouseCanvas.y);
ctx.stroke();
currentLot.forEach((pt, i) => {
ctx.fillStyle = '#f9e2af';
ctx.beginPath();
ctx.arc(toScreen(pt.x, pt.y).x, toScreen(pt.x, pt.y).y, 4, 0, Math.PI * 2);
ctx.fill();
});
}
ctx.setLineDash([]);
}
function drawImageryTraceLayer() {
if (previewOsmBuildingPolylines.length) {
ctx.strokeStyle = '#c678ff';
ctx.lineWidth = 2.5;
ctx.setLineDash([]);
previewOsmBuildingPolylines.forEach((poly) => {
if (poly.length < 2) return;
ctx.beginPath();
const p0 = toScreen(poly[0].x, poly[0].y);
ctx.moveTo(p0.x, p0.y);
for (let i = 1; i < poly.length; i++) ctx.lineTo(toScreen(poly[i].x, poly[i].y).x, toScreen(poly[i].x, poly[i].y).y);
ctx.closePath();
ctx.stroke();
});
}
if (!previewImageryTracePolylines.length && !previewImageryFencePolylines.length) return;
if (previewImageryFencePolylines.length) {
ctx.strokeStyle = '#fab387';
ctx.lineWidth = 2;
ctx.setLineDash([]);
previewImageryFencePolylines.forEach((poly) => {
if (poly.length < 2) return;
ctx.beginPath();
const p0 = toScreen(poly[0].x, poly[0].y);
ctx.moveTo(p0.x, p0.y);
for (let i = 1; i < poly.length; i++) ctx.lineTo(toScreen(poly[i].x, poly[i].y).x, toScreen(poly[i].x, poly[i].y).y);
ctx.stroke();
});
}
if (!previewImageryTracePolylines.length) return;
ctx.strokeStyle = '#00d4aa';
ctx.lineWidth = 2.5;
ctx.setLineDash([6, 4]);
previewImageryTracePolylines.forEach((poly) => {
if (poly.length < 2) return;
ctx.beginPath();
const p0 = toScreen(poly[0].x, poly[0].y);
ctx.moveTo(p0.x, p0.y);
for (let i = 1; i < poly.length; i++) ctx.lineTo(toScreen(poly[i].x, poly[i].y).x, toScreen(poly[i].x, poly[i].y).y);
ctx.closePath();
ctx.stroke();
});
ctx.setLineDash([]);
}
function draw() {
const cw = canvas.width, ch = canvas.height;
ctx.fillStyle = '#313244';
ctx.fillRect(0, 0, cw, ch);
const hasMap = previewData.length > 0;
const hasSite = !!centerOrigin;
if (!hasMap && !hasSite) {
ctx.fillStyle = '#a6adc8';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Enter an address and click Go to address, or Load preview', cw / 2, ch / 2);
return;
}
if (showSatellite && centerOrigin) {
drawSatelliteLayer();
} else if (hasMap) {
drawVectorLayer();
drawImageryTraceLayer();
drawLotsLayer();
}
if (centerOrigin && showLocationMarker()) drawOriginCrosshair();
if (!hasMap && hasSite && !showSatellite) {
ctx.fillStyle = 'rgba(166, 173, 200, 0.85)';
ctx.font = '13px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Centered on location — turn on satellite or Load preview', cw / 2, ch - 24);
}
}
function drawOriginCrosshair() {
const s = 10;
const p1 = toScreen(-s, 0);
const p2 = toScreen(s, 0);
const p3 = toScreen(0, -s);
const p4 = toScreen(0, s);
ctx.strokeStyle = '#f9e2af';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.moveTo(p3.x, p3.y);
ctx.lineTo(p4.x, p4.y);
ctx.stroke();
ctx.fillStyle = '#f9e2af';
ctx.beginPath();
const c = toScreen(0, 0);
ctx.arc(c.x, c.y, 4, 0, Math.PI * 2);
ctx.fill();
}
function zoomToSiteView(radiusMeters) {
if (!centerOrigin) return;
const cosLat = Math.cos((centerOrigin.lat * Math.PI) / 180);
viewRadiusLatDeg = radiusMeters / 111320;
viewRadiusLonDeg = radiusMeters / (111320 * Math.max(0.01, cosLat));
const mplon = getMetersPerLon();
const minX = -viewRadiusLonDeg * mplon;
const maxX = viewRadiusLonDeg * mplon;
const minY = -viewRadiusLatDeg * METERS_PER_LAT;
const maxY = viewRadiusLatDeg * METERS_PER_LAT;
const w = maxX - minX;
const h = maxY - minY;
const cw = canvas.width;
const ch = canvas.height;
scale = Math.min((cw - 2 * padding) / w, (ch - 2 * padding) / h);
offsetX = cw / 2;
offsetY = ch / 2;
clampScaleToNativeTiles();
draw();
}
function getSiteZoomMeters() {
const el = document.getElementById('siteZoom');
return el ? parseInt(el.value, 10) || 100 : 100;
}
function morphCloseRadii(spanM) {
const closeBig = Math.min(14, Math.max(6, Math.round(spanM / 16)));
const closeMid = Math.min(8, Math.max(3, Math.round(spanM / 32)));
return { closeBig: closeBig, closeMid: closeMid };
}
function getTracePixelSize(spanM) {
if (spanM <= 160) return 1024;
if (spanM <= 320) return 1024;
return PREVIEW_TRACE_SIZE;
}
function getTraceTuneOptions() {
const brightness = parseInt(document.getElementById('traceBrightness').value, 10) || 0;
const contrast = (parseInt(document.getElementById('traceContrast').value, 10) || 100) / 100;
const sobelFactor = (parseInt(document.getElementById('traceEdge').value, 10) || 4) / 100;
const thresholdBlack = parseInt(document.getElementById('traceThreshold').value, 10) || 150;
const useThreshold = !!(document.getElementById('chkThreshold') && document.getElementById('chkThreshold').checked);
const buildingFootprints = !!(document.getElementById('chkBuildingFootprints') && document.getElementById('chkBuildingFootprints').checked);
const traceFences = !!(document.getElementById('chkTraceFences') && document.getElementById('chkTraceFences').checked);
return {
brightness: brightness,
contrast: contrast,
sobelFactor: sobelFactor,
thresholdBlack: thresholdBlack,
roofBright: thresholdBlack,
useThreshold: useThreshold,
buildingFootprints: buildingFootprints,
traceFences: traceFences,
douglasEps: 0.65,
minPolyLengthMeters: 0.05
};
}
function appendTraceTuneToForm(form) {
const tune = getTraceTuneOptions();
form.append('brightness', String(tune.brightness));
form.append('contrast', String(tune.contrast));
form.append('thresholdBlack', String(tune.thresholdBlack));
form.append('thresholdWhite', '255');
}
let traceRefreshTimer = null;
function scheduleTraceRefresh() {
clearTimeout(traceRefreshTimer);
traceRefreshTimer = setTimeout(function() {
if (document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked) {
updatePreviewImageryTrace();
}
}, 700);
}
function bindTraceSlider(id, outId, format, onInput) {
const el = document.getElementById(id);
const out = document.getElementById(outId);
if (!el || !out) return;
function sync() {
out.textContent = format(el.value);
if (onInput) onInput();
}
el.addEventListener('input', sync);
out.textContent = format(el.value);
}
bindTraceSlider('traceBrightness', 'traceBrightnessVal', function(v) { return v; }, scheduleTraceRefresh);
bindTraceSlider('traceContrast', 'traceContrastVal', function(v) { return (v / 100).toFixed(1); }, scheduleTraceRefresh);
bindTraceSlider('traceEdge', 'traceEdgeVal', function(v) { return (v / 100).toFixed(2); }, scheduleTraceRefresh);
bindTraceSlider('traceThreshold', 'traceThresholdVal', function(v) { return v; }, scheduleTraceRefresh);
bindTraceSlider('siteZoom', 'siteZoomVal', function(v) { return v + ' m'; }, null);
document.getElementById('btnRefreshTrace').addEventListener('click', function() {
if (document.getElementById('chkImageryTrace').checked) updatePreviewImageryTrace();
else setStatus('Turn on "Generate drawing from imagery" first.', true);
});
const btnGoTo = document.getElementById('btnGoTo');
btnGoTo.addEventListener('click', async function() {
const input = urlInput.value.trim();
if (!input) {
setStatus('Enter an address or place name to go to.', true);
return;
}
btnGoTo.disabled = true;
try {
const loc = await resolveLocation(input);
centerOrigin = { lat: loc.lat, lon: loc.lon };
resetTileZoomCap();
const zoomM = loc.viewMeters != null
? Math.min(500, Math.max(50, loc.viewMeters))
: getSiteZoomMeters();
zoomToSiteView(zoomM);
const sat = document.getElementById('chkSatellite');
if (sat && !sat.checked) {
sat.checked = true;
showSatellite = true;
}
await probeNativeMaxZoom();
draw();
const label = loc.displayName
? loc.displayName.split(',').slice(0, 2).join(',')
: (loc.lat.toFixed(5) + ', ' + loc.lon.toFixed(5));
setStatus('Centered on ' + label + ' (zoom ~' + zoomM + ' m — scroll out to see more). Load preview for OSM roads, or Export DXF from satellite.', false, true);
enableDrawingTools();
if (document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked) {
updatePreviewImageryTrace();
}
} catch (e) {
setStatus(e.message || 'Could not find that address.', true);
} finally {
btnGoTo.disabled = false;
}
});
function fitView() {
const b = getBounds();
const cw = canvas.width, ch = canvas.height;
scale = Math.min((cw - 2 * padding) / b.w, (ch - 2 * padding) / b.h);
offsetX = cw / 2 - (b.minX + b.w / 2) * scale;
offsetY = ch / 2 + (b.minY + b.h / 2) * scale;
clampScaleToNativeTiles();
draw();
scheduleTraceRefresh();
}
function zoomAt(mx, my, factor) {
const wx = (mx - offsetX) / scale;
const wy = (offsetY - my) / scale;
scale = Math.max(MIN_SCALE, Math.min(getMaxAllowedScale(), scale * factor));
offsetX = mx - wx * scale;
offsetY = my + wy * scale;
draw();
scheduleTraceRefresh();
}
canvas.addEventListener('mousedown', (e) => {
if (e.button !== 0) return;
const p = getCanvasCoords(e);
if (imageBoundsMode) {
imageBoundsStart = p;
imageBoundsCurrent = p;
draw();
return;
}
if (selectAreaMode) {
rectStart = p;
rectCurrent = p;
draw();
return;
}
if (drawLotMode) {
const w = screenToWorld(p.x, p.y);
currentLot.push({ x: w.x, y: w.y });
draw();
return;
}
if (editLotMode) {
const hit = hitTestVertex(p.x, p.y);
if (hit) {
selectedVertex = hit;
isDragging = false;
} else {
selectedVertex = null;
isDragging = true;
lastCanvasX = p.x;
lastCanvasY = p.y;
}
draw();
return;
}
isDragging = true;
lastCanvasX = p.x;
lastCanvasY = p.y;
});
canvas.addEventListener('mousemove', (e) => {
const p = getCanvasCoords(e);
if (imageBoundsMode && imageBoundsStart) {
imageBoundsCurrent = p;
draw();
return;
}
if (selectAreaMode && rectStart) {
rectCurrent = p;
draw();
return;
}
if (drawLotMode) {
mouseCanvas = p;
draw();
return;
}
if (editLotMode) {
if (selectedVertex !== null) {
canvas.style.cursor = 'move';
const w = screenToWorld(p.x, p.y);
lots[selectedVertex.lotIndex][selectedVertex.vertexIndex] = { x: w.x, y: w.y };
draw();
return;
}
if (isDragging) {
offsetX += p.x - lastCanvasX;
offsetY += p.y - lastCanvasY;
lastCanvasX = p.x;
lastCanvasY = p.y;
draw();
return;
}
const hit = hitTestVertex(p.x, p.y);
canvas.style.cursor = hit ? 'pointer' : 'default';
draw();
return;
}
if (!isDragging) return;
offsetX += p.x - lastCanvasX;
offsetY += p.y - lastCanvasY;
lastCanvasX = p.x;
lastCanvasY = p.y;
draw();
});
canvas.addEventListener('mouseup', (e) => {
if (e.button !== 0) return;
if (imageBoundsMode && imageBoundsStart && imageBoundsCurrent) {
const w1 = screenToWorld(imageBoundsStart.x, imageBoundsStart.y);
const w2 = screenToWorld(imageBoundsCurrent.x, imageBoundsCurrent.y);
imageBoundsRect = {
minX: Math.min(w1.x, w2.x),
maxX: Math.max(w1.x, w2.x),
minY: Math.min(w1.y, w2.y),
maxY: Math.max(w1.y, w2.y)
};
imageBoundsStart = null;
imageBoundsCurrent = null;
imageBoundsMode = false;
document.getElementById('btnSetImageBounds').textContent = 'Set image bounds';
document.getElementById('btnSetImageBounds').classList.add('secondary');
document.getElementById('btnClearImageBounds').disabled = false;
canvas.style.cursor = 'grab';
setStatus('Image bounds set (orange box). Export DXF will use this extent for the satellite image. Clear image bounds to use current view.');
draw();
return;
}
if (selectAreaMode && rectStart && rectCurrent) {
const w1 = screenToWorld(rectStart.x, rectStart.y);
const w2 = screenToWorld(rectCurrent.x, rectCurrent.y);
detectionRect = {
minX: Math.min(w1.x, w2.x),
maxX: Math.max(w1.x, w2.x),
minY: Math.min(w1.y, w2.y),
maxY: Math.max(w1.y, w2.y)
};
rectStart = null;
rectCurrent = null;
selectAreaMode = false;
document.getElementById('btnSelectArea').textContent = 'Select detection area';
document.getElementById('btnSelectArea').classList.add('secondary');
document.getElementById('btnAddSelectionAsLot').disabled = false;
canvas.style.cursor = 'grab';
setStatus('Area set. Use "Detect buildings in boundary" for buildings inside this box, "Add selection as lot" for the property line, or "Detect lots" to auto-detect lots.');
draw();
return;
}
if (editLotMode) selectedVertex = null;
if (isDragging) scheduleTraceRefresh();
isDragging = false;
draw();
});
canvas.addEventListener('mouseleave', () => {
isDragging = false;
selectedVertex = null;
if (drawLotMode) mouseCanvas = null;
if (editLotMode) canvas.style.cursor = 'default';
if (selectAreaMode && !rectCurrent) { }
if (imageBoundsMode && !imageBoundsCurrent) { }
draw();
});
canvas.addEventListener('dblclick', (e) => {
if (drawLotMode && currentLot.length >= 3) {
lots.push(currentLot.slice());
currentLot = [];
draw();
}
});
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
if (!centerOrigin) return;
const p = getCanvasCoords(e);
const factor = e.deltaY > 0 ? 0.9 : 1.1;
zoomAt(p.x, p.y, factor);
}, { passive: false });
document.getElementById('chkSatellite').addEventListener('change', (e) => {
showSatellite = e.target.checked;
if (showSatellite) {
draw();
probeNativeMaxZoom();
} else {
draw();
}
scheduleTraceRefresh();
});
const chkLocationMarker = document.getElementById('chkLocationMarker');
if (chkLocationMarker) {
chkLocationMarker.addEventListener('change', () => {
if (osmData && centerOrigin) refreshPreviewFromLayers();
else draw();
});
}
const selSatelliteSource = document.getElementById('selSatelliteSource');
if (selSatelliteSource) {
selSatelliteSource.addEventListener('change', () => {
clearTileCache();
resetTileZoomCap();
if (showSatellite) {
draw();
probeNativeMaxZoom();
} else draw();
scheduleTraceRefresh();
});
}
function filterPolylinesInExtent(polys, extent) {
if (!polys || !polys.length || !extent) return polys || [];
return polys.filter((poly) => {
if (!poly || poly.length < 2) return false;
const cx = poly.reduce((s, p) => s + p.x, 0) / poly.length;
const cy = poly.reduce((s, p) => s + p.y, 0) / poly.length;
return cx >= extent.minX && cx <= extent.maxX && cy >= extent.minY && cy <= extent.maxY;
});
}
const BUILDINGS_ONLY_LAYERS = {
buildings: true,
roads: false,
railways: false,
paths: false,
water: false,
parks: false,
landuse: false,
parkingOutline: false,
parkingSpaces: false,
trees: false,
barriers: false,
power: false,
boundary: false,
man_made: false
};
function getSiteTraceOsmLayers() {
const layers = Object.assign({}, BUILDINGS_ONLY_LAYERS);
layers.buildings = true;
if (document.getElementById('chkTraceFences') && document.getElementById('chkTraceFences').checked) {
layers.barriers = true;
}
return layers;
}
async function fetchOsmBuildingsQuick() {
if (!centerOrigin) return null;
const radiusM = Math.min(getSiteZoomMeters(), 280);
const bbox = {
south: centerOrigin.lat - radiusM / 111320,
north: centerOrigin.lat + radiusM / 111320,
west: centerOrigin.lon - radiusM / (111320 * Math.max(0.01, Math.cos((centerOrigin.lat * Math.PI) / 180))),
east: centerOrigin.lon + radiusM / (111320 * Math.max(0.01, Math.cos((centerOrigin.lat * Math.PI) / 180)))
};
return fetchOsmForBbox(bbox, getSiteTraceOsmLayers(), { quiet: true });
}
const PREVIEW_TRACE_SIZE = 1024;
async function updatePreviewImageryTrace() {
const chk = document.getElementById('chkImageryTrace');
if (!chk || !chk.checked || !centerOrigin) return;
const runId = ++traceRunId;
const satChk = document.getElementById('chkSatellite');
if (satChk && !satChk.checked) {
satChk.checked = true;
showSatellite = true;
draw();
}
const useML = document.getElementById('chkServerML') && document.getElementById('chkServerML').checked;
const useOSMSnap = document.getElementById('chkOSMSnap') && document.getElementById('chkOSMSnap').checked;
const extent = getTraceExtentInMeters();
const spanM = Math.max(extent.maxX - extent.minX, extent.maxY - extent.minY);
const osmPromise = (!osmData && centerOrigin)
? fetchOsmBuildingsQuick().catch(() => null)
: Promise.resolve(osmData);
setStatus(useML ? 'Server-side ML segmentation…' : 'Detecting buildings (~' + Math.round(spanM) + ' m view)…');
try {
const traceSpec = extentToImagePixels(extent.minX, extent.maxX, extent.minY, extent.maxY, getTracePixelSize(spanM));
const traceCanvas = await drawSatelliteForExtent(extent.minX, extent.maxX, extent.minY, extent.maxY, traceSpec.width, traceSpec.height);
if (runId !== traceRunId || !document.getElementById('chkImageryTrace').checked) return;
if (!traceCanvas) {
previewImageryTracePolylines = [];
previewImageryFencePolylines = [];
previewOsmBuildingPolylines = [];
setStatus('Satellite tiles did not load. Check connection, use Esri source, then Refresh trace preview.', true);
draw();
return;
}
let polylines = [];
let fencePolylines = [];
if (useML) {
const form = new FormData();
const blob = await new Promise((res) => traceCanvas.toBlob(res, 'image/png'));
form.append('image', blob, 'image.png');
form.append('minX', String(extent.minX));
form.append('maxX', String(extent.maxX));
form.append('minY', String(extent.minY));
form.append('maxY', String(extent.maxY));
if (document.getElementById('chkVtracer') && document.getElementById('chkVtracer').checked) form.append('useVtracer', '1');
if (document.getElementById('chkThreshold') && document.getElementById('chkThreshold').checked) form.append('useThreshold', '1');
appendTraceTuneToForm(form);
const r = await fetch('/api/segment', { method: 'POST', body: form });
const data = await r.json();
if (!r.ok) {
previewImageryTracePolylines = [];
setStatus('ML: ' + (data.error || r.status), true);
draw();
return;
}
let b = (data.buildings || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
let t = (data.trees || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
let l = (data.lots || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
if (useOSMSnap && osmData && centerOrigin) {
const nodes = getOSMNodesInMeters(osmData, centerOrigin);
b = snapTracePolylinesToOSM(b, osmData, nodes, 1.5);
t = snapTracePolylinesToOSM(t, osmData, nodes, 1.5);
l = snapTracePolylinesToOSM(l, osmData, nodes, 1.5);
}
polylines = b.concat(t).concat(l);
} else {
const raw = vectorizeImageryToPolylines(traceCanvas, extent.minX, extent.maxX, extent.minY, extent.maxY, getTraceTuneOptions());
if (raw === null) {
previewImageryTracePolylines = [];
previewImageryFencePolylines = [];
setStatus('Imagery trace blocked (canvas). Run the app with npm start and open http://localhost:' + (window.location.port || '3456') + '.', true);
draw();
return;
}
let buildingLines = [];
if (raw && raw.buildings) {
buildingLines = raw.buildings;
fencePolylines = raw.fences || [];
} else if (Array.isArray(raw)) {
buildingLines = raw;
}
const clientPolylines = useOSMSnap && osmData && centerOrigin
? snapTracePolylinesToOSM(buildingLines, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
: buildingLines;
polylines = clientPolylines;
}
if (runId !== traceRunId) return;
const traceOsmData = osmData || await osmPromise;
if (runId !== traceRunId) return;
const buildingMode = document.getElementById('chkBuildingFootprints') && document.getElementById('chkBuildingFootprints').checked;
const traceFences = document.getElementById('chkTraceFences') && document.getElementById('chkTraceFences').checked;
let osmBuildingsInView = [];
let osmFencesInView = [];
if (traceOsmData && centerOrigin) {
osmBuildingsInView = filterPolylinesInExtent(getOSMBuildingFootprints(traceOsmData, centerOrigin), extent);
if (traceFences) {
osmFencesInView = filterPolylinesInExtent(getOSMBarrierPolylines(traceOsmData, centerOrigin), extent);
}
}
let usedOsmFallback = false;
if (buildingMode) {
const imageryOnly = polylines.slice();
if (imageryOnly.length === 0 && osmBuildingsInView.length) {
polylines = osmBuildingsInView;
usedOsmFallback = true;
} else if (osmBuildingsInView.length) {
polylines = mergeBuildingPolylines(osmBuildingsInView, imageryOnly);
}
} else if (polylines.length === 0 && osmBuildingsInView.length) {
polylines = osmBuildingsInView;
usedOsmFallback = true;
}
if (traceFences) {
if (fencePolylines.length === 0 && osmFencesInView.length) {
fencePolylines = osmFencesInView;
} else if (osmFencesInView.length) {
fencePolylines = mergeBuildingPolylines(osmFencesInView, fencePolylines);
}
} else {
fencePolylines = [];
}
previewImageryTracePolylines = polylines;
previewImageryFencePolylines = fencePolylines;
const useOsmBuildings = document.getElementById('chkOSMBuildingTrace') && document.getElementById('chkOSMBuildingTrace').checked;
if (useOsmBuildings) {
previewOsmBuildingPolylines = osmBuildingsInView;
} else {
previewOsmBuildingPolylines = [];
}
const n = previewImageryTracePolylines.length;
const fenceN = previewImageryFencePolylines.length;
const osmN = previewOsmBuildingPolylines.length;
const srcNote = getSatelliteSource() === 'usgs' && getEffectiveTileSource() === 'esri'
? ' (Esri tiles for sharp zoom)'
: '';
const imageryCount = buildingMode ? Math.max(0, n - osmN) : n;
setStatus(n > 0 || fenceN > 0
? ((usedOsmFallback && imageryCount === 0
? 'Using OSM building outline(s). '
: imageryCount + ' building(s)' + (fenceN ? ', ' + fenceN + ' fence/site line(s)' : '') + (osmN ? ', ' + osmN + ' OSM bldg' : '') + srcNote + '. ')
+ 'Cyan = buildings, orange = fences, purple = OSM.')
: 'No outlines — zoom out slightly for fence perimeter, use Esri, Load preview (enable Barriers layer), Refresh trace.', n === 0 && fenceN === 0, n > 0 || fenceN > 0);
} catch (err) {
if (runId !== traceRunId) return;
previewImageryTracePolylines = [];
previewImageryFencePolylines = [];
previewOsmBuildingPolylines = [];
setStatus('Imagery trace failed: ' + (err.message || 'unknown error'), true);
}
if (runId !== traceRunId) return;
draw();
}
document.getElementById('chkImageryTrace').addEventListener('change', (e) => {
if (e.target.checked) {
if (centerOrigin) zoomToSiteView(getSiteZoomMeters());
setStatus('Imagery trace on — starting tight zoom…', false, true);
updatePreviewImageryTrace();
} else {
previewImageryTracePolylines = [];
previewImageryFencePolylines = [];
setStatus('', false, false);
draw();
}
});
['chkServerML', 'chkVtracer', 'chkThreshold', 'chkOSMSnap', 'chkBuildingFootprints', 'chkOSMBuildingTrace', 'chkTraceFences'].forEach((id) => {
const el = document.getElementById(id);
if (el) el.addEventListener('change', () => { if (document.getElementById('chkImageryTrace').checked) updatePreviewImageryTrace(); });
});
const btnDrawLot = document.getElementById('btnDrawLot');
const btnCloseLot = document.getElementById('btnCloseLot');
const btnClearLots = document.getElementById('btnClearLots');
btnDrawLot.addEventListener('click', () => {
drawLotMode = !drawLotMode;
btnDrawLot.textContent = drawLotMode ? 'Stop drawing' : 'Draw lot';
btnDrawLot.classList.toggle('secondary', !drawLotMode);
if (!drawLotMode) currentLot = [];
canvas.style.cursor = drawLotMode ? 'crosshair' : 'grab';
draw();
});
btnCloseLot.addEventListener('click', () => {
if (currentLot.length >= 3) {
lots.push(currentLot.slice());
currentLot = [];
draw();
}
});
btnClearLots.addEventListener('click', () => {
lots = [];
currentLot = [];
draw();
});
const btnEditLots = document.getElementById('btnEditLots');
btnEditLots.addEventListener('click', () => {
editLotMode = !editLotMode;
btnEditLots.textContent = editLotMode ? 'Stop editing' : 'Edit lots';
btnEditLots.classList.toggle('secondary', !editLotMode);
selectedVertex = null;
canvas.style.cursor = editLotMode ? 'default' : 'grab';
draw();
});
const MAX_DETECT_SIZE = 480;
function grayscale(data, w, h) {
const out = new Uint8Array(w * h);
for (let i = 0; i < w * h; i++) {
const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
out[i] = (0.299 * r + 0.587 * g + 0.114 * b) | 0;
}
return out;
}
function blur(gray, w, h) {
const out = new Uint8Array(w * h);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
let sum = 0;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) sum += gray[(y + dy) * w + (x + dx)];
out[y * w + x] = (sum / 9) | 0;
}
}
for (let i = 0; i < w * h; i++) if (out[i] === 0) out[i] = gray[i];
return out;
}
/** Stretch contrast to full 0-255. Improves edge detection on flat/dull satellite imagery. */
function applyBrightnessContrast(gray, w, h, brightness, contrast) {
const out = new Uint8Array(w * h);
const b = brightness || 0;
const c = contrast != null ? contrast : 1;
for (let i = 0; i < w * h; i++) {
out[i] = Math.max(0, Math.min(255, Math.round(gray[i] * c + b)));
}
return out;
}
function contrastStretch(gray, w, h) {
const n = w * h;
let low = 255, high = 0;
for (let i = 0; i < n; i++) {
const v = gray[i];
if (v < low) low = v;
if (v > high) high = v;
}
const span = Math.max(high - low, 1);
const out = new Uint8Array(n);
for (let i = 0; i < n; i++) out[i] = Math.max(0, Math.min(255, Math.round(((gray[i] - low) / span) * 255)));
return out;
}
function sobelThreshold(gray, w, h, thresh, factor) {
const out = new Uint8Array(w * h);
const gx = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
const gy = [-1, -2, -1, 0, 0, 0, 1, 2, 1];
let maxMag = 0;
const mag = new Float32Array(w * h);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
let sx = 0, sy = 0;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
const v = gray[(y + dy) * w + (x + dx)];
sx += v * gx[(dy + 1) * 3 + (dx + 1)];
sy += v * gy[(dy + 1) * 3 + (dx + 1)];
}
const m = Math.sqrt(sx * sx + sy * sy);
mag[y * w + x] = m;
if (m > maxMag) maxMag = m;
}
}
const defaultFactor = factor != null ? factor : 0.12;
const t = thresh != null ? thresh : maxMag * defaultFactor;
for (let i = 0; i < w * h; i++) out[i] = mag[i] >= t ? 255 : 0;
return out;
}
function dilateEdge(edge, w, h) {
const out = new Uint8Array(w * h);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * w + x;
if (edge[i] === 255) { out[i] = 255; continue; }
let any = 0;
for (let dy = -1; dy <= 1 && !any; dy++) for (let dx = -1; dx <= 1; dx++)
if (edge[(y + dy) * w + (x + dx)] === 255) { any = 1; break; }
out[i] = any ? 255 : 0;
}
}
for (let i = 0; i < w * h; i++) if (out[i] === 0) out[i] = edge[i];
return out;
}
function erodeEdge(edge, w, h) {
const out = new Uint8Array(w * h);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * w + x;
if (edge[i] !== 255) { out[i] = 0; continue; }
let all = true;
for (let dy = -1; dy <= 1 && all; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (edge[(y + dy) * w + (x + dx)] !== 255) all = false;
}
}
out[i] = all ? 255 : 0;
}
}
return out;
}
function morphClose(mask, w, h, radius) {
let out = mask;
for (let i = 0; i < radius; i++) out = dilateEdge(out, w, h);
for (let i = 0; i < radius; i++) out = erodeEdge(out, w, h);
return out;
}
function maskToBoundary(mask, w, h) {
const out = new Uint8Array(w * h);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * w + x;
if (mask[i] !== 255) continue;
let boundary = false;
for (let dy = -1; dy <= 1 && !boundary; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (mask[(y + dy) * w + (x + dx)] !== 255) { boundary = true; break; }
}
}
if (boundary) out[i] = 255;
}
}
return out;
}
function brightRoofMask(gray, w, h, minBright) {
const out = new Uint8Array(w * h);
for (let i = 0; i < w * h; i++) out[i] = gray[i] >= minBright ? 255 : 0;
return out;
}
function percentileOfSample(values, p) {
if (!values.length) return 180;
const sorted = values.slice().sort((a, b) => a - b);
const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * p));
return sorted[idx];
}
function localAdaptiveRoofMask(data, gray, w, h, roofBright) {
const n = w * h;
const out = new Uint8Array(n);
const sample = [];
const step = Math.max(1, Math.floor(n / 10000));
for (let i = 0; i < n; i += step) sample.push(gray[i]);
const p70 = percentileOfSample(sample, 0.7);
const p85 = percentileOfSample(sample, 0.85);
const globalThresh = Math.max(145, Math.min(roofBright, p70 - 8));
const win = 9;
const half = Math.floor(win / 2);
for (let y = half; y < h - half; y++) {
for (let x = half; x < w - half; x++) {
const i = y * w + x;
const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
const sat = Math.max(r, g, b) - Math.min(r, g, b);
let sum = 0;
for (let dy = -half; dy <= half; dy++) {
for (let dx = -half; dx <= half; dx++) sum += gray[(y + dy) * w + (x + dx)];
}
const mean = sum / (win * win);
const lum = gray[i];
const roofLike = sat < 60 || lum >= 200;
const brightGlobal = lum >= globalThresh || lum >= p85 - 10;
const brightLocal = lum >= mean + 14 && lum >= 130;
if (roofLike && (brightGlobal || brightLocal)) out[i] = 255;
}
}
return out;
}
function convexHullPx(points) {
if (points.length < 3) return points.slice();
const pts = points.slice().sort((a, b) => (a.x !== b.x ? a.x - b.x : a.y - b.y));
const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower = [];
for (const p of pts) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
lower.push(p);
}
const upper = [];
for (let i = pts.length - 1; i >= 0; i--) {
const p = pts[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
upper.push(p);
}
upper.pop();
lower.pop();
return lower.concat(upper);
}
function extractMaskComponents(mask, w, h, minPx, maxPx) {
const visited = new Uint8Array(w * h);
const components = [];
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const start = y * w + x;
if (mask[start] !== 255 || visited[start]) continue;
const pixels = [];
const stack = [start];
visited[start] = 1;
while (stack.length) {
const idx = stack.pop();
const px = idx % w;
const py = (idx / w) | 0;
pixels.push({ x: px, y: py });
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (!dx && !dy) continue;
const nx = px + dx, ny = py + dy;
if (nx < 0 || nx >= w || ny < 0 || ny >= h) continue;
const ni = ny * w + nx;
if (mask[ni] === 255 && !visited[ni]) {
visited[ni] = 1;
stack.push(ni);
}
}
}
}
if (pixels.length >= minPx && pixels.length <= maxPx) components.push(pixels);
}
}
return components;
}
function componentsToWorldPolylines(components, ow, oh, minX, maxX, minY, maxY, sampleStep) {
const polylines = [];
components.forEach((pixels) => {
const sample = pixels.length > 4000
? pixels.filter((_, i) => i % sampleStep === 0)
: pixels;
const hull = convexHullPx(sample);
if (hull.length < 3) return;
polylines.push(contourPixelsToWorldInRect(hull, ow, oh, minX, maxX, minY, maxY));
});
return polylines;
}
function seedGrowRoofMask(data, gray, w, h, seedPercentile) {
const n = w * h;
const hist = new Uint32Array(256);
for (let i = 0; i < n; i++) hist[gray[i]]++;
let cum = 0;
const target = n * (1 - (seedPercentile || 0.9));
let seedThresh = 185;
for (let t = 255; t >= 0; t--) {
cum += hist[t];
if (cum >= target) { seedThresh = t; break; }
}
const mask = new Uint8Array(n);
const visited = new Uint8Array(n);
const queue = [];
for (let i = 0; i < n; i++) {
if (gray[i] < seedThresh) continue;
const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
if (Math.max(r, g, b) - Math.min(r, g, b) > 90) continue;
mask[i] = 255;
visited[i] = 1;
queue.push(i);
}
let qi = 0;
while (qi < queue.length) {
const idx = queue[qi++];
const px = idx % w;
const py = (idx / w) | 0;
const curLum = gray[idx];
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (!dx && !dy) continue;
const nx = px + dx, ny = py + dy;
if (nx < 0 || nx >= w || ny < 0 || ny >= h) continue;
const ni = ny * w + nx;
if (visited[ni]) continue;
const l = gray[ni];
const r = data[ni * 4], g = data[ni * 4 + 1], b = data[ni * 4 + 2];
const sat = Math.max(r, g, b) - Math.min(r, g, b);
const lumOk = l >= curLum - 75 && l >= 60;
const colorOk = sat < 110 || l >= 130;
if (lumOk && colorOk) {
visited[ni] = 1;
mask[ni] = 255;
queue.push(ni);
}
}
}
}
return mask;
}
function permissiveRoofMask(data, gray, w, h, minLum) {
const n = w * h;
const out = new Uint8Array(n);
const min = minLum != null ? minLum : 95;
for (let i = 0; i < n; i++) {
const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
if (g > r + 14 && g > b + 10 && g > 70) continue;
const sat = Math.max(r, g, b) - Math.min(r, g, b);
const l = gray[i];
if (l >= min && (sat < 95 || l >= 130)) out[i] = 255;
}
return out;
}
function componentToAabbPolygon(pixels, ow, oh, minX, maxX, minY, maxY) {
let minPx = 1e9, maxPx = -1, minPy = 1e9, maxPy = -1;
pixels.forEach((p) => {
if (p.x < minPx) minPx = p.x;
if (p.x > maxPx) maxPx = p.x;
if (p.y < minPy) minPy = p.y;
if (p.y > maxPy) maxPy = p.y;
});
const pad = 2;
minPx = Math.max(0, minPx - pad);
minPy = Math.max(0, minPy - pad);
maxPx = Math.min(ow - 1, maxPx + pad);
maxPy = Math.min(oh - 1, maxPy + pad);
const corners = [
{ x: minPx, y: minPy },
{ x: maxPx, y: minPy },
{ x: maxPx, y: maxPy },
{ x: minPx, y: maxPy },
{ x: minPx, y: minPy }
];
return contourPixelsToWorldInRect(corners, ow, oh, minX, maxX, minY, maxY);
}
function extractMaskComponentsSorted(mask, w, h, minPx, maxPx) {
const components = extractMaskComponents(mask, w, h, minPx, maxPx);
components.sort((a, b) => b.length - a.length);
return components;
}
function grayStructureMask(data, gray, w, h) {
const n = w * h;
const out = new Uint8Array(n);
for (let i = 0; i < n; i++) {
const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
if (g > r + 12 && g > b + 8 && g > 65) continue;
const sat = Math.max(r, g, b) - Math.min(r, g, b);
const l = gray[i];
if (l < 48 || l > 242) continue;
if (sat > 80 && l < 150) continue;
out[i] = 255;
}
return out;
}
function extractBuildingFootprintsFromImagery(data, gray, ow, oh, minX, maxX, minY, maxY, options) {
const worldW = maxX - minX;
const worldH = maxY - minY;
const worldAreaM2 = worldW * worldH;
const spanM = Math.max(worldW, worldH);
const pxPerM2 = (ow * oh) / Math.max(worldAreaM2, 1);
const minAreaM2 = spanM <= 160
? Math.max(18, worldAreaM2 * 0.004)
: Math.max(40, worldAreaM2 * 0.002);
const minPx = Math.max(20, Math.floor(minAreaM2 * pxPerM2 * 0.35));
const maxPx = Math.floor(120000 * pxPerM2);
const roofBright = options.roofBright != null ? options.roofBright : 150;
const brightness = options.brightness != null ? options.brightness : 0;
const contrast = options.contrast != null ? options.contrast : 1;
const tuned = applyBrightnessContrast(gray, ow, oh, brightness, contrast);
const radii = morphCloseRadii(spanM);
const maskBuilders = [
() => permissiveRoofMask(data, tuned, ow, oh, Math.max(70, roofBright - 55)),
() => permissiveRoofMask(data, tuned, ow, oh, Math.max(55, roofBright - 80)),
() => seedGrowRoofMask(data, tuned, ow, oh, 0.82),
() => seedGrowRoofMask(data, tuned, ow, oh, 0.7),
() => grayStructureMask(data, tuned, ow, oh),
() => localAdaptiveRoofMask(data, tuned, ow, oh, roofBright)
];
let bestPolys = [];
let bestScore = 0;
for (let mi = 0; mi < maskBuilders.length; mi++) {
let mask = maskBuilders[mi]();
mask = morphClose(mask, ow, oh, radii.closeBig);
mask = morphClose(mask, ow, oh, radii.closeMid);
const components = extractMaskComponentsSorted(mask, ow, oh, minPx, maxPx);
const polylines = [];
for (let ci = 0; ci < components.length && ci < 14; ci++) {
const poly = componentToAabbPolygon(components[ci], ow, oh, minX, maxX, minY, maxY);
if (polygonAreaWorld(poly) >= minAreaM2) polylines.push(poly);
}
const filtered = filterBuildingFootprints(polylines, minAreaM2);
const filteredScore = filtered.reduce((s, p) => s + polygonAreaWorld(p), 0);
if (filteredScore > bestScore) {
bestScore = filteredScore;
bestPolys = filtered;
}
if (filtered.length >= 1 && filteredScore > worldAreaM2 * 0.008) break;
}
return bestPolys;
}
function polyCentroid(poly) {
const cx = poly.reduce((s, p) => s + p.x, 0) / poly.length;
const cy = poly.reduce((s, p) => s + p.y, 0) / poly.length;
return { x: cx, y: cy };
}
function pointInPolygon(x, y, poly) {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const xi = poly[i].x, yi = poly[i].y;
const xj = poly[j].x, yj = poly[j].y;
if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi + 1e-12) + xi)) inside = !inside;
}
return inside;
}
function centroidInsideBuildings(poly, buildings) {
if (!buildings || !buildings.length) return false;
const c = polyCentroid(poly);
for (let i = 0; i < buildings.length; i++) {
if (pointInPolygon(c.x, c.y, buildings[i])) return true;
}
return false;
}
function isFenceLikePoly(poly, minLenM) {
if (!poly || poly.length < 2) return false;
const area = polygonAreaWorld(poly);
const perim = typeof polygonPerimeter === 'function' ? polygonPerimeter(poly) : 0;
if (perim < minLenM) return false;
if (area > 90000) return false;
const compact = perim > 0 ? (4 * Math.PI * area) / (perim * perim) : 0;
if (area >= 120 && compact > 0.22) return false;
if (compact < 0.16 && perim >= 8) return true;
if (perim >= 50 && area >= 150 && area <= 55000 && compact < 0.38) return true;
let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9;
poly.forEach((p) => {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
});
const longSide = Math.max(maxX - minX, maxY - minY);
const shortSide = Math.min(maxX - minX, maxY - minY) + 0.05;
if (longSide / shortSide >= 3.5 && perim >= 10) return true;
return false;
}
function extractFenceLinesFromImagery(tuned, ow, oh, minX, maxX, minY, maxY, options, buildingPolys) {
const sobelFactor = (options && options.sobelFactor != null) ? options.sobelFactor : 0.04;
const minLenM = 8;
const minContourPx = 18;
const stretched = contrastStretch(tuned, ow, oh);
const factors = [sobelFactor * 1.1, sobelFactor * 0.75, 0.028, 0.02];
const seen = new Set();
const fences = [];
function runEdgePass(edge) {
const dilated = dilateEdge(edge, ow, oh);
return findContours(dilated, ow, oh);
}
for (let fi = 0; fi < factors.length; fi++) {
const contours = runEdgePass(sobelThreshold(stretched, ow, oh, null, factors[fi]));
contours.forEach((contour) => {
let pxLen = 0;
for (let i = 0; i < contour.length; i++) {
const a = contour[i], b = contour[(i + 1) % contour.length];
pxLen += Math.hypot(b.x - a.x, b.y - a.y);
}
if (pxLen < minContourPx) return;
const world = contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY);
const simplified = douglasPeucker(world, 0.55);
if (!isFenceLikePoly(simplified, minLenM)) return;
if (centroidInsideBuildings(simplified, buildingPolys)) return;
const c = polyCentroid(simplified);
const key = (c.x | 0) + ',' + (c.y | 0);
if (seen.has(key)) return;
seen.add(key);
fences.push(simplified);
});
}
return fences.sort((a, b) => polygonPerimeter(b) - polygonPerimeter(a)).slice(0, 24);
}
function filterBuildingFootprints(polylines, minAreaM2) {
const minArea = minAreaM2 != null ? minAreaM2 : 40;
return polylines.filter((poly) => {
const area = polygonAreaWorld(poly);
if (area < minArea || area > 120000) return false;
let perim = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i], b = poly[(i + 1) % poly.length];
perim += Math.hypot(b.x - a.x, b.y - a.y);
}
if (perim < 8) return false;
const compact = (4 * Math.PI * area) / (perim * perim);
return compact > 0.02;
}).sort((a, b) => polygonAreaWorld(b) - polygonAreaWorld(a)).slice(0, 12);
}
function mergeBuildingPolylines(primary, secondary) {
const out = (primary || []).slice();
const seen = new Set();
out.forEach((poly) => {
const cx = poly.reduce((s, p) => s + p.x, 0) / poly.length;
const cy = poly.reduce((s, p) => s + p.y, 0) / poly.length;
seen.add((cx | 0) + ',' + (cy | 0));
});
(secondary || []).forEach((poly) => {
const cx = poly.reduce((s, p) => s + p.x, 0) / poly.length;
const cy = poly.reduce((s, p) => s + p.y, 0) / poly.length;
const key = (cx | 0) + ',' + (cy | 0);
if (!seen.has(key)) {
seen.add(key);
out.push(poly);
}
});
return out;
}
const DIRS = [[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0]];
const NEAR_CLOSE_PX = 6;
function findContours(edge, w, h) {
const visited = new Uint8Array(w * h);
const contours = [];
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * w + x;
if (edge[i] !== 255 || visited[i]) continue;
const contour = [];
let cx = x, cy = y;
let fromDir = 4;
const startX = x, startY = y;
do {
contour.push({ x: cx, y: cy });
visited[cy * w + cx] = 1;
let next = -1;
for (let d = 0; d < 8; d++) {
const nd = (fromDir + 5 + d) % 8;
const nx = cx + DIRS[nd][0], ny = cy + DIRS[nd][1];
if (nx < 1 || nx >= w - 1 || ny < 1 || ny >= h - 1) continue;
if (edge[ny * w + nx] === 255) { next = nd; break; }
}
if (next < 0) break;
cx += DIRS[next][0]; cy += DIRS[next][1];
fromDir = (next + 4) % 8;
const closed = cx === startX && cy === startY;
const nearClose = contour.length >= 4 && Math.hypot(cx - startX, cy - startY) <= NEAR_CLOSE_PX;
if (closed || nearClose) break;
} while (contour.length < 5000);
if (contour.length >= 4) {
const last = contour[contour.length - 1];
if (Math.hypot(last.x - startX, last.y - startY) > 0.5)
contour.push({ x: startX, y: startY });
contours.push(contour);
}
}
}
return contours;
}
function polygonArea(points) {
let a = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
a += points[i].x * points[j].y - points[j].x * points[i].y;
}
return Math.abs(a) / 2;
}
function polygonAreaWorld(points) {
if (!points || points.length < 3) return 0;
let a = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
a += points[i].x * points[j].y - points[j].x * points[i].y;
}
return Math.abs(a) / 2;
}
function douglasPeucker(points, eps) {
if (points.length <= 2) return points;
let maxD = 0, idx = 0;
const end = points.length - 1;
const a = points[0], b = points[end];
for (let i = 1; i < end; i++) {
const p = points[i];
const d = Math.abs((b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - b.y * a.x) / Math.hypot(b.x - a.x, b.y - a.y);
if (d > maxD) { maxD = d; idx = i; }
}
if (maxD < eps) return [a, b];
const left = douglasPeucker(points.slice(0, idx + 1), eps);
const right = douglasPeucker(points.slice(idx), eps);
return left.slice(0, -1).concat(right);
}
function contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY) {
const w = maxX - minX, h = maxY - minY;
return contour.map((p) => ({
x: minX + (p.x / ow) * w,
y: maxY - (p.y / oh) * h
}));
}
function thresholdEdges(gray, w, h, thresholdBlack) {
const out = new Uint8Array(w * h);
const t = thresholdBlack != null ? thresholdBlack : 160;
for (let i = 0; i < w * h; i++) out[i] = gray[i] < t ? 255 : 0;
return out;
}
function collectPolylinesFromContours(contours, ow, oh, minX, maxX, minY, maxY, options, minContourPx, minAreaWorld) {
const minLen = (options && options.minPolyLengthMeters != null) ? options.minPolyLengthMeters : 0.05;
const eps = (options && options.douglasEps != null) ? options.douglasEps : 0.65;
const polylines = [];
contours.forEach((contour) => {
let pxLen = 0;
for (let i = 0; i < contour.length; i++) {
const a = contour[i], b = contour[(i + 1) % contour.length];
pxLen += Math.hypot(b.x - a.x, b.y - a.y);
}
if (pxLen < minContourPx) return;
const world = contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY);
const simplified = douglasPeucker(world, eps);
const area = polygonAreaWorld(simplified);
if (area < minAreaWorld) return;
let totalLen = 0;
for (let i = 0; i < simplified.length; i++) {
const a = simplified[i], b = simplified[(i + 1) % simplified.length];
totalLen += Math.hypot(b.x - a.x, b.y - a.y);
}
if (totalLen >= minLen && simplified.length >= 2) polylines.push(simplified);
});
return polylines;
}
const MIN_CONTOUR_PIXELS = 28;
const MIN_AREA_WORLD_M2 = 25;
function vectorizeImageryToPolylines(imgCanvas, minX, maxX, minY, maxY, options) {
const ow = imgCanvas.width, oh = imgCanvas.height;
if (ow < 16 || oh < 16) return [];
const octx = imgCanvas.getContext('2d');
let id;
try {
id = octx.getImageData(0, 0, ow, oh);
} catch (e) {
console.warn('Imagery trace: getImageData failed (canvas tainted?). Run app with npm start.', e);
return null;
}
const spanM = Math.max(maxX - minX, maxY - minY);
const minAreaWorld = spanM < 180 ? 6 : (spanM < 350 ? 12 : MIN_AREA_WORLD_M2);
const minContourPx = ow >= 1024 ? 14 : MIN_CONTOUR_PIXELS;
const brightness = options && options.brightness != null ? options.brightness : 0;
const contrast = options && options.contrast != null ? options.contrast : 1;
const useThreshold = options && options.useThreshold;
const thresholdBlack = options && options.thresholdBlack != null ? options.thresholdBlack : 160;
const sobelFactor = (options && options.sobelFactor != null) ? options.sobelFactor : 0.04;
const buildingFootprints = options && options.buildingFootprints;
const traceFences = options && options.traceFences;
const roofBright = options && options.roofBright != null ? options.roofBright : 180;
const gray = grayscale(id.data, ow, oh);
let blurred = blur(gray, ow, oh);
blurred = blur(blurred, ow, oh);
const tuned = applyBrightnessContrast(blurred, ow, oh, brightness, contrast);
let polylines = [];
let fencePolylines = [];
function runEdgePass(edge) {
const dilated = dilateEdge(edge, ow, oh);
return findContours(dilated, ow, oh);
}
if (buildingFootprints) {
polylines = extractBuildingFootprintsFromImagery(id.data, blurred, ow, oh, minX, maxX, minY, maxY, {
roofBright: roofBright,
brightness: brightness,
contrast: contrast
});
const worldAreaM2 = (maxX - minX) * (maxY - minY);
const spanM = Math.max(maxX - minX, maxY - minY);
const minAreaM2 = spanM <= 140
? Math.max(40, worldAreaM2 * 0.01)
: Math.max(80, worldAreaM2 * 0.0025);
polylines = filterBuildingFootprints(polylines, minAreaM2);
if (traceFences) {
fencePolylines = extractFenceLinesFromImagery(tuned, ow, oh, minX, maxX, minY, maxY, options, polylines);
}
return { buildings: polylines, fences: fencePolylines };
}
if (!buildingFootprints) {
if (useThreshold) {
const edge = runEdgePass(thresholdEdges(tuned, ow, oh, thresholdBlack));
polylines = collectPolylinesFromContours(edge, ow, oh, minX, maxX, minY, maxY, options, minContourPx, minAreaWorld);
}
if (polylines.length === 0) {
const stretched = contrastStretch(tuned, ow, oh);
const factors = [sobelFactor, sobelFactor * 0.65, 0.025, 0.018];
for (let fi = 0; fi < factors.length && polylines.length === 0; fi++) {
const contours = runEdgePass(sobelThreshold(stretched, ow, oh, null, factors[fi]));
polylines = collectPolylinesFromContours(contours, ow, oh, minX, maxX, minY, maxY, options, minContourPx, minAreaWorld);
}
}
if (polylines.length === 0 && useThreshold) {
const stretched = contrastStretch(tuned, ow, oh);
const edge = runEdgePass(thresholdEdges(stretched, ow, oh, Math.max(50, thresholdBlack - 25)));
polylines = collectPolylinesFromContours(edge, ow, oh, minX, maxX, minY, maxY, options, minContourPx, minAreaWorld * 0.5);
}
}
if (traceFences && polylines.length) {
fencePolylines = extractFenceLinesFromImagery(tuned, ow, oh, minX, maxX, minY, maxY, options, []);
return { buildings: polylines, fences: fencePolylines };
}
return polylines;
}
async function detectLotsFromImagery() {
if (!centerOrigin || !showSatellite) {
setStatus('Turn on satellite imagery and load a map first.', true);
return;
}
const minAreaWorld = 80;
if (detectionRect) {
const r = detectionRect;
const detectSpec = extentToImagePixels(r.minX, r.maxX, r.minY, r.maxY, 400);
const ow = detectSpec.width, oh = detectSpec.height;
setStatus('Loading satellite in selected area…');
const off = await drawSatelliteForExtent(r.minX, r.maxX, r.minY, r.maxY, ow, oh);
if (!off) { setStatus('Could not load imagery for area.', true); draw(); return; }
setStatus('Detecting boundaries in area…');
const octx = off.getContext('2d');
const id = octx.getImageData(0, 0, ow, oh);
const gray = grayscale(id.data, ow, oh);
const blurred = blur(gray, ow, oh);
let edge = sobelThreshold(blurred, ow, oh, null);
edge = dilateEdge(edge, ow, oh);
const contours = findContours(edge, ow, oh);
let added = 0;
contours.forEach((contour) => {
const world = contourPixelsToWorldInRect(contour, ow, oh, r.minX, r.maxX, r.minY, r.maxY);
const simplified = douglasPeucker(world, 0.6);
const area = polygonArea(simplified);
if (area >= minAreaWorld && simplified.length >= 3) {
lots.push(simplified);
added++;
}
});
setStatus(added > 0 ? 'Detected ' + added + ' lot(s) in selected area.' : 'No lot found in area. Try a different region or draw by hand.', added === 0, added > 0);
draw();
return;
}
const cw = canvas.width, ch = canvas.height;
const scaleDetect = Math.min(1, MAX_DETECT_SIZE / Math.max(cw, ch));
const ow = (cw * scaleDetect) | 0, oh = (ch * scaleDetect) | 0;
if (ow < 20 || oh < 20) { setStatus('Canvas too small.', true); return; }
const off = document.createElement('canvas');
off.width = ow;
off.height = oh;
const octx = off.getContext('2d');
setStatus('Loading satellite tiles…');
await drawSatelliteToContext(octx, ow, oh, scaleDetect);
setStatus('Detecting boundaries…');
const id = octx.getImageData(0, 0, ow, oh);
const gray = grayscale(id.data, ow, oh);
const blurred = blur(gray, ow, oh);
let edge = sobelThreshold(blurred, ow, oh, null);
edge = dilateEdge(edge, ow, oh);
const contours = findContours(edge, ow, oh);
const scaleBackX = cw / ow, scaleBackY = ch / oh;
let added = 0;
contours.forEach((contour) => {
const world = contour.map((p) => {
const sx = p.x * scaleBackX, sy = p.y * scaleBackY;
return screenToWorld(sx, sy);
});
const simplified = douglasPeucker(world, 0.8);
const area = polygonArea(simplified);
if (area >= minAreaWorld && simplified.length >= 3) {
lots.push(simplified);
added++;
}
});
if (added === 0 && osmData && osmData.elements) {
let osmLots = getOSMSiteBoundaryAsLot(osmData, centerOrigin);
if (osmLots.length === 0) osmLots = getOSMLotsAsPolygons(osmData, centerOrigin);
const SNAP_RADIUS = 14;
function worldToDetectPx(wx, wy) {
const sx = offsetX + wx * scale;
const sy = offsetY - wy * scale;
return { x: (sx * scaleDetect) | 0, y: (sy * scaleDetect) | 0 };
}
function detectPxToWorld(px, py) {
const sx = px / scaleDetect, sy = py / scaleDetect;
return { x: (sx - offsetX) / scale, y: (offsetY - sy) / scale };
}
function snapToNearestEdge(px, py) {
if (edge[py * ow + px] === 255) return { x: px, y: py };
for (let r = 1; r <= SNAP_RADIUS; r++) {
for (let dy = -r; dy <= r; dy++) {
for (let dx = -r; dx <= r; dx++) {
if (dx * dx + dy * dy > r * r) continue;
const nx = px + dx, ny = py + dy;
if (nx < 1 || nx >= ow - 1 || ny < 1 || ny >= oh - 1) continue;
if (edge[ny * ow + nx] === 255) return { x: nx, y: ny };
}
}
}
return { x: px, y: py };
}
osmLots.forEach((poly) => {
const snapped = poly.map((v) => {
const px = worldToDetectPx(v.x, v.y);
const q = snapToNearestEdge(px.x, px.y);
return detectPxToWorld(q.x, q.y);
});
lots.push(snapped);
added++;
});
setStatus(added > 0 ? 'Used site boundary snapped to imagery edges. Clear lots to try again.' : 'No lot boundaries detected. Try drawing by hand or zoom in on clearer imagery.', added === 0, added > 0);
} else {
setStatus('Detected ' + added + ' lot(s). Clear lots to try again.', false, true);
}
draw();
}
function rectToPolygon(r) {
return [
{ x: r.minX, y: r.minY },
{ x: r.maxX, y: r.minY },
{ x: r.maxX, y: r.maxY },
{ x: r.minX, y: r.maxY }
];
}
function polygonBounds(poly) {
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
poly.forEach(function(p) {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
});
return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
}
function getActiveBoundary() {
if (detectionRect) {
return { poly: rectToPolygon(detectionRect), bounds: detectionRect, label: 'selected area' };
}
if (lots.length) {
const poly = lots[lots.length - 1];
if (poly && poly.length >= 3) {
return { poly: poly, bounds: polygonBounds(poly), label: 'drawn lot' };
}
}
return null;
}
function polyInsideBoundary(poly, boundary) {
if (!poly || poly.length < 1 || !boundary) return false;
const c = polyCentroid(poly);
if (pointInPolygon(c.x, c.y, boundary)) return true;
let hits = 0;
for (let i = 0; i < poly.length; i++) {
if (pointInPolygon(poly[i].x, poly[i].y, boundary)) hits++;
}
return hits >= Math.min(3, poly.length);
}
async function detectBuildingsInBoundary() {
if (!centerOrigin) {
setStatus('Go to an address first, then select a detection area or draw a lot.', true);
return;
}
const boundary = getActiveBoundary();
if (!boundary) {
setStatus('Select a detection area (blue box) or draw a lot first, then detect buildings in that boundary.', true);
return;
}
const sat = document.getElementById('chkSatellite');
if (sat && !sat.checked) {
sat.checked = true;
showSatellite = true;
}
const r = boundary.bounds;
const spanM = Math.max(r.maxX - r.minX, r.maxY - r.minY);
if (spanM < 8) {
setStatus('Boundary is too small. Draw a larger area around the buildings.', true);
return;
}
setStatus('Detecting buildings inside ' + boundary.label + '…');
const spec = extentToImagePixels(r.minX, r.maxX, r.minY, r.maxY, getTracePixelSize(spanM));
const off = await drawSatelliteForExtent(r.minX, r.maxX, r.minY, r.maxY, spec.width, spec.height);
if (!off) {
setStatus('Could not load satellite tiles for that boundary.', true);
draw();
return;
}
const octx = off.getContext('2d');
let id;
try {
id = octx.getImageData(0, 0, off.width, off.height);
} catch (e) {
setStatus('Canvas access blocked. Run with Start.bat and open http://localhost:3456.', true);
return;
}
const gray = grayscale(id.data, off.width, off.height);
const blurred = blur(gray, off.width, off.height);
const tune = getTraceTuneOptions();
let buildings = extractBuildingFootprintsFromImagery(id.data, blurred, off.width, off.height, r.minX, r.maxX, r.minY, r.maxY, tune);
buildings = buildings.filter(function(poly) { return polyInsideBoundary(poly, boundary.poly); });
let osmN = 0;
if (osmData && centerOrigin && typeof getOSMBuildingFootprints === 'function') {
const osm = getOSMBuildingFootprints(osmData, centerOrigin).filter(function(poly) {
return polyInsideBoundary(poly, boundary.poly);
});
previewOsmBuildingPolylines = osm;
osmN = osm.length;
}
previewImageryTracePolylines = buildings;
const n = buildings.length;
setStatus(
n > 0
? n + ' building(s) inside ' + boundary.label + (osmN ? ' (+' + osmN + ' OSM)' : '') + '. Export DXF to keep them on IMAGERY_BUILDINGS.'
: 'No buildings found in ' + boundary.label + '. Zoom to the roofs, use Esri, lower roof threshold, or draw the lot tighter around the building.',
n === 0,
n > 0
);
draw();
}
const btnDetectLots = document.getElementById('btnDetectLots');
btnDetectLots.addEventListener('click', () => {
btnDetectLots.disabled = true;
detectLotsFromImagery().finally(() => { btnDetectLots.disabled = false; });
});
const btnDetectBuildings = document.getElementById('btnDetectBuildings');
btnDetectBuildings.addEventListener('click', () => {
btnDetectBuildings.disabled = true;
detectBuildingsInBoundary().finally(() => { btnDetectBuildings.disabled = false; });
});
const btnSelectArea = document.getElementById('btnSelectArea');
btnSelectArea.addEventListener('click', () => {
if (selectAreaMode) {
selectAreaMode = false;
rectStart = null;
rectCurrent = null;
btnSelectArea.textContent = 'Select detection area';
btnSelectArea.classList.add('secondary');
canvas.style.cursor = 'grab';
} else {
selectAreaMode = true;
btnSelectArea.textContent = 'Cancel';
btnSelectArea.classList.remove('secondary');
canvas.style.cursor = 'crosshair';
}
draw();
});
const btnClearArea = document.getElementById('btnClearArea');
btnClearArea.addEventListener('click', () => {
detectionRect = null;
document.getElementById('btnAddSelectionAsLot').disabled = true;
setStatus('Detection area cleared. Detect will run on full view.');
draw();
});
const btnSetImageBounds = document.getElementById('btnSetImageBounds');
btnSetImageBounds.addEventListener('click', () => {
if (imageBoundsMode) {
imageBoundsMode = false;
imageBoundsStart = null;
imageBoundsCurrent = null;
btnSetImageBounds.textContent = 'Set image bounds';
btnSetImageBounds.classList.add('secondary');
canvas.style.cursor = 'grab';
} else {
imageBoundsMode = true;
btnSetImageBounds.textContent = 'Cancel';
btnSetImageBounds.classList.remove('secondary');
canvas.style.cursor = 'crosshair';
}
draw();
});
const btnClearImageBounds = document.getElementById('btnClearImageBounds');
btnClearImageBounds.addEventListener('click', () => {
imageBoundsRect = null;
setStatus('Image bounds cleared. Export will use current view extent for satellite image.');
draw();
});
const btnAddSelectionAsLot = document.getElementById('btnAddSelectionAsLot');
btnAddSelectionAsLot.addEventListener('click', () => {
if (!detectionRect) return;
const r = detectionRect;
const poly = [
{ x: r.minX, y: r.minY },
{ x: r.maxX, y: r.minY },
{ x: r.maxX, y: r.maxY },
{ x: r.minX, y: r.maxY }
];
lots.push(poly);
setStatus('Added selection as one lot. Use Edit lots to adjust corners if needed.', false, true);
draw();
});
function setStatus(msg, isError, isSuccess) {
status.textContent = msg;
status.classList.toggle('error', !!isError);
status.classList.toggle('success', !!isSuccess);
}
function isGoogleEarthSearchUrl(input) {
return /earth\.google\.com\/web\/search\//i.test(String(input).trim());
}
function extractGoogleEarthSearchQuery(input) {
const m = String(input).trim().match(/earth\.google\.com\/web\/search\/([^/#?]+)/i);
if (!m || !m[1]) return null;
const raw = m[1].replace(/\/$/, '');
const decoded = decodeURIComponent(raw.replace(/\+/g, ' ')).trim();
return decoded || null;
}
async function resolveLocation(input) {
let s = String(input).trim();
if (typeof isGoogleMapsLink === 'function' && isGoogleMapsLink(s)) {
setStatus('Reading Google Maps pin…');
const rr = await fetch('/api/maps-pin?url=' + encodeURIComponent(s));
const pin = await rr.json();
if (!rr.ok) throw new Error(pin.error || 'Could not read that Maps link.');
return {
lat: pin.lat,
lon: pin.lon,
viewMeters: pin.viewMeters,
fromUrl: true,
displayName: pin.display_name || ''
};
}
if (isGoogleEarthSearchUrl(s)) {
const coords = extractCoordinates(s);
if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true };
const earthSearch = extractGoogleEarthSearchQuery(s);
if (earthSearch !== null) {
const coordLike = /^-?\d+\.?\d*\s*,\s*-?\d+\.?\d*$/.test(earthSearch);
if (coordLike) {
const [lat, lon] = earthSearch.split(',').map((n) => parseFloat(n.trim()));
if (!isNaN(lat) && !isNaN(lon)) return { lat, lon, viewMeters: undefined, fromUrl: true };
}
setStatus('Looking up address…');
const res = await fetch('/api/geocode?q=' + encodeURIComponent(earthSearch));
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Geocoding failed');
return { lat: data.lat, lon: data.lon, viewMeters: undefined, fromUrl: false, displayName: data.display_name };
}
}
const coords = extractCoordinates(s);
if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true };
const mapsAddress = typeof extractAddressFromMapsUrl === 'function' ? extractAddressFromMapsUrl(s) : null;
const query = mapsAddress || s;
if (/^https?:/i.test(query)) {
throw new Error('Could not read a pin from that link. Open Google Maps, click the building, copy the URL, and paste that — or type the street address.');
}
setStatus('Looking up address…');
const res = await fetch('/api/geocode?q=' + encodeURIComponent(query));
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Geocoding failed');
return { lat: data.lat, lon: data.lon, viewMeters: undefined, fromUrl: false, displayName: data.display_name };
}
function getAreaRadiusMeters(loc) {
const sel = document.getElementById('areaSize');
const mode = sel ? sel.value : '400';
if (mode !== 'auto') return parseInt(mode, 10) || 400;
if (loc.viewMeters != null) return Math.min(loc.viewMeters, 1200);
return 400;
}
function mergeOsmResults(results) {
const seen = new Set();
const elements = [];
results.forEach(function(data) {
(data.elements || []).forEach(function(el) {
const key = el.type + '/' + el.id;
if (seen.has(key)) return;
seen.add(key);
elements.push(el);
});
});
return { version: 0.6, elements: elements };
}
async function fetchOsmForBbox(bbox, layers, options) {
const quiet = options && options.quiet;
const planRes = await fetch('/api/overpass/plan', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(bbox)
});
const plan = await planRes.json();
if (!planRes.ok) throw new Error(plan.error || 'Could not plan map fetch');
const tiles = plan.tiles || [bbox];
const results = [];
for (let i = 0; i < tiles.length; i++) {
if (!quiet) {
setStatus(tiles.length > 1
? 'Fetching map data (' + (i + 1) + ' of ' + tiles.length + ') — throttled to avoid rate limits…'
: 'Fetching map data (throttled so OSM stays available)…');
}
let lastErr = null;
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch('/api/overpass', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...tiles[i], layers: layers })
});
let data = {};
try { data = await res.json(); } catch (_) {}
if (res.ok) {
results.push(data);
lastErr = null;
break;
}
lastErr = new Error(data.error || 'Request failed');
lastErr.status = res.status;
const waitMs = data.retryAfterMs || (res.status === 429 ? 8000 : 2500 * (attempt + 1));
if (attempt < 2 && (res.status === 429 || res.status === 502 || res.status === 503)) {
if (!quiet) setStatus('Map server busy — waiting ' + Math.round(waitMs / 1000) + 's then retrying…');
await new Promise(function(r) { setTimeout(r, waitMs); });
continue;
}
throw lastErr;
}
if (lastErr) throw lastErr;
}
const merged = mergeOsmResults(results);
if (tiles.length > 1) {
merged._meta = { tiles: tiles.length, elementCount: merged.elements.length };
}
return merged;
}
function enableDrawingTools() {
btnFit.disabled = false;
btnExport.disabled = false;
btnDrawLot.disabled = false;
btnCloseLot.disabled = false;
btnClearLots.disabled = false;
document.getElementById('btnEditLots').disabled = false;
document.getElementById('btnDetectLots').disabled = false;
document.getElementById('btnDetectBuildings').disabled = false;
document.getElementById('btnSelectArea').disabled = false;
document.getElementById('btnClearArea').disabled = false;
document.getElementById('btnSetImageBounds').disabled = false;
document.getElementById('btnClearImageBounds').disabled = false;
}
function bboxFromCenter(lat, lon, radiusMeters) {
const cosLat = Math.cos((lat * Math.PI) / 180);
viewRadiusLatDeg = radiusMeters / 111320;
viewRadiusLonDeg = radiusMeters / (111320 * Math.max(0.01, cosLat));
return {
south: lat - viewRadiusLatDeg,
west: lon - viewRadiusLonDeg,
north: lat + viewRadiusLatDeg,
east: lon + viewRadiusLonDeg
};
}
btnLoad.addEventListener('click', async () => {
const input = urlInput.value.trim();
if (!input) {
setStatus('Enter an address, place name, or paste a Google Maps / Earth link.', true);
return;
}
btnLoad.disabled = true;
try {
const loc = await resolveLocation(input);
centerOrigin = { lat: loc.lat, lon: loc.lon };
resetTileZoomCap();
const radiusM = getAreaRadiusMeters(loc);
const bbox = bboxFromCenter(loc.lat, loc.lon, radiusM);
const layers = getLayerOptions();
const data = await fetchOsmForBbox(bbox, layers);
setStatus('Drawing preview…');
await new Promise(function(resolve) { requestAnimationFrame(resolve); });
osmData = data;
if (!osmData.elements || osmData.elements.length === 0) {
enableDrawingTools();
setStatus('No OSM features in this area. Satellite is still available — generate drawing from imagery and Export DXF.', true);
return;
}
previewData = buildPreviewData(osmData, centerOrigin, layers);
previewImageryTracePolylines = [];
previewImageryFencePolylines = [];
enableDrawingTools();
fitView();
zoomToSiteView(getSiteZoomMeters());
if (showSatellite) await probeNativeMaxZoom();
let msg = loc.fromUrl ? 'Preview loaded. Click Export DXF to download.' : 'Found: ' + (loc.displayName || '').split(',').slice(0, 2).join(',') + '. Preview loaded.';
if (data._meta && data._meta.tiles > 1) {
msg += ' (' + data._meta.elementCount + ' features from ' + data._meta.tiles + ' map tiles)';
} else if (osmData.elements) {
msg += ' (' + osmData.elements.length + ' features)';
}
setStatus(msg, false, true);
if (document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked) {
updatePreviewImageryTrace();
}
} catch (e) {
if (centerOrigin) enableDrawingTools();
const hint = e.status === 429
? ' OSM is rate-limited. Wait, then retry Load preview — or use satellite + Generate drawing from imagery and Export DXF now.'
: ' You can still use satellite imagery, Generate drawing from imagery, and Export DXF without OSM.';
setStatus((e.message || 'Failed to load OSM map data.') + hint, true);
} finally {
btnLoad.disabled = false;
}
});
btnFit.addEventListener('click', fitView);
btnExport.addEventListener('click', async () => {
if (!centerOrigin) {
setStatus('Go to an address or load a preview first.', true);
return;
}
if (!osmData) osmData = { elements: [] };
const baseName = 'Map_RailFixed_' + centerOrigin.lat + '_' + centerOrigin.lon;
const dxfFileName = baseName + '.dxf';
const pngFileName = baseName + '.png';
const IMAGERY_TRACE_MAX = 2048;
const IMAGE_MAX_EDGE = 2048;
const exportExtent = getTraceExtentInMeters();
const useImageryTrace = document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked;
const useML = document.getElementById('chkServerML') && document.getElementById('chkServerML').checked;
const useOSMSnap = document.getElementById('chkOSMSnap') && document.getElementById('chkOSMSnap').checked;
let imageryTracePolylines = null;
let imageryFencePolylines = null;
let imageryTraceClassified = null;
let imageryTraceError = null;
if (useImageryTrace) {
setStatus(useML ? 'Exporting (server-side ML segmentation)…' : 'Exporting (loading and vectorizing satellite imagery)…');
try {
const traceSpec = extentToImagePixels(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, IMAGERY_TRACE_MAX);
const traceCanvas = await drawSatelliteForExtent(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, traceSpec.width, traceSpec.height);
if (!traceCanvas) {
imageryTraceError = 'Could not load imagery tiles.';
} else if (useML) {
const form = new FormData();
const blob = await new Promise((res) => traceCanvas.toBlob(res, 'image/png'));
form.append('image', blob, 'image.png');
form.append('minX', String(exportExtent.minX));
form.append('maxX', String(exportExtent.maxX));
form.append('minY', String(exportExtent.minY));
form.append('maxY', String(exportExtent.maxY));
if (document.getElementById('chkVtracer') && document.getElementById('chkVtracer').checked) form.append('useVtracer', '1');
if (document.getElementById('chkThreshold') && document.getElementById('chkThreshold').checked) form.append('useThreshold', '1');
appendTraceTuneToForm(form);
const r = await fetch('/api/segment', { method: 'POST', body: form });
const data = await r.json();
if (!r.ok) {
imageryTraceError = data.error || 'ML server error';
} else {
let b = (data.buildings || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
let t = (data.trees || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
let l = (data.lots || []).map((p) => p.map((pt) => ({ x: pt.x, y: pt.y })));
if (useOSMSnap && osmData && centerOrigin) {
const nodes = getOSMNodesInMeters(osmData, centerOrigin);
b = snapTracePolylinesToOSM(b, osmData, nodes, 1.5);
t = snapTracePolylinesToOSM(t, osmData, nodes, 1.5);
l = snapTracePolylinesToOSM(l, osmData, nodes, 1.5);
}
imageryTraceClassified = { buildings: b, trees: t, lots: l };
}
} else {
const raw = vectorizeImageryToPolylines(traceCanvas, exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, getTraceTuneOptions());
if (raw === null) imageryTraceError = 'Canvas access blocked. Run with npm start and open http://localhost.';
else if (raw.buildings) {
let buildings = raw.buildings;
imageryFencePolylines = raw.fences || [];
if (useOSMSnap && osmData && centerOrigin) {
buildings = snapTracePolylinesToOSM(buildings, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5);
}
imageryTracePolylines = buildings;
} else {
imageryTracePolylines = useOSMSnap && osmData && centerOrigin
? snapTracePolylinesToOSM(raw, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
: raw;
}
}
} catch (err) {
imageryTraceError = err.message || (useML ? 'ML request failed' : 'Vectorization failed.');
}
}
if (!useImageryTrace) setStatus('Exporting (building satellite image)…');
await probeNativeMaxZoom(true);
if (!imageryTraceClassified && (!imageryTracePolylines || !imageryTracePolylines.length) && previewImageryTracePolylines.length) {
imageryTracePolylines = previewImageryTracePolylines;
}
if ((!imageryFencePolylines || !imageryFencePolylines.length) && previewImageryFencePolylines.length) {
imageryFencePolylines = previewImageryFencePolylines;
}
const imgSpec = extentToImagePixels(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, IMAGE_MAX_EDGE);
const imgCanvas = await drawSatelliteForExtent(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, imgSpec.width, imgSpec.height);
let dxfContent = generateHighDetailDXF(osmData, centerOrigin, getLayerOptions(), exportExtent);
if (imageryTraceClassified) {
if (imageryTraceClassified.buildings.length) dxfContent = appendImageryTraceToDXF(dxfContent, imageryTraceClassified.buildings, 0.2, 0.5, 'IMAGERY_BUILDINGS');
if (imageryTraceClassified.trees.length) dxfContent = appendImageryTraceToDXF(dxfContent, imageryTraceClassified.trees, 0.2, 0.5, 'IMAGERY_TREES');
if (imageryTraceClassified.lots.length) dxfContent = appendImageryTraceToDXF(dxfContent, imageryTraceClassified.lots, 0.2, 0.5, 'IMAGERY_LOTS');
} else if (imageryTracePolylines && imageryTracePolylines.length > 0) {
dxfContent = appendImageryTraceToDXF(dxfContent, imageryTracePolylines, 0.2, 0.5, 'IMAGERY_BUILDINGS');
}
if (imageryFencePolylines && imageryFencePolylines.length > 0) {
dxfContent = appendImageryTraceToDXF(dxfContent, imageryFencePolylines, 0.2, 1, 'IMAGERY_FENCES');
}
dxfContent = appendLotsToDXF(dxfContent, lots);
const pgwFileName = baseName + '.pgw';
if (imgCanvas) {
dxfContent = appendSatelliteImageToDXF(dxfContent, pngFileName, exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height);
}
if (imgCanvas && typeof JSZip !== 'undefined') {
const zip = new JSZip();
zip.file(dxfFileName, dxfContent, { binary: false });
const pngBlob = await new Promise((res) => imgCanvas.toBlob(res, 'image/png'));
zip.file(pngFileName, pngBlob, { binary: true });
zip.file(pgwFileName, generateWorldFilePgw(exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height, false), { binary: false });
const zipBlob = await zip.generateAsync({ type: 'blob' });
const zipUrl = URL.createObjectURL(zipBlob);
const aZip = document.createElement('a');
aZip.href = zipUrl;
aZip.download = baseName + '.zip';
aZip.click();
URL.revokeObjectURL(zipUrl);
} else {
const dxfBlob = new Blob([dxfContent], { type: 'application/dxf' });
const dxfUrl = URL.createObjectURL(dxfBlob);
const aDxf = document.createElement('a');
aDxf.href = dxfUrl;
aDxf.download = dxfFileName;
aDxf.click();
URL.revokeObjectURL(dxfUrl);
if (imgCanvas) {
const pngBlob = await new Promise((res) => imgCanvas.toBlob(res, 'image/png'));
const pngUrl = URL.createObjectURL(pngBlob);
const aPng = document.createElement('a');
aPng.href = pngUrl;
aPng.download = pngFileName;
aPng.click();
URL.revokeObjectURL(pngUrl);
const pgwBlob = new Blob([generateWorldFilePgw(exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height, false)], { type: 'text/plain' });
const pgwUrl = URL.createObjectURL(pgwBlob);
const aPgw = document.createElement('a');
aPgw.href = pgwUrl;
aPgw.download = pgwFileName;
aPgw.click();
URL.revokeObjectURL(pgwUrl);
}
}
let statusMsg = imgCanvas && typeof JSZip !== 'undefined'
? 'Downloaded ' + baseName + '.zip. Unzip and open the DXF — satellite is already attached and scaled to the selected extent (1 unit = 1 meter).'
: imgCanvas
? 'Downloaded ' + dxfFileName + ' and ' + pngFileName + '. Keep both in the same folder so CAD can show the attached image.'
: 'Downloaded: ' + dxfFileName;
if (imgCanvas) {
statusMsg += ' Image extent: ' + imgSpec.widthMeters.toFixed(1) + ' m × ' + imgSpec.heightMeters.toFixed(1)
+ ' m (' + imgSpec.width + '×' + imgSpec.height + ' px, ' + imgSpec.metersPerPixel.toFixed(4) + ' m/px).';
statusMsg += ' Cyan IMAGE_BOUNDS box should match the satellite and trace.';
}
if (useImageryTrace) {
if (imageryTraceError) statusMsg += ' Imagery trace: ' + imageryTraceError;
else if (imageryTraceClassified) {
const n = imageryTraceClassified.buildings.length + imageryTraceClassified.trees.length + imageryTraceClassified.lots.length;
statusMsg += ' Imagery trace (ML): ' + n + ' features on IMAGERY_BUILDINGS, IMAGERY_TREES, IMAGERY_LOTS.' + (useOSMSnap ? ' Snapped to OSM.' : '');
} else if (imageryTracePolylines && imageryTracePolylines.length > 0) statusMsg += ' Imagery trace: ' + imageryTracePolylines.length + ' polylines on IMAGERY_TRACE.' + (useOSMSnap ? ' Snapped to OSM.' : '');
else statusMsg += ' Imagery trace: no edges detected—try zooming in.';
}
setStatus(statusMsg, false, true);
});
function onResize() {
const wrap = document.getElementById('canvasWrap');
canvas.width = wrap.clientWidth;
canvas.height = 400;
if (previewData.length) fitView();
else draw();
}
window.addEventListener('resize', onResize);
onResize();
})();
</script>
</body>
</html>