Files
MAPS-to-DXF-standalone/public/index.html
T
Michael-A-SloanandCursor 7c20a404bf feat: add standalone maps-to-dxf web application
Node.js/Express server with web GUI for converting Google Maps links to DXF files. Includes optional Python ML server for satellite lot detection.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-25 15:30:38 -04:00

1682 lines
71 KiB
HTML

<!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"] {
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;
}
.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; }
</style>
</head>
<body>
<h1>MAPS to DXF</h1>
<p class="legend">Enter an <strong>address or place name</strong>, or paste a link: <strong>Google Earth</strong> <code>https://earth.google.com/web/search/</code> (search URL), or Google Maps / Earth view URL. Load preview, then export DXF.</p>
<label for="url">Address, place name, or map URL</label>
<input type="text" id="url" placeholder="e.g. 123 Main St or https://earth.google.com/web/search/Your+Search or maps/@40.7128,-74.0060" autocomplete="off" />
<div class="row">
<button id="btnLoad">Load preview</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="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>
</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="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> embeds the satellite image in a single ZIP (unzip to use in CAD). Use <strong>Set image bounds</strong> (orange box) to choose the satellite image extent. Center = map origin. <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 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 = [];
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 = true;
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;
});
return opts;
}
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 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 Math.max(0, Math.min(19, 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 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 Math.max(0, Math.min(19, 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, size) {
return new Promise((resolve) => {
if (!centerOrigin) { resolve(null); return; }
const off = document.createElement('canvas');
off.width = size;
off.height = size;
const octx = off.getContext('2d');
octx.fillStyle = '#8b8b8b';
octx.fillRect(0, 0, size, size);
const w = maxX - minX, h = maxY - minY;
const z = getTileZoomForExtent(minX, maxX, minY, maxY, size);
const tiles = getTilesInViewForExtent(minX, maxX, minY, maxY, z);
let pending = tiles.length;
if (pending === 0) { resolve(off); return; }
function done() {
pending--;
if (pending === 0) resolve(off);
}
tiles.forEach(({ tx, ty, z: zz }) => {
getTileImage(zz, tx, ty, (img) => {
if (!img.complete || !img.naturalWidth) { 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) * size;
const pxTop = ((maxY - tl.y) / h) * size;
const pxW = ((br.x - tl.x) / w) * size;
const pxH = ((tl.y - br.y) / h) * size;
octx.drawImage(img, 0, 0, TILE_SIZE, TILE_SIZE, pxLeft, pxTop, pxW, pxH);
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 (!img.complete || !img.naturalWidth) { 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 getTileImage(z, tx, ty, onLoad, onError) {
const key = z + '_' + tx + '_' + ty;
if (tileCache[key]) {
if (tileCache[key].complete && tileCache[key].naturalWidth) onLoad(tileCache[key]);
else {
tileCache[key].addEventListener('load', () => onLoad(tileCache[key]));
tileCache[key].addEventListener('error', () => (onError && onError()));
}
return;
}
const img = new Image();
img.crossOrigin = 'anonymous';
tileCache[key] = img;
img.addEventListener('load', () => onLoad(img));
img.addEventListener('error', () => (onError && onError()));
img.src = '/api/tile/' + z + '/' + ty + '/' + tx;
}
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 (!img.complete || !img.naturalWidth) { 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 (!previewImageryTracePolylines.length) return;
ctx.strokeStyle = '#00d4aa';
ctx.lineWidth = 1.5;
ctx.setLineDash([3, 3]);
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.stroke();
});
ctx.setLineDash([]);
}
function draw() {
const cw = canvas.width, ch = canvas.height;
ctx.fillStyle = '#313244';
ctx.fillRect(0, 0, cw, ch);
if (!previewData.length) {
ctx.fillStyle = '#a6adc8';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Load a map to see preview', cw / 2, ch / 2);
return;
}
if (showSatellite && centerOrigin) {
drawSatelliteLayer();
} else {
drawVectorLayer();
drawImageryTraceLayer();
drawLotsLayer();
}
}
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;
draw();
}
function zoomAt(mx, my, factor) {
const wx = (mx - offsetX) / scale;
const wy = (offsetY - my) / scale;
scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale * factor));
offsetX = mx - wx * scale;
offsetY = my + wy * scale;
draw();
}
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. Click "Add selection as lot" to use this as one property lot, or "Detect lots" to auto-detect inside it.');
draw();
return;
}
if (editLotMode) selectedVertex = null;
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 (!previewData.length) 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;
draw();
});
const PREVIEW_TRACE_SIZE = 512;
async function updatePreviewImageryTrace() {
const chk = document.getElementById('chkImageryTrace');
if (!chk || !chk.checked || !centerOrigin || !previewData.length) return;
const useML = document.getElementById('chkServerML') && document.getElementById('chkServerML').checked;
const useOSMSnap = document.getElementById('chkOSMSnap') && document.getElementById('chkOSMSnap').checked;
setStatus(useML ? 'Server-side ML segmentation…' : 'Computing imagery trace preview…');
try {
const extent = getMapExtentInMeters();
const traceCanvas = await drawSatelliteForExtent(extent.minX, extent.maxX, extent.minY, extent.maxY, PREVIEW_TRACE_SIZE);
if (!traceCanvas || !document.getElementById('chkImageryTrace').checked) {
previewImageryTracePolylines = [];
draw();
return;
}
let polylines = [];
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');
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, { douglasEps: 0.65, minPolyLengthMeters: 0.05, sobelFactor: 0.04 });
if (raw === null) {
previewImageryTracePolylines = [];
setStatus('Imagery trace blocked (canvas). Run the app with npm start and open http://localhost:' + (window.location.port || '3456') + '.', true);
draw();
return;
}
const filtered = filterImageryPolylinesForLotDrawing(raw);
const clientPolylines = useOSMSnap && osmData && centerOrigin
? snapTracePolylinesToOSM(filtered.all, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
: filtered.all;
polylines = clientPolylines;
}
previewImageryTracePolylines = polylines;
const n = previewImageryTracePolylines.length;
setStatus(n > 0 ? 'Imagery trace: ' + n + ' polylines. Export DXF to include.' + (useOSMSnap ? ' (Snapped to OSM)' : '') : 'No edges detected. Try "Show satellite imagery" and zoom in.', n === 0, n > 0);
} catch (err) {
previewImageryTracePolylines = [];
setStatus('Imagery trace failed: ' + (err.message || 'unknown error'), true);
}
draw();
}
document.getElementById('chkImageryTrace').addEventListener('change', (e) => {
if (e.target.checked) {
setStatus('Imagery trace on: computing preview…', false, true);
updatePreviewImageryTrace();
} else {
previewImageryTracePolylines = [];
setStatus('', false, false);
draw();
}
});
['chkServerML', 'chkVtracer', 'chkThreshold', 'chkOSMSnap'].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 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;
}
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
}));
}
const MIN_CONTOUR_PIXELS = 28; // ignore small contours (cars, HVAC, noise)
const MIN_AREA_WORLD_M2 = 25; // drop contours smaller than ~25 m² (cars, small blobs)
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 gray = grayscale(id.data, ow, oh);
let blurred = blur(gray, ow, oh);
blurred = blur(blurred, ow, oh); // second pass reduces tile-boundary noise
const stretched = contrastStretch(blurred, ow, oh);
const sobelFactor = (options && options.sobelFactor != null) ? options.sobelFactor : 0.04;
let edge = sobelThreshold(stretched, ow, oh, null, sobelFactor);
edge = dilateEdge(edge, ow, oh);
let contours = findContours(edge, ow, oh);
contours = contours.filter((c) => {
let pxLen = 0;
for (let i = 0; i < c.length; i++) {
const a = c[i], b = c[(i + 1) % c.length];
pxLen += Math.hypot(b.x - a.x, b.y - a.y);
}
return pxLen >= MIN_CONTOUR_PIXELS;
});
const minLen = (options && options.minPolyLengthMeters != null) ? options.minPolyLengthMeters : 0.05;
const eps = (options && options.douglasEps != null) ? options.douglasEps : 0.65;
let polylines = [];
contours.forEach((contour) => {
const world = contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY);
const simplified = douglasPeucker(world, eps);
const area = polygonAreaWorld(simplified);
if (area < MIN_AREA_WORLD_M2) return; // skip cars, HVAC, small blobs
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);
});
if (polylines.length === 0 && contours.length > 0) {
edge = sobelThreshold(stretched, ow, oh, null, 0.02);
edge = dilateEdge(edge, ow, oh);
const contours2 = findContours(edge, ow, oh);
contours2.filter((c) => {
let pxLen = 0;
for (let i = 0; i < c.length; i++) {
const a = c[i], b = c[(i + 1) % c.length];
pxLen += Math.hypot(b.x - a.x, b.y - a.y);
}
return pxLen >= MIN_CONTOUR_PIXELS;
}).forEach((contour) => {
const world = contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY);
const simplified = douglasPeucker(world, eps * 1.2);
if (polygonAreaWorld(simplified) >= MIN_AREA_WORLD_M2 && simplified.length >= 2) polylines.push(simplified);
});
}
if (polylines.length === 0 && contours.length > 0) {
contours.forEach((contour) => {
const world = contourPixelsToWorldInRect(contour, ow, oh, minX, maxX, minY, maxY);
const simplified = douglasPeucker(world, 1.0);
if (polygonAreaWorld(simplified) >= MIN_AREA_WORLD_M2 && simplified.length >= 2) polylines.push(simplified);
});
}
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 detectSize = 400;
const ow = detectSize, oh = detectSize;
setStatus('Loading satellite in selected area…');
const off = await drawSatelliteForExtent(r.minX, r.maxX, r.minY, r.maxY, detectSize);
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();
}
const btnDetectLots = document.getElementById('btnDetectLots');
btnDetectLots.addEventListener('click', () => {
btnDetectLots.disabled = true;
detectLotsFromImagery().finally(() => { btnDetectLots.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) {
if (isGoogleEarthSearchUrl(input)) {
const coords = extractCoordinates(input);
if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true };
const earthSearch = extractGoogleEarthSearchQuery(input);
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 Google Earth search…');
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(input);
if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true };
setStatus('Looking up address…');
const res = await fetch('/api/geocode?q=' + encodeURIComponent(input));
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 };
}
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 };
if (loc.viewMeters != null) {
const cosLat = Math.cos((loc.lat * Math.PI) / 180);
viewRadiusLatDeg = loc.viewMeters / 111320;
viewRadiusLonDeg = loc.viewMeters / (111320 * Math.max(0.01, cosLat));
} else {
viewRadiusLatDeg = 0.002;
viewRadiusLonDeg = 0.002 * 1.5;
}
const bbox = {
south: loc.lat - viewRadiusLatDeg,
west: loc.lon - viewRadiusLonDeg,
north: loc.lat + viewRadiusLatDeg,
east: loc.lon + viewRadiusLonDeg
};
setStatus('Fetching map data…');
const res = await fetch('/api/overpass', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(bbox)
});
const data = await res.json();
if (!res.ok) {
setStatus(data.error || 'Request failed', true);
return;
}
osmData = data;
previewData = buildPreviewData(osmData, centerOrigin, getLayerOptions());
previewImageryTracePolylines = [];
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('btnSelectArea').disabled = false;
document.getElementById('btnClearArea').disabled = false;
document.getElementById('btnSetImageBounds').disabled = false;
document.getElementById('btnClearImageBounds').disabled = false;
fitView();
if (document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked) updatePreviewImageryTrace();
else {
const msg = loc.fromUrl ? 'Preview loaded. Click Export DXF to download.' : 'Found: ' + (loc.displayName || '').split(',').slice(0, 2).join(',') + '. Preview loaded.';
setStatus(msg, false, true);
}
} catch (e) {
setStatus(e.message || 'Failed to resolve location.', true);
} finally {
btnLoad.disabled = false;
}
});
btnFit.addEventListener('click', fitView);
btnExport.addEventListener('click', async () => {
if (!osmData || !centerOrigin) {
setStatus('Load a preview first.', true);
return;
}
const baseName = 'Map_RailFixed_' + centerOrigin.lat + '_' + centerOrigin.lon;
const dxfFileName = baseName + '.dxf';
const pngFileName = baseName + '.png';
const IMAGE_SIZE = 1024;
const IMAGERY_TRACE_SIZE = 2048;
const extent = getMapExtentInMeters();
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 imageryTraceClassified = null;
let imageryTraceError = null;
if (useImageryTrace) {
setStatus(useML ? 'Exporting (server-side ML segmentation)…' : 'Exporting (loading and vectorizing satellite imagery)…');
try {
const traceCanvas = await drawSatelliteForExtent(extent.minX, extent.maxX, extent.minY, extent.maxY, IMAGERY_TRACE_SIZE);
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(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');
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, extent.minX, extent.maxX, extent.minY, extent.maxY, { douglasEps: 0.65, minPolyLengthMeters: 0.05, sobelFactor: 0.04 });
if (raw === null) imageryTraceError = 'Canvas access blocked. Run with npm start and open http://localhost.';
else {
const filtered = filterImageryPolylinesForLotDrawing(raw);
imageryTracePolylines = useOSMSnap && osmData && centerOrigin
? snapTracePolylinesToOSM(filtered.all, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
: filtered.all;
}
}
} catch (err) {
imageryTraceError = err.message || (useML ? 'ML request failed' : 'Vectorization failed.');
}
}
const imageExtent = imageBoundsRect || extent;
if (!useImageryTrace) setStatus('Exporting (building satellite image)…');
const imgCanvas = await drawSatelliteForExtent(imageExtent.minX, imageExtent.maxX, imageExtent.minY, imageExtent.maxY, IMAGE_SIZE);
let dxfContent = generateHighDetailDXF(osmData, centerOrigin, getLayerOptions());
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);
}
dxfContent = appendLotsToDXF(dxfContent, lots);
const EMBEDDED_IMAGE_FILENAME = 'satellite.png';
if (imgCanvas) {
dxfContent = appendSatelliteImageToDXF(dxfContent, EMBEDDED_IMAGE_FILENAME, imageExtent.minX, imageExtent.minY, imageExtent.maxX, imageExtent.maxY, IMAGE_SIZE, IMAGE_SIZE);
}
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(EMBEDDED_IMAGE_FILENAME, pngBlob, { binary: true });
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);
}
}
let statusMsg = imgCanvas && typeof JSZip !== 'undefined'
? 'Downloaded ' + baseName + '.zip (DXF + satellite image inside). Unzip and open the DXF in CAD.'
: imgCanvas
? 'Downloaded ' + dxfFileName + ' and ' + pngFileName + '. Keep both in the same folder for CAD.'
: 'Downloaded: ' + dxfFileName;
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>