diff --git a/Start.bat b/Start.bat
index a0ef63d..7126564 100644
--- a/Start.bat
+++ b/Start.bat
@@ -44,6 +44,7 @@ if exist "ml_server\segment_server.py" (
)
echo Starting MAPS to DXF...
+for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":3456" ^| findstr "LISTENING"') do taskkill /PID %%a /F >nul 2>&1
echo Browser will open. Keep this window open while using the app.
if exist "ml_server\segment_server.py" echo (ML server started in the other window - enable "Use server-side ML segmentation" in the app.)
echo.
diff --git a/public/app.js b/public/app.js
index 62865d7..19a19d3 100644
--- a/public/app.js
+++ b/public/app.js
@@ -5,19 +5,36 @@
*/
function extractCoordinates(url) {
const s = String(url).trim();
- // Google Maps: ...@lat,lon... Google Earth Web: ...@lat,lon... or ...@lat,lon,altitudea,distanced...
+ let lat;
+ let lon;
+ const placePins = [];
+ const placePinRegex = /!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/g;
+ let pinMatch;
+ while ((pinMatch = placePinRegex.exec(s)) !== null) {
+ placePins.push({ lat: parseFloat(pinMatch[1]), lon: parseFloat(pinMatch[2]) });
+ }
const coordRegex = /@(-?\d+\.?\d*),(-?\d+\.?\d*)/;
const coordMatch = s.match(coordRegex);
- if (!coordMatch || coordMatch.length < 3) return null;
- const lat = parseFloat(coordMatch[1]);
- const lon = parseFloat(coordMatch[2]);
- let viewMeters = undefined;
- // Google Earth Web: optional altitude (e.g. ,1234a) or distance (e.g. ,50000d) in meters; order may be ,100a,50000d
+ if (placePins.length > 0) {
+ const pin = placePins[placePins.length - 1];
+ lat = pin.lat;
+ lon = pin.lon;
+ } else if (coordMatch && coordMatch.length >= 3) {
+ lat = parseFloat(coordMatch[1]);
+ lon = parseFloat(coordMatch[2]);
+ } else {
+ return null;
+ }
+ if (isNaN(lat) || isNaN(lon)) return null;
+
+ let viewMeters;
+ const mapsZoomM = s.match(/@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*m\b/i);
const distRegex = /@-?\d+\.?\d*,-?\d+\.?\d*(?:,\d+(?:\.\d*)?\s*a)?\s*,(\d+(?:\.\d*)?)\s*d/i;
const altRegex = /@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*a/i;
const distMatch = s.match(distRegex);
const altMatch = s.match(altRegex);
- if (distMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(distMatch[1])));
+ if (mapsZoomM) viewMeters = Math.min(50000, Math.max(50, parseFloat(mapsZoomM[1])));
+ else if (distMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(distMatch[1])));
else if (altMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(altMatch[1]) * 2));
return { lat, lon, viewMeters };
}
@@ -32,10 +49,10 @@ var DEFAULT_LAYER_OPTIONS = {
landuse: true,
parkingOutline: true,
parkingSpaces: true,
- trees: true,
- barriers: true,
- power: true,
- boundary: true,
+ trees: false,
+ barriers: false,
+ power: false,
+ boundary: false,
man_made: true
};
@@ -177,12 +194,28 @@ function buildPreviewData(osmData, origin, layerOptions) {
return out;
}
-function generateHighDetailDXF(osmData, origin, layerOptions) {
+function generateHighDetailDXF(osmData, origin, layerOptions, clipBounds) {
const opts = layerOptions || DEFAULT_LAYER_OPTIONS;
const on = function (key) { return opts[key] !== false; };
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
+ const clipMargin = 8;
+
+ function inClip(x, y) {
+ if (!clipBounds) return true;
+ return x >= clipBounds.minX - clipMargin && x <= clipBounds.maxX + clipMargin
+ && y >= clipBounds.minY - clipMargin && y <= clipBounds.maxY + clipMargin;
+ }
+
+ function wayTouchesClip(el) {
+ if (!clipBounds || !el.nodes) return true;
+ for (let i = 0; i < el.nodes.length; i++) {
+ const n = nodes[el.nodes[i]];
+ if (n && inClip(n.x, n.y)) return true;
+ }
+ return false;
+ }
osmData.elements.forEach((el) => {
if (el.type === 'node') {
@@ -194,7 +227,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
}
});
- let dxf = '0\nSECTION\n2\nHEADER\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n';
+ let dxf = '0\nSECTION\n2\nHEADER\n9\n$INSUNITS\n70\n6\n9\n$MEASUREMENT\n70\n1\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n';
dxf += '0\nLTYPE\n2\nDASHED\n70\n0\n3\n_ _ _ _ _ _\n72\n65\n73\n2\n40\n2.0\n49\n1.25\n49\n-0.75\n0\nENDTAB\n0\nENDSEC\n';
dxf += '0\nSECTION\n2\nENTITIES\n';
@@ -207,6 +240,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
const PARKING_HH = 2.5;
for (const id in nodes) {
const n = nodes[id];
+ if (!inClip(n.x, n.y)) continue;
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
@@ -233,6 +267,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
if (el.nodes[0] !== el.nodes[el.nodes.length - 1]) return;
+ if (!wayTouchesClip(el)) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
const points = [];
@@ -250,6 +285,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
+ if (!wayTouchesClip(el)) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let layer = '0', color = '7', isRoad = false, roadHalfWidth = 0, isRail = false, lineType = 'CONTINUOUS';
@@ -651,6 +687,47 @@ function classifyImageryContour(poly) {
return null;
}
+/**
+ * Closed OSM building footprints in world meters (for trace overlay / export).
+ */
+function getOSMBuildingFootprints(osmData, origin) {
+ if (!osmData || !origin) return [];
+ const nodes = getOSMNodesInMeters(osmData, origin);
+ const polygons = [];
+ osmData.elements.forEach((el) => {
+ if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
+ if (!el.tags || !el.tags.building) return;
+ const ids = el.nodes[0] === el.nodes[el.nodes.length - 1] ? el.nodes.slice(0, -1) : el.nodes;
+ const pts = [];
+ ids.forEach((id) => {
+ const n = nodes[id];
+ if (n) pts.push({ x: n.x, y: n.y });
+ });
+ if (pts.length >= 3) polygons.push(pts);
+ });
+ return polygons;
+}
+
+/**
+ * OSM barrier/fence ways as polylines in world meters (open or closed).
+ */
+function getOSMBarrierPolylines(osmData, origin) {
+ if (!osmData || !origin) return [];
+ const nodes = getOSMNodesInMeters(osmData, origin);
+ const lines = [];
+ osmData.elements.forEach((el) => {
+ if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
+ if (!el.tags || !el.tags.barrier) return;
+ const pts = [];
+ el.nodes.forEach((id) => {
+ const n = nodes[id];
+ if (n) pts.push({ x: n.x, y: n.y });
+ });
+ if (pts.length >= 2) lines.push(pts);
+ });
+ return lines;
+}
+
/**
* Filter imagery polylines to only those suitable for land lot drawings (trees, buildings, lots).
* Returns { trees: [], buildings: [], lots: [], all: [] }.
@@ -774,6 +851,43 @@ function appendImageryTraceToDXF(dxfContent, polylines, minSegmentMeters, minLen
return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF');
}
+/**
+ * Pixel size for export: preserves geographic aspect ratio; 1 DXF unit = 1 meter.
+ */
+function extentToImagePixels(minX, maxX, minY, maxY, maxLongEdge) {
+ const w = maxX - minX;
+ const h = maxY - minY;
+ const long = Math.max(w, h, 1);
+ const maxPx = maxLongEdge || 2048;
+ const metersPerPixel = long / maxPx;
+ return {
+ width: Math.max(1, Math.round(w / metersPerPixel)),
+ height: Math.max(1, Math.round(h / metersPerPixel)),
+ metersPerPixel: metersPerPixel,
+ widthMeters: w,
+ heightMeters: h
+ };
+}
+
+/**
+ * ESRI world file (.pgw) for georeferenced raster attach in CAD/GIS.
+ * Coordinates match DXF: origin at map center, X east, Y north, units = meters.
+ */
+function generateWorldFilePgw(minX, minY, maxX, maxY, widthPx, heightPx, rowZeroAtSouth) {
+ const pixelW = (maxX - minX) / widthPx;
+ const pixelH = (maxY - minY) / heightPx;
+ const A = pixelW;
+ const C = minX + A / 2;
+ if (rowZeroAtSouth) {
+ const E = pixelH;
+ const F = minY + E / 2;
+ return A + '\n0\n0\n' + E + '\n' + C + '\n' + F + '\n';
+ }
+ const E = -pixelH;
+ const F = maxY + E / 2;
+ return A + '\n0\n0\n' + E + '\n' + C + '\n' + F + '\n';
+}
+
/**
* Append satellite imagery reference to DXF so CAD shows the image as background.
* Also adds a visible bounding box (rectangle) on layer IMAGE_BOUNDS so the image extent is visible in CAD.
@@ -787,6 +901,9 @@ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX,
const h = maxY - minY;
const uPerPx = w / widthPx;
const vPerPx = h / heightPx;
+ const scaleNote =
+ `0\nTEXT\n8\nIMAGE_SCALE\n62\n3\n10\n${minX}\n20\n${minY - Math.max(3, h * 0.02)}\n40\n${Math.max(2, Math.min(w, h) * 0.03)}\n1\n` +
+ `Satellite ${w.toFixed(1)}m x ${h.toFixed(1)}m | ${uPerPx.toFixed(4)} m/px | INSUNITS=meters\n`;
/* Visible bounding box in CAD: four LINE entities (color 4 = cyan) so user sees the image extent */
const layer = 'IMAGE_BOUNDS';
const color = '4';
@@ -803,5 +920,5 @@ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX,
`0\nSECTION\n2\nOBJECTS\n` +
`0\nIMAGEDEF\n90\n${handle}\n1\n${imageFilename}\n13\n${widthPx}\n23\n${heightPx}\n` +
`0\nENDSEC\n0\nEOF`;
- return dxfContent.replace('0\nENDSEC\n0\nEOF', boxLines + imageEntity + '0\nENDSEC\n' + objectsSection);
+ return dxfContent.replace('0\nENDSEC\n0\nEOF', boxLines + scaleNote + imageEntity + '0\nENDSEC\n' + objectsSection);
}
diff --git a/public/index.html b/public/index.html
index a153813..323cb31 100644
--- a/public/index.html
+++ b/public/index.html
@@ -27,7 +27,7 @@
margin-bottom: 6px;
color: #a6adc8;
}
- input[type="url"], input[type="text"] {
+ input[type="url"], input[type="text"], select {
width: 100%;
padding: 10px 12px;
font-size: 14px;
@@ -99,6 +99,12 @@
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;
@@ -130,6 +136,19 @@
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; }
@@ -139,14 +158,31 @@
Address, place name, or map URL
+ Map area to import
+
+ Auto (from map link zoom, or small)
+ Small — ~400 m radius (fastest)
+ Medium — ~800 m radius
+ Large — ~1.5 km radius
+ Extra large — ~3 km radius
+
+
Load preview
+ Go to address
Fit view
Export DXF
Show satellite imagery
+
+ Satellite source
+
+ Esri World Imagery (sharp zoomed in)
+ USGS NAIP (wide area; auto-switches to Esri when zoomed in)
+
+
Generate drawing from imagery
@@ -167,6 +203,50 @@
Snap imagery trace to OSM
+
+
+ Building outlines only (bright roofs)
+
+
+
+ Overlay OSM building footprints
+
+
+
+ Trace fences & site lines
+
+
+ Satellite is Esri or USGS NAIP (not Google). Cyan = buildings from imagery, purple = OSM buildings, orange = fences/site lines. Scroll out after Go to address if you need a wider view.
+
+ Imagery trace tuning (brightness, contrast, edge sensitivity)
+
+ Brightness
+
+ 0
+
+
+ Contrast
+
+ 1.0
+
+
+ Edge sensitivity
+
+ 0.04
+
+
+ Roof / B&W threshold
+
+ 175
+
+
+ Refresh trace preview
+
+
+
+ Site zoom
+
+ 100 m
Layers to include (uncheck to hide in preview and DXF)
@@ -230,6 +310,32 @@
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',
@@ -252,7 +358,7 @@
const label = document.createElement('label');
const cb = document.createElement('input');
cb.type = 'checkbox';
- cb.checked = true;
+ cb.checked = DEFAULT_LAYER_OPTIONS[key] !== false;
cb.id = 'chkLayer_' + key;
cb.dataset.layerKey = key;
label.appendChild(cb);
@@ -297,12 +403,16 @@
y: (lat - centerOrigin.lat) * METERS_PER_LAT
};
}
+ function capTileZoom(z) {
+ const maxZ = getEffectiveTileSource() === 'usgs' ? 16 : 19;
+ return Math.max(0, Math.min(maxZ, z));
+ }
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)));
+ return capTileZoom(Math.round(z));
}
function latLonToTile(lat, lon, z) {
const latRad = (lat * Math.PI) / 180;
@@ -348,11 +458,28 @@
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 Math.max(0, Math.min(19, Math.round(z)));
+ let zBase = capTileZoom(Math.round(z));
+ const span = Math.max(w, h);
+ if (getSatelliteSource() !== 'usgs' && span < 400) zBase = capTileZoom(zBase + 1);
+ return zBase;
}
function getTilesInViewForExtent(minX, maxX, minY, maxY, z) {
const tl = worldToLatLon(minX, maxY);
@@ -367,23 +494,28 @@
}
return tiles;
}
- function drawSatelliteForExtent(minX, maxX, minY, maxY, size) {
+ 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 = size;
- off.height = size;
+ off.width = wp;
+ off.height = hp;
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);
+ 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;
- if (pending === 0) { resolve(off); return; }
+ let tilesDrawn = 0;
+ if (pending === 0) { resolve(null); return; }
function done() {
pending--;
- if (pending === 0) resolve(off);
+ if (pending === 0) resolve(tilesDrawn > 0 ? off : null);
}
tiles.forEach(({ tx, ty, z: zz }) => {
getTileImage(zz, tx, ty, (img) => {
@@ -391,16 +523,27 @@
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;
+ 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 flipCanvasVertical(src) {
+ const out = document.createElement('canvas');
+ out.width = src.width;
+ out.height = src.height;
+ const ctx = out.getContext('2d');
+ ctx.translate(0, out.height);
+ ctx.scale(1, -1);
+ ctx.drawImage(src, 0, 0);
+ return out;
+ }
function drawSatelliteToContext(targetCtx, targetWidth, targetHeight, scaleFactor) {
const sf = scaleFactor || 1;
return new Promise((resolve) => {
@@ -432,7 +575,8 @@
});
}
function getTileImage(z, tx, ty, onLoad, onError) {
- const key = z + '_' + tx + '_' + ty;
+ const source = getEffectiveTileSource();
+ const key = source + '_' + z + '_' + tx + '_' + ty;
if (tileCache[key]) {
if (tileCache[key].complete && tileCache[key].naturalWidth) onLoad(tileCache[key]);
else {
@@ -444,9 +588,21 @@
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;
+ const timer = setTimeout(function() {
+ if (!img.complete) {
+ img.src = '';
+ if (onError) onError();
+ }
+ }, 20000);
+ img.addEventListener('load', function() {
+ clearTimeout(timer);
+ onLoad(img);
+ });
+ img.addEventListener('error', function() {
+ clearTimeout(timer);
+ if (onError) onError();
+ });
+ img.src = '/api/tile/' + z + '/' + ty + '/' + tx + '?source=' + encodeURIComponent(source);
}
function drawSatelliteLayer() {
if (!centerOrigin || !showSatellite) return;
@@ -695,16 +851,45 @@
}
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 = 1.5;
- ctx.setLineDash([3, 3]);
+ 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([]);
@@ -714,22 +899,186 @@
const cw = canvas.width, ch = canvas.height;
ctx.fillStyle = '#313244';
ctx.fillRect(0, 0, cw, ch);
- if (!previewData.length) {
+ const hasMap = previewData.length > 0;
+ const hasSite = !!centerOrigin;
+ if (!hasMap && !hasSite) {
ctx.fillStyle = '#a6adc8';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
- ctx.fillText('Load a map to see preview', cw / 2, ch / 2);
+ ctx.fillText('Enter an address and click Go to address, or Load preview', cw / 2, ch / 2);
return;
}
if (showSatellite && centerOrigin) {
drawSatelliteLayer();
- } else {
+ } else if (hasMap) {
drawVectorLayer();
drawImageryTraceLayer();
drawLotsLayer();
}
+ if (centerOrigin) 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;
+ draw();
+ }
+
+ function getSiteZoomMeters() {
+ const el = document.getElementById('siteZoom');
+ return el ? parseInt(el.value, 10) || 100 : 100;
+ }
+
+ function morphCloseRadii(spanM) {
+ const closeBig = Math.min(10, Math.max(3, Math.round(spanM / 20)));
+ const closeMid = Math.min(5, Math.max(2, Math.round(spanM / 40)));
+ 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) || 175;
+ 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 };
+ const zoomM = getSiteZoomMeters();
+ zoomToSiteView(zoomM);
+ const sat = document.getElementById('chkSatellite');
+ if (sat && !sat.checked) {
+ sat.checked = true;
+ showSatellite = true;
+ 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 roads/OSM.', false, true);
+ btnFit.disabled = false;
+ 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;
@@ -737,6 +1086,7 @@
offsetX = cw / 2 - (b.minX + b.w / 2) * scale;
offsetY = ch / 2 + (b.minY + b.h / 2) * scale;
draw();
+ scheduleTraceRefresh();
}
function zoomAt(mx, my, factor) {
@@ -746,6 +1096,7 @@
offsetX = mx - wx * scale;
offsetY = my + wy * scale;
draw();
+ scheduleTraceRefresh();
}
canvas.addEventListener('mousedown', (e) => {
@@ -875,6 +1226,7 @@
return;
}
if (editLotMode) selectedVertex = null;
+ if (isDragging) scheduleTraceRefresh();
isDragging = false;
draw();
});
@@ -897,7 +1249,7 @@
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
- if (!previewData.length) return;
+ if (!centerOrigin) return;
const p = getCanvasCoords(e);
const factor = e.deltaY > 0 ? 0.9 : 1.1;
zoomAt(p.x, p.y, factor);
@@ -906,23 +1258,97 @@
document.getElementById('chkSatellite').addEventListener('change', (e) => {
showSatellite = e.target.checked;
draw();
+ scheduleTraceRefresh();
});
- const PREVIEW_TRACE_SIZE = 512;
+ const selSatelliteSource = document.getElementById('selSatelliteSource');
+ if (selSatelliteSource) {
+ selSatelliteSource.addEventListener('change', () => {
+ clearTileCache();
+ 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());
+ }
+
+ const PREVIEW_TRACE_SIZE = 1024;
async function updatePreviewImageryTrace() {
const chk = document.getElementById('chkImageryTrace');
- if (!chk || !chk.checked || !centerOrigin || !previewData.length) return;
+ 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;
- setStatus(useML ? 'Server-side ML segmentation…' : 'Computing imagery trace preview…');
+ 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 extent = getMapExtentInMeters();
- const traceCanvas = await drawSatelliteForExtent(extent.minX, extent.maxX, extent.minY, extent.maxY, PREVIEW_TRACE_SIZE);
- if (!traceCanvas || !document.getElementById('chkImageryTrace').checked) {
+ 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'));
@@ -933,6 +1359,7 @@
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) {
@@ -952,39 +1379,105 @@
}
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 });
+ 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;
}
- const filtered = filterImageryPolylinesForLotDrawing(raw);
+ 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(filtered.all, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
- : filtered.all;
+ ? 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;
- 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);
+ 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) {
- setStatus('Imagery trace on: computing preview…', false, true);
+ 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'].forEach((id) => {
+ ['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(); });
});
@@ -1045,6 +1538,15 @@
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;
@@ -1097,6 +1599,394 @@
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 - 65 && l >= 88;
+ const colorOk = sat < 95 || l >= 155;
+ 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);
+ for (let i = 0; i < n; i++) {
+ 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);
+ if (gray[i] >= minLum && (sat < 75 || gray[i] >= 170)) 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 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 <= 140
+ ? Math.max(40, worldAreaM2 * 0.01)
+ : Math.max(80, worldAreaM2 * 0.0025);
+ const minPx = Math.max(60, Math.floor(minAreaM2 * pxPerM2 * 0.5));
+ const maxPx = Math.floor(80000 * pxPerM2);
+ const roofBright = options.roofBright != null ? options.roofBright : 175;
+ 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, roofBright - 30),
+ () => permissiveRoofMask(data, tuned, ow, oh, roofBright - 45),
+ () => seedGrowRoofMask(data, tuned, ow, oh, 0.9),
+ () => 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 < 10; 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.015) 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 : 150;
+ return polylines.filter((poly) => {
+ const area = polygonAreaWorld(poly);
+ if (area < minArea || area > 80000) 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) {
@@ -1178,8 +2068,40 @@
}));
}
- 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 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 [];
@@ -1191,60 +2113,69 @@
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); // 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;
+ blurred = blur(blurred, ow, oh);
+ const tuned = applyBrightnessContrast(blurred, ow, oh, brightness, contrast);
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);
- });
+ let fencePolylines = [];
+
+ function runEdgePass(edge) {
+ const dilated = dilateEdge(edge, ow, oh);
+ return findContours(dilated, ow, oh);
}
- 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);
+
+ 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;
}
@@ -1258,10 +2189,10 @@
if (detectionRect) {
const r = detectionRect;
- const detectSize = 400;
- const ow = detectSize, oh = detectSize;
+ 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, detectSize);
+ 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');
@@ -1477,6 +2408,74 @@
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) {
+ 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++) {
+ setStatus(tiles.length > 1
+ ? 'Fetching map data (' + (i + 1) + ' of ' + tiles.length + ')…'
+ : 'Fetching map data…');
+ const res = await fetch('/api/overpass', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...tiles[i], layers: layers })
+ });
+ const data = await res.json();
+ if (!res.ok) {
+ const err = new Error(data.error || 'Request failed');
+ err.status = res.status;
+ throw err;
+ }
+ results.push(data);
+ }
+ const merged = mergeOsmResults(results);
+ if (tiles.length > 1) {
+ merged._meta = { tiles: tiles.length, elementCount: merged.elements.length };
+ }
+ return merged;
+ }
+
+ 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) {
@@ -1487,34 +2486,20 @@
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);
+ 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) {
+ setStatus('No map features found in this area. Try a different location or larger area.', true);
return;
}
- osmData = data;
- previewData = buildPreviewData(osmData, centerOrigin, getLayerOptions());
+ previewData = buildPreviewData(osmData, centerOrigin, layers);
previewImageryTracePolylines = [];
+ previewImageryFencePolylines = [];
btnFit.disabled = false;
btnExport.disabled = false;
btnDrawLot.disabled = false;
@@ -1527,13 +2512,22 @@
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);
+ zoomToSiteView(getSiteZoomMeters());
+ 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) {
- setStatus(e.message || 'Failed to resolve location.', true);
+ const hint = e.status === 429
+ ? ' Overpass is rate-limited — wait 1–2 minutes, try Small area, or uncheck unused layers.'
+ : '';
+ setStatus((e.message || 'Failed to load map.') + hint, true);
} finally {
btnLoad.disabled = false;
}
@@ -1549,31 +2543,34 @@
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 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 traceCanvas = await drawSatelliteForExtent(extent.minX, extent.maxX, extent.minY, extent.maxY, IMAGERY_TRACE_SIZE);
+ 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(extent.minX));
- form.append('maxX', String(extent.maxX));
- form.append('minY', String(extent.minY));
- form.append('maxY', String(extent.maxY));
+ 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) {
@@ -1591,40 +2588,52 @@
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 });
+ 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 {
- const filtered = filterImageryPolylinesForLotDrawing(raw);
+ 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(filtered.all, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
- : filtered.all;
+ ? snapTracePolylinesToOSM(raw, osmData, getOSMNodesInMeters(osmData, centerOrigin), 1.5)
+ : raw;
}
}
} 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());
+ const imgSpec = extentToImagePixels(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, IMAGE_MAX_EDGE);
+ const imgCanvasRaw = await drawSatelliteForExtent(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, imgSpec.width, imgSpec.height);
+ const imgCanvas = imgCanvasRaw ? flipCanvasVertical(imgCanvasRaw) : null;
+ 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);
+ 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 EMBEDDED_IMAGE_FILENAME = 'satellite.png';
+ const PGW_FILENAME = 'satellite.pgw';
if (imgCanvas) {
- dxfContent = appendSatelliteImageToDXF(dxfContent, EMBEDDED_IMAGE_FILENAME, imageExtent.minX, imageExtent.minY, imageExtent.maxX, imageExtent.maxY, IMAGE_SIZE, IMAGE_SIZE);
+ dxfContent = appendSatelliteImageToDXF(dxfContent, EMBEDDED_IMAGE_FILENAME, 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(EMBEDDED_IMAGE_FILENAME, pngBlob, { binary: true });
+ zip.file(PGW_FILENAME, generateWorldFilePgw(exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height, true), { binary: false });
const zipBlob = await zip.generateAsync({ type: 'blob' });
const zipUrl = URL.createObjectURL(zipBlob);
const aZip = document.createElement('a');
@@ -1648,13 +2657,25 @@
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, true)], { type: 'text/plain' });
+ const pgwUrl = URL.createObjectURL(pgwBlob);
+ const aPgw = document.createElement('a');
+ aPgw.href = pgwUrl;
+ aPgw.download = 'satellite.pgw';
+ aPgw.click();
+ URL.revokeObjectURL(pgwUrl);
}
}
let statusMsg = imgCanvas && typeof JSZip !== 'undefined'
- ? 'Downloaded ' + baseName + '.zip (DXF + satellite image inside). Unzip and open the DXF in CAD.'
+ ? 'Downloaded ' + baseName + '.zip (DXF + satellite.png + satellite.pgw). Unzip and open the DXF in CAD — 1 unit = 1 meter.'
: imgCanvas
? 'Downloaded ' + dxfFileName + ' and ' + pngFileName + '. Keep both in the same folder for CAD.'
: '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) {
diff --git a/server.js b/server.js
index 7e19080..d53234e 100644
--- a/server.js
+++ b/server.js
@@ -21,108 +21,200 @@ function openBrowser() {
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(__dirname, 'public')));
-// Multiple public Overpass API instances; we try each until one returns valid JSON.
+// Public Overpass mirrors; rotated and retried on 429/503/504.
const OVERPASS_ENDPOINTS = [
- 'https://overpass-api.de/api/interpreter',
'https://overpass.kumi.systems/api/interpreter',
- 'https://overpass.openstreetmap.fr/api/interpreter'
+ 'https://overpass-api.de/api/interpreter',
+ 'https://overpass.openstreetmap.fr/api/interpreter',
+ 'https://overpass.private.coffee/api/interpreter'
];
const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool; https://github.com)';
+const OVERPASS_MIN_INTERVAL_MS = Number(process.env.OVERPASS_MIN_INTERVAL_MS) || 1000;
+const OVERPASS_MAX_RETRIES = Number(process.env.OVERPASS_MAX_RETRIES) || 3;
+const OVERPASS_BACKOFF_BASE_MS = Number(process.env.OVERPASS_BACKOFF_BASE_MS) || 2000;
+const OVERPASS_TILE_MAX_DEG = Number(process.env.OVERPASS_TILE_MAX_DEG) || 0.018;
+const OVERPASS_MAX_TILES = Number(process.env.OVERPASS_MAX_TILES) || 9;
+const RETRYABLE_OVERPASS_STATUSES = new Set([429, 502, 503, 504]);
-async function fetchOverpass(query, timeoutMs = 45000) {
- let lastError;
- for (const url of OVERPASS_ENDPOINTS) {
- const controller = new AbortController();
- const to = setTimeout(() => controller.abort(), timeoutMs);
- try {
- const r = await fetch(url, {
- method: 'POST',
- body: query,
- headers: {
- 'Content-Type': 'text/plain',
- 'User-Agent': OVERPASS_USER_AGENT
- },
- signal: controller.signal
+let lastOverpassRequestAt = 0;
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function throttleOverpass(skip) {
+ if (skip) return;
+ const now = Date.now();
+ const wait = OVERPASS_MIN_INTERVAL_MS - (now - lastOverpassRequestAt);
+ if (wait > 0) await sleep(wait);
+ lastOverpassRequestAt = Date.now();
+}
+
+function layerEnabled(layers, key) {
+ return !layers || layers[key] !== false;
+}
+
+function buildOverpassQuery(bbox, layers) {
+ const b = `(${bbox.south},${bbox.west},${bbox.north},${bbox.east})`;
+ const parts = [];
+ if (layerEnabled(layers, 'roads') || layerEnabled(layers, 'paths')) {
+ parts.push(`way["highway"]${b};`);
+ }
+ if (layerEnabled(layers, 'railways')) parts.push(`way["railway"]${b};`);
+ if (layerEnabled(layers, 'buildings')) parts.push(`way["building"]${b};`);
+ if (layerEnabled(layers, 'parkingOutline')) parts.push(`way["amenity"="parking"]${b};`);
+ if (layerEnabled(layers, 'landuse')) parts.push(`way["landuse"]${b};`);
+ if (layerEnabled(layers, 'water')) parts.push(`way["natural"="water"]${b};`);
+ if (layerEnabled(layers, 'parks')) parts.push(`way["leisure"]${b};`);
+ if (layerEnabled(layers, 'barriers')) parts.push(`way["barrier"]${b};`);
+ if (layerEnabled(layers, 'power')) parts.push(`way["power"]${b};`);
+ if (layerEnabled(layers, 'boundary')) parts.push(`way["boundary"]${b};`);
+ if (layerEnabled(layers, 'man_made')) {
+ parts.push(`way["man_made"="embankment"]${b};`);
+ parts.push(`way["man_made"="cutline"]${b};`);
+ }
+ if (layerEnabled(layers, 'trees')) {
+ parts.push(`node["natural"="tree"]${b};`);
+ parts.push(`node["natural"="tree_row"]${b};`);
+ }
+ if (layerEnabled(layers, 'parkingSpaces')) parts.push(`node["amenity"="parking_space"]${b};`);
+ if (parts.length === 0) {
+ parts.push(`way["highway"]${b};`);
+ }
+ return `[out:json][timeout:15];(${parts.join('')});(._;>;);out body;`;
+}
+
+function splitBbox(bbox) {
+ const latSpan = bbox.north - bbox.south;
+ const lonSpan = bbox.east - bbox.west;
+ let nLat = Math.max(1, Math.ceil(latSpan / OVERPASS_TILE_MAX_DEG));
+ let nLon = Math.max(1, Math.ceil(lonSpan / OVERPASS_TILE_MAX_DEG));
+ while (nLat * nLon > OVERPASS_MAX_TILES) {
+ if (nLat >= nLon && nLat > 1) nLat--;
+ else if (nLon > 1) nLon--;
+ else break;
+ }
+ if (nLat === 1 && nLon === 1) return [bbox];
+ const tiles = [];
+ const latStep = latSpan / nLat;
+ const lonStep = lonSpan / nLon;
+ for (let i = 0; i < nLat; i++) {
+ for (let j = 0; j < nLon; j++) {
+ tiles.push({
+ south: bbox.south + i * latStep,
+ north: bbox.south + (i + 1) * latStep,
+ west: bbox.west + j * lonStep,
+ east: bbox.west + (j + 1) * lonStep
});
- const text = await r.text();
- clearTimeout(to);
- const looksLikeJson = /^\s*[\{\[]/.test(text);
- if (!r.ok) {
- let msg = `Overpass ${r.status}`;
- if (looksLikeJson) {
- try {
- const err = JSON.parse(text);
- if (err.error) msg = err.error;
- } catch (_) {}
- } else if (/<\?xml| controller.abort(), timeoutMs);
+ try {
+ const r = await fetch(url, {
+ method: 'POST',
+ body: query,
+ headers: {
+ 'Content-Type': 'text/plain',
+ 'User-Agent': OVERPASS_USER_AGENT
+ },
+ signal: controller.signal
+ });
+ const text = await r.text();
+ clearTimeout(to);
+ const parsed = parseOverpassResponse(text, r.status);
+ if (parsed.data) return parsed.data;
+ const err = parsed.error || new Error(`Overpass ${r.status}`);
+ err.retryable = parsed.retryable ?? RETRYABLE_OVERPASS_STATUSES.has(r.status);
+ err.status = r.status;
+ const retryAfter = parseInt(r.headers.get('Retry-After'), 10);
+ if (retryAfter > 0) err.retryAfterMs = retryAfter * 1000;
+ throw err;
+ } catch (e) {
+ clearTimeout(to);
+ if (e.name === 'AbortError') {
+ const err = new Error('Request timed out. Try a smaller area or try again later.');
+ err.retryable = true;
+ throw err;
+ }
+ throw e;
+ }
+}
+
+async function fetchOverpass(query, timeoutMs = 25000, skipThrottle) {
+ let lastError;
+ const startIdx = Math.floor(Math.random() * OVERPASS_ENDPOINTS.length);
+ for (let endpointOffset = 0; endpointOffset < OVERPASS_ENDPOINTS.length; endpointOffset++) {
+ const url = OVERPASS_ENDPOINTS[(startIdx + endpointOffset) % OVERPASS_ENDPOINTS.length];
+ for (let attempt = 0; attempt < OVERPASS_MAX_RETRIES; attempt++) {
try {
- data = JSON.parse(text);
- } catch (parseErr) {
- lastError = new Error('Overpass returned invalid JSON. Try again later.');
- continue;
+ return await fetchOverpassOnce(query, url, timeoutMs, skipThrottle && endpointOffset === 0 && attempt === 0);
+ } catch (e) {
+ lastError = e;
+ const retryable = e.retryable !== false && (e.retryable || e.status === 429);
+ if (!retryable || attempt >= OVERPASS_MAX_RETRIES - 1) break;
+ const delay = e.retryAfterMs || OVERPASS_BACKOFF_BASE_MS * Math.pow(2, attempt);
+ console.warn(`Overpass retry ${attempt + 1}/${OVERPASS_MAX_RETRIES} on ${url} after ${delay}ms: ${e.message}`);
+ await sleep(delay);
+ skipThrottle = false;
}
- if (data.error) {
- lastError = new Error(data.error);
- continue;
- }
- return data;
- } catch (e) {
- clearTimeout(to);
- if (e.name === 'AbortError') lastError = new Error('Request timed out. Try a smaller area or try again later.');
- else lastError = e;
}
}
throw lastError || new Error('All Overpass servers failed. Wait a few minutes and try again, or use a smaller map area.');
}
-app.post('/api/overpass', async (req, res) => {
- const bbox = req.body;
- if (!bbox || typeof bbox.south !== 'number' || typeof bbox.north !== 'number') {
+app.post('/api/overpass/plan', (req, res) => {
+ const { south, west, north, east } = req.body || {};
+ if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') {
return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' });
}
- const query = `
- [out:json][timeout:25];
- (
- way["highway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["railway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["building"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["amenity"="parking"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["landuse"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["natural"="water"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["leisure"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["barrier"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["power"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["boundary"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["man_made"="embankment"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- way["man_made"="cutline"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- node["natural"="tree"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- node["natural"="tree_row"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- node["amenity"="parking_space"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
- );
- (._;>;);
- out body;
- `;
+ const tiles = splitBbox({ south, west, north, east });
+ res.json({ tiles, count: tiles.length });
+});
+
+app.post('/api/overpass', async (req, res) => {
+ const { south, west, north, east, layers } = req.body || {};
+ if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') {
+ return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' });
+ }
+ const bbox = { south, west, north, east };
try {
- const data = await fetchOverpass(query);
+ const query = buildOverpassQuery(bbox, layers);
+ const data = await fetchOverpass(query, 25000, true);
res.json(data);
} catch (e) {
const msg = e.message || 'Overpass request failed';
console.error('Overpass error:', msg);
- res.status(502).json({ error: msg });
+ const status = e.status === 429 ? 429 : 502;
+ res.status(status).json({ error: msg });
}
});
@@ -181,8 +273,31 @@ app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
-const TILE_BASE = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile';
-// Proxy to Python ML segmentation server (run: cd ml_server && pip install -r requirements.txt && python segment_server.py)
+const TILE_SOURCES = {
+ esri: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile',
+ usgs: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile'
+};
+
+app.get('/api/tile/:z/:y/:x', async (req, res) => {
+ const { z, y, x } = req.params;
+ const sourceKey = String(req.query.source || 'esri').toLowerCase();
+ const base = TILE_SOURCES[sourceKey] || TILE_SOURCES.esri;
+ const url = `${base}/${z}/${y}/${x}`;
+ try {
+ const r = await fetch(url);
+ if (!r.ok) {
+ res.status(r.status).end();
+ return;
+ }
+ const buf = await r.arrayBuffer();
+ res.set('Cache-Control', 'public, max-age=86400');
+ res.set('Access-Control-Allow-Origin', '*');
+ res.type('image/png').send(Buffer.from(buf));
+ } catch (e) {
+ res.status(502).end();
+ }
+});
+
app.post('/api/segment', upload.single('image'), async (req, res) => {
if (!req.file || !req.file.buffer) {
return res.status(400).json({ error: 'Missing image file' });
@@ -226,25 +341,17 @@ app.post('/api/segment', upload.single('image'), async (req, res) => {
}
});
-app.get('/api/tile/:z/:y/:x', async (req, res) => {
- const { z, y, x } = req.params;
- const url = `${TILE_BASE}/${z}/${y}/${x}`;
- try {
- const r = await fetch(url);
- if (!r.ok) {
- res.status(r.status).end();
- return;
- }
- const buf = await r.arrayBuffer();
- res.set('Cache-Control', 'public, max-age=86400');
- res.set('Access-Control-Allow-Origin', '*');
- res.type('image/png').send(Buffer.from(buf));
- } catch (e) {
- res.status(502).end();
- }
-});
-
-app.listen(PORT, () => {
+const server = app.listen(PORT, () => {
console.log('MAPS to DXF — ' + URL);
openBrowser();
});
+server.on('error', (err) => {
+ if (err.code === 'EADDRINUSE') {
+ console.error('');
+ console.error('Port ' + PORT + ' is already in use.');
+ console.error('Close the other MAPS to DXF console window, or run Start.bat again (it will free the port).');
+ console.error('');
+ process.exit(1);
+ }
+ throw err;
+});