From 7769a4412ea2b55a7fc78df8785ddaecc49aa320 Mon Sep 17 00:00:00 2001 From: Michael Sloan Date: Mon, 31 Aug 2026 15:43:01 -0400 Subject: [PATCH] feat: harden maps export for CAD and improve satellite/OSM workflow Cap zoom to real imagery, attach a BricsCAD-safe DXF IMAGE at the selected extent, and consolidate startup plus Overpass/address handling. Co-authored-by: Cursor --- README.md | 12 +- Start.bat | 97 ++++--- Start_ML_Server.bat | 40 --- ai_dna.md | 2 +- ml_server/README.md | 6 +- public/app.js | 213 ++++++++++++-- public/index.html | 657 +++++++++++++++++++++++++++++++++++--------- server.js | 489 +++++++++++++++++++++++++++------ 8 files changed, 1186 insertions(+), 330 deletions(-) delete mode 100644 Start_ML_Server.bat diff --git a/README.md b/README.md index 45bdf88..2f3db7b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Turn a **Google Maps link** into a **DXF map** with roads, rails, buildings, and **Easiest:** Double-click **Start.bat**. - If Node.js isn’t installed, the script will try to install it (Windows Package Manager) or open the Node.js download page. After installing, run **Start.bat** again. -- If Node.js is installed: the app starts, your browser opens to the app. Keep the console window open while using it; close it to stop the server. +- If Node.js is installed: the app starts in **one window**, your browser opens, and the optional Python ML server starts in the background if Python is installed. Keep the console window open while using it; close it to stop everything. **Or from a terminal:** @@ -67,7 +67,7 @@ Then open http://localhost:8080 | File / folder | Role | |--------------------|------| -| `Start.bat` | One-click run on Windows (installs Node if needed, then `npm start`) | +| `Start.bat` | Only launcher you need: installs Node if needed, frees ports, starts the app + optional ML | | `server.js` | Express server: serves `public/`, proxies Overpass and tile API | | `public/index.html`| Single-page UI + canvas preview + all map/lot/edit logic (inline script) | | `public/app.js` | Shared helpers: OSM→preview, DXF generation, OSM lot/concave-hull logic | @@ -79,13 +79,7 @@ Then open http://localhost:8080 - **Generate drawing from imagery** — Vectorizes satellite imagery into the DXF (client-side edge detection). - **Use server-side ML segmentation** — Sends the imagery to a small Python server that runs OpenCV Canny + contours and classifies buildings, trees, and lots. Export writes separate DXF layers: **IMAGERY_BUILDINGS**, **IMAGERY_TREES**, **IMAGERY_LOTS**. - **To enable:** In a second terminal: - ```bash - cd ml_server - pip install -r requirements.txt - python segment_server.py - ``` - The Python server runs on **http://127.0.0.1:3457**. The Node app proxies `/api/segment` to it. If the Python server is not running, the checkbox will show an error when you use it. + **To enable:** Double-click **Start.bat**. If Python is installed, the ML server starts automatically with the app (port 3457). If Python is missing, satellite tracing still works. - **Snap imagery trace to OSM** — When enabled, trace points are snapped to nearby OSM buildings, roads, and landuse (within ~1.5 m). Use this to align the imagery trace with OSM where data exists. diff --git a/Start.bat b/Start.bat index 7126564..d04e13c 100644 --- a/Start.bat +++ b/Start.bat @@ -1,52 +1,65 @@ @echo off +setlocal title MAPS to DXF cd /d "%~dp0" where node >nul 2>&1 -if %errorlevel% neq 0 ( - echo Node.js not found. Installing via Windows Package Manager... - winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements 2>nul - if %errorlevel% neq 0 ( - echo. - echo Could not install Node.js automatically. Opening download page... - start https://nodejs.org/ - echo. - echo After installing Node.js, close this window and double-click Start.bat again. - pause - exit /b 1 - ) - echo. - echo Node.js installed. Please close this window, then double-click Start.bat again. - pause - exit /b 0 -) +if errorlevel 1 goto INSTALL_NODE +goto DEPS -if not exist "node_modules" ( - echo Installing dependencies... - call npm install -) else if not exist "node_modules\multer" ( - echo Installing missing dependencies... - call npm install -) - -if exist "ml_server\segment_server.py" ( - where python >nul 2>&1 - if %errorlevel% equ 0 ( - start "MAPS to DXF - ML Server" cmd /k "call %~sdp0Start_ML_Server.bat" - timeout /t 2 /nobreak >nul - ) else ( - where py >nul 2>&1 - if %errorlevel% equ 0 ( - start "MAPS to DXF - ML Server" cmd /k "call %~sdp0Start_ML_Server.bat" - timeout /t 2 /nobreak >nul - ) - ) -) +:INSTALL_NODE +echo Node.js not found. Installing via Windows Package Manager... +winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements +if errorlevel 1 goto NODE_FAIL +echo Node.js installed. Close this window, then double-click Start.bat again. +pause +exit /b 0 +:NODE_FAIL +echo Could not install Node.js automatically. Opening download page... +start https://nodejs.org/ +echo After installing Node.js, close this window and double-click Start.bat again. +pause +exit /b 1 + +:DEPS +if not exist "node_modules\express" goto NPM_INSTALL +if not exist "node_modules\multer" goto NPM_INSTALL +goto PORTS + +:NPM_INSTALL +echo Installing dependencies... +call npm install +if errorlevel 1 goto NPM_FAIL +goto PORTS + +:NPM_FAIL +echo npm install failed. +pause +exit /b 1 + +:PORTS +echo Freeing ports 3456 and 3457 if a previous run is still open... +powershell -NoProfile -Command "foreach ($p in 3456,3457) { Get-NetTCPConnection -LocalPort $p -State Listen -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue } }" >nul 2>&1 + +set "PY=" +where python >nul 2>&1 +if not errorlevel 1 set "PY=python" +if defined PY goto ML_DEPS +where py >nul 2>&1 +if not errorlevel 1 set "PY=py" +if not defined PY goto START_APP + +:ML_DEPS +if not exist "ml_server\requirements.txt" goto START_APP +echo Checking Python ML dependencies... +"%PY%" -m pip install -r "ml_server\requirements.txt" -q + +:START_APP 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 Browser will open. Keep this window open. +echo Close this window to stop the app. +echo. +node server.js echo. -call npm start pause diff --git a/Start_ML_Server.bat b/Start_ML_Server.bat deleted file mode 100644 index 0ad4704..0000000 --- a/Start_ML_Server.bat +++ /dev/null @@ -1,40 +0,0 @@ -@echo off -title MAPS to DXF - ML segmentation server -cd /d "%~dp0" - -where python >nul 2>&1 -if %errorlevel% neq 0 ( - where py >nul 2>&1 - if %errorlevel% neq 0 ( - echo Python not found. Install Python from https://www.python.org/downloads/ - echo Then run this script again. - pause - exit /b 1 - ) - set PY=py -) else ( - set PY=python -) - -if not exist "ml_server" ( - echo ml_server folder not found. - pause - exit /b 1 -) - -cd ml_server -echo Installing Python dependencies... -"%PY%" -m pip install -r requirements.txt -q -if %errorlevel% neq 0 ( - echo. - echo Pip install failed. Try: pip install -r requirements.txt - pause - exit /b 1 -) - -echo. -echo ML segmentation server starting on http://127.0.0.1:3457 -echo Keep this window open while using "Use server-side ML segmentation" in the app. -echo. -"%PY%" segment_server.py -pause diff --git a/ai_dna.md b/ai_dna.md index 2437ef1..a001f84 100644 --- a/ai_dna.md +++ b/ai_dna.md @@ -26,7 +26,7 @@ Quick reference for AI and developers jumping back into this repo: purpose, stru MAPS-to-DXF-standalone/ ├── server.js # Express: static files, /api/overpass, /api/tile ├── package.json # express only -├── Start.bat # Windows: install Node if missing, npm install, npm start +├── Start.bat # Only Windows launcher: Node + app + optional ML server ├── README.md # User-facing run + workflow ├── ai_dna.md # This file — project DNA for AI/developers └── public/ diff --git a/ml_server/README.md b/ml_server/README.md index 68fbc80..3e2a09e 100644 --- a/ml_server/README.md +++ b/ml_server/README.md @@ -4,13 +4,15 @@ Run this server to enable **Use server-side ML segmentation** in the app. It tra ## Run +Double-click **Start.bat** in the project root (starts the main app and this ML server together). + +Or from a terminal: + ```bash pip install -r requirements.txt python segment_server.py ``` -Or double-click **Start_ML_Server.bat** from the project root. - Server listens on **http://127.0.0.1:3457**. The Node app proxies `/api/segment` to it. ## Backends diff --git a/public/app.js b/public/app.js index 19a19d3..e401621 100644 --- a/public/app.js +++ b/public/app.js @@ -3,6 +3,35 @@ * Supports Google Maps and Google Earth (Web) links. Google Earth view/altitude/distance * is used to optimize the requested area (smaller = faster Overpass and imagery). */ +function isShortMapsUrl(input) { + return /^https?:\/\/(maps\.app\.goo\.gl|goo\.gl\/maps)\//i.test(String(input).trim()); +} + +function isGoogleMapsLink(input) { + const s = String(input).trim(); + return isShortMapsUrl(s) || /^https?:\/\/(www\.)?(google\.[^/]+\/maps|maps\.google\.)/i.test(s); +} + +function extractAddressFromMapsUrl(input) { + const s = String(input).trim(); + const place = s.match(/google\.[^/]+\/maps\/place\/([^/@?#]+)/i); + if (place && place[1]) { + const decoded = decodeURIComponent(place[1].replace(/\+/g, ' ')).trim(); + if (decoded && !/^-?\d+\.?\d*\s*,\s*-?\d+\.?\d*$/.test(decoded)) return decoded; + } + const search = s.match(/google\.[^/]+\/maps\/search\/([^/@?#]+)/i); + if (search && search[1]) { + const decoded = decodeURIComponent(search[1].replace(/\+/g, ' ')).trim(); + if (decoded && !/^-?\d+\.?\d*\s*,\s*-?\d+\.?\d*$/.test(decoded)) return decoded; + } + const q = s.match(/[?&](?:q|query|daddr|saddr)=([^&]+)/i); + if (q && q[1]) { + const decoded = decodeURIComponent(q[1].replace(/\+/g, ' ')).trim(); + if (decoded && !/^https?:/i.test(decoded) && !/^-?\d+\.?\d*\s*,\s*-?\d+\.?\d*$/.test(decoded)) return decoded; + } + return null; +} + function extractCoordinates(url) { const s = String(url).trim(); let lat; @@ -13,19 +42,26 @@ function extractCoordinates(url) { 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); + const atMatch = s.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/); + const qCoord = s.match(/[?&](?:q|ll|center|query)=(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)/i); + const dirCoord = s.match(/!8m2!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/); 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 if (dirCoord) { + lat = parseFloat(dirCoord[1]); + lon = parseFloat(dirCoord[2]); + } else if (atMatch && atMatch.length >= 3) { + lat = parseFloat(atMatch[1]); + lon = parseFloat(atMatch[2]); + } else if (qCoord && qCoord.length >= 3) { + lat = parseFloat(qCoord[1]); + lon = parseFloat(qCoord[2]); } else { return null; } - if (isNaN(lat) || isNaN(lon)) return null; + if (isNaN(lat) || isNaN(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null; let viewMeters; const mapsZoomM = s.match(/@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*m\b/i); @@ -99,9 +135,11 @@ function buildPreviewData(osmData, origin, layerOptions) { }); const s = 8; - out.push(['L', -s, 0, s, 0, 4]); - out.push(['L', 0, -s, 0, s, 4]); - out.push(['C', 0, 0, s / 1.5, 4]); + if (on('locationMarker')) { + out.push(['L', -s, 0, s, 0, 4]); + out.push(['L', 0, -s, 0, s, 4]); + out.push(['C', 0, 0, s / 1.5, 4]); + } const PARKING_SPOT_HW = 1.25; const PARKING_SPOT_HH = 2.5; @@ -201,6 +239,9 @@ function generateHighDetailDXF(osmData, origin, layerOptions, clipBounds) { const metersPerLat = 111132.92; const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180); const clipMargin = 8; + if (!osmData || !Array.isArray(osmData.elements)) { + osmData = { elements: [] }; + } function inClip(x, y) { if (!clipBounds) return true; @@ -227,14 +268,15 @@ function generateHighDetailDXF(osmData, origin, layerOptions, clipBounds) { } }); - 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'; + let dxf = dxfR2000Preamble(); dxf += '0\nSECTION\n2\nENTITIES\n'; const s = 8; - dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n-${s}\n20\n0\n11\n${s}\n21\n0\n`; - dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n-${s}\n11\n0\n21\n${s}\n`; - dxf += `0\nCIRCLE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n0\n40\n${s / 1.5}\n`; + if (on('locationMarker')) { + dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n-${s}\n20\n0\n11\n${s}\n21\n0\n`; + dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n-${s}\n11\n0\n21\n${s}\n`; + dxf += `0\nCIRCLE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n0\n40\n${s / 1.5}\n`; + } const PARKING_HW = 1.25; const PARKING_HH = 2.5; @@ -402,10 +444,101 @@ function generateHighDetailDXF(osmData, origin, layerOptions, clipBounds) { } }); - dxf += '0\nENDSEC\n0\nEOF'; + dxf += '0\nENDSEC\n' + dxfBaseObjectsSection() + '0\nEOF'; return dxf; } +/** Model-space BLOCK_RECORD handle; IMAGE entities must own to this, never 0. */ +const DXF_MODEL_SPACE_HANDLE = '1F'; + +/** + * R2000 tables/blocks BricsCAD needs. Missing BLOCK_RECORD *MODEL_SPACE causes "Null object Id: (0)". + */ +function dxfR2000Preamble() { + const ms = DXF_MODEL_SPACE_HANDLE; + const ps = '1B'; + return [ + '0', 'SECTION', '2', 'HEADER', + '9', '$ACADVER', '1', 'AC1015', + '9', '$HANDSEED', '5', 'FFFF', + '9', '$INSUNITS', '70', '6', + '9', '$MEASUREMENT', '70', '1', + '0', 'ENDSEC', + '0', 'SECTION', '2', 'TABLES', + '0', 'TABLE', '2', 'VPORT', '5', '8', '100', 'AcDbSymbolTable', '70', '1', + '0', 'VPORT', '5', '29', '330', '8', '100', 'AcDbSymbolTableRecord', '100', 'AcDbViewportTableRecord', + '2', '*ACTIVE', '70', '0', + '10', '0.0', '20', '0.0', '11', '1.0', '21', '1.0', + '12', '0.0', '22', '0.0', '13', '0.0', '23', '0.0', + '14', '0.5', '24', '0.5', '15', '0.5', '25', '0.5', + '16', '0.0', '26', '0.0', '36', '1.0', + '17', '0.0', '27', '0.0', '37', '0.0', + '40', '297.0', '41', '1.6', '42', '50.0', '43', '0.0', '44', '0.0', + '50', '0.0', '51', '0.0', '71', '0', '72', '100', '73', '1', '74', '3', + '75', '0', '76', '0', '77', '0', '78', '0', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'LTYPE', '5', '5', '100', 'AcDbSymbolTable', '70', '4', + '0', 'LTYPE', '5', '6', '330', '5', '100', 'AcDbSymbolTableRecord', '100', 'AcDbLinetypeTableRecord', + '2', 'BYBLOCK', '70', '0', '3', '', '72', '65', '73', '0', '40', '0.0', + '0', 'LTYPE', '5', '7', '330', '5', '100', 'AcDbSymbolTableRecord', '100', 'AcDbLinetypeTableRecord', + '2', 'BYLAYER', '70', '0', '3', '', '72', '65', '73', '0', '40', '0.0', + '0', 'LTYPE', '5', '9', '330', '5', '100', 'AcDbSymbolTableRecord', '100', 'AcDbLinetypeTableRecord', + '2', 'CONTINUOUS', '70', '0', '3', 'Solid line', '72', '65', '73', '0', '40', '0.0', + '0', 'LTYPE', '5', 'A', '330', '5', '100', 'AcDbSymbolTableRecord', '100', 'AcDbLinetypeTableRecord', + '2', 'DASHED', '70', '0', '3', '_ _ _ _ _ _', '72', '65', '73', '2', '40', '2.0', '49', '1.25', '49', '-0.75', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'LAYER', '5', '2', '100', 'AcDbSymbolTable', '70', '1', + '0', 'LAYER', '5', '10', '330', '2', '100', 'AcDbSymbolTableRecord', '100', 'AcDbLayerTableRecord', + '2', '0', '70', '0', '62', '7', '6', 'CONTINUOUS', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'STYLE', '5', '3', '100', 'AcDbSymbolTable', '70', '1', + '0', 'STYLE', '5', '11', '330', '3', '100', 'AcDbSymbolTableRecord', '100', 'AcDbTextStyleTableRecord', + '2', 'STANDARD', '70', '0', '40', '0.0', '41', '1.0', '50', '0.0', '71', '0', '42', '2.5', '3', 'txt', '4', '', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'VIEW', '5', '4', '100', 'AcDbSymbolTable', '70', '0', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'UCS', '5', '32', '100', 'AcDbSymbolTable', '70', '0', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'APPID', '5', '12', '100', 'AcDbSymbolTable', '70', '1', + '0', 'APPID', '5', '13', '330', '12', '100', 'AcDbSymbolTableRecord', '100', 'AcDbRegAppTableRecord', + '2', 'ACAD', '70', '0', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'DIMSTYLE', '5', '14', '100', 'AcDbSymbolTable', '70', '1', + '0', 'DIMSTYLE', '105', '15', '330', '14', '100', 'AcDbSymbolTableRecord', '100', 'AcDbDimStyleTableRecord', + '2', 'STANDARD', '70', '0', + '0', 'ENDTAB', + '0', 'TABLE', '2', 'BLOCK_RECORD', '5', '1', '100', 'AcDbSymbolTable', '70', '2', + '0', 'BLOCK_RECORD', '5', ms, '330', '1', '100', 'AcDbSymbolTableRecord', '100', 'AcDbBlockTableRecord', + '2', '*MODEL_SPACE', + '0', 'BLOCK_RECORD', '5', ps, '330', '1', '100', 'AcDbSymbolTableRecord', '100', 'AcDbBlockTableRecord', + '2', '*PAPER_SPACE', + '0', 'ENDTAB', + '0', 'ENDSEC', + '0', 'SECTION', '2', 'BLOCKS', + '0', 'BLOCK', '5', '20', '330', ms, '100', 'AcDbEntity', '8', '0', '100', 'AcDbBlockBegin', + '2', '*MODEL_SPACE', '70', '0', '10', '0.0', '20', '0.0', '30', '0.0', '3', '*MODEL_SPACE', '1', '', + '0', 'ENDBLK', '5', '21', '330', ms, '100', 'AcDbEntity', '8', '0', '100', 'AcDbBlockEnd', + '0', 'BLOCK', '5', '22', '330', ps, '100', 'AcDbEntity', '8', '0', '100', 'AcDbBlockBegin', + '2', '*PAPER_SPACE', '70', '0', '10', '0.0', '20', '0.0', '30', '0.0', '3', '*PAPER_SPACE', '1', '', + '0', 'ENDBLK', '5', '23', '330', ps, '100', 'AcDbEntity', '8', '0', '100', 'AcDbBlockEnd', + '0', 'ENDSEC' + ].join('\n') + '\n'; +} + +const DXF_ENTITIES_CLOSE = '0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n'; + +function dxfBaseObjectsSection() { + return '0\nSECTION\n2\nOBJECTS\n' + + '0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nACAD_GROUP\n350\nD\n' + + '0\nDICTIONARY\n5\nD\n330\nC\n100\nAcDbDictionary\n281\n1\n' + + '0\nENDSEC\n'; +} + +function insertDxfEntities(dxfContent, block) { + if (!block) return dxfContent; + return dxfContent.replace(DXF_ENTITIES_CLOSE, block + DXF_ENTITIES_CLOSE); +} + /** * Convex hull (Graham scan). Returns hull points in CCW order. */ @@ -640,7 +773,7 @@ function appendLotsToDXF(dxfContent, lots) { block += `0\nLINE\n8\nLOTS\n62\n40\n10\n${a.x}\n20\n${a.y}\n11\n${b.x}\n21\n${b.y}\n`; } }); - return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF'); + return insertDxfEntities(dxfContent, block); } /** @@ -848,7 +981,7 @@ function appendImageryTraceToDXF(dxfContent, polylines, minSegmentMeters, minLen block += `0\nLINE\n8\n${layer}\n62\n7\n10\n${a.x}\n20\n${a.y}\n11\n${b.x}\n21\n${b.y}\n`; } }); - return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF'); + return insertDxfEntities(dxfContent, block); } /** @@ -889,22 +1022,26 @@ function generateWorldFilePgw(minX, minY, maxX, maxY, widthPx, heightPx, rowZero } /** - * 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. - * imageFilename: e.g. "satellite.png" (same folder as DXF). - * minX, minY, maxX, maxY: extent in drawing units (meters from origin). Image is placed to fill this rect. - * widthPx, heightPx: image size in pixels. + * Append a georeferenced IMAGE already attached in the DXF (AutoCAD/BricsCAD IMAGE). + * PNG must sit next to the DXF using imageFilename. Insertion is SW corner; size fills the selected extent. + * 1 drawing unit = 1 meter ($INSUNITS=6). U/V are meters per pixel so CAD scale matches the selection. */ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX, maxY, widthPx, heightPx) { - const handle = '1F0'; const w = maxX - minX; const h = maxY - minY; + if (!(widthPx > 0) || !(heightPx > 0) || !(w > 0) || !(h > 0)) return dxfContent; const uPerPx = w / widthPx; const vPerPx = h / heightPx; + const clipU = widthPx - 0.5; + const clipV = heightPx - 0.5; + const imageHandle = 'A4'; + const defHandle = 'A2'; + const reactorHandle = 'A3'; + const imageDictHandle = 'A1'; + const safeName = String(imageFilename || 'satellite.png').replace(/[\r\n]/g, ''); 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'; const boxLines = @@ -913,12 +1050,30 @@ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX, `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${maxX}\n20\n${maxY}\n30\n0\n11\n${minX}\n21\n${maxY}\n31\n0\n` + `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${minX}\n20\n${maxY}\n30\n0\n11\n${minX}\n21\n${minY}\n31\n0\n`; const imageEntity = - `0\nIMAGE\n8\nSATELLITE_IMAGERY\n10\n${minX}\n20\n${minY}\n30\n0\n` + + `0\nIMAGE\n5\n${imageHandle}\n330\n${DXF_MODEL_SPACE_HANDLE}\n100\nAcDbEntity\n8\nSATELLITE_IMAGERY\n100\nAcDbRasterImage\n90\n0\n` + + `10\n${minX}\n20\n${minY}\n30\n0\n` + `11\n${uPerPx}\n21\n0\n31\n0\n12\n0\n22\n${vPerPx}\n32\n0\n` + - `13\n${widthPx}\n23\n${heightPx}\n340\n${handle}\n`; + `13\n${widthPx}\n23\n${heightPx}\n340\n${defHandle}\n70\n7\n280\n0\n281\n50\n282\n50\n283\n0\n360\n${reactorHandle}\n` + + `71\n1\n91\n2\n14\n-0.5\n24\n-0.5\n14\n${clipU}\n24\n${clipV}\n`; + const classes = + `0\nSECTION\n2\nCLASSES\n` + + `0\nCLASS\n1\nIMAGE\n2\nAcDbRasterImage\n3\nISM\n90\n127\n91\n0\n280\n0\n281\n1\n` + + `0\nCLASS\n1\nIMAGEDEF\n2\nAcDbRasterImageDef\n3\nISM\n90\n0\n91\n0\n280\n0\n281\n0\n` + + `0\nCLASS\n1\nIMAGEDEF_REACTOR\n2\nAcDbRasterImageDefReactor\n3\nISM\n90\n0\n91\n0\n280\n0\n281\n0\n` + + `0\nENDSEC\n`; const objectsSection = `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 + scaleNote + imageEntity + '0\nENDSEC\n' + objectsSection); + `0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nACAD_GROUP\n350\nD\n3\nACAD_IMAGE_DICT\n350\n${imageDictHandle}\n` + + `0\nDICTIONARY\n5\nD\n330\nC\n100\nAcDbDictionary\n281\n1\n` + + `0\nDICTIONARY\n5\n${imageDictHandle}\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSATELLITE\n350\n${defHandle}\n` + + `0\nIMAGEDEF\n5\n${defHandle}\n330\n${imageDictHandle}\n100\nAcDbRasterImageDef\n90\n0\n1\n${safeName}\n` + + `10\n${widthPx}\n20\n${heightPx}\n280\n1\n281\n0\n11\n${uPerPx}\n21\n${vPerPx}\n` + + `0\nIMAGEDEF_REACTOR\n5\n${reactorHandle}\n330\n${imageHandle}\n100\nAcDbRasterImageDefReactor\n90\n2\n330\n${imageHandle}\n` + + `0\nENDSEC\n`; + let out = dxfContent; + if (out.indexOf('\n2\nCLASSES\n') === -1) { + out = out.replace('0\nENDSEC\n0\nSECTION\n2\nTABLES\n', '0\nENDSEC\n' + classes + '0\nSECTION\n2\nTABLES\n'); + } + out = insertDxfEntities(out, boxLines + scaleNote + imageEntity); + return out.replace(dxfBaseObjectsSection(), objectsSection); } diff --git a/public/index.html b/public/index.html index 323cb31..f589140 100644 --- a/public/index.html +++ b/public/index.html @@ -153,10 +153,10 @@

MAPS to DXF

-

Enter an address or place name, or paste a link: Google Earth https://earth.google.com/web/search/ (search URL), or Google Maps / Earth view URL. Load preview, then export DXF.

+

Paste a Google Maps pin URL for the exact building (best). Typed addresses use OpenStreetMap, not Google — they can land on the street or town. Satellite is Esri/USGS, not Google imagery.

- + Show satellite imagery + -

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.

+

Satellite is Esri (not Google). If it looks fuzzy, switch to Esri Clarity and zoom so the building fills more of the view. Cyan = buildings, purple = OSM, orange = fences.

Imagery trace tuning (brightness, contrast, edge sensitivity)
@@ -236,8 +241,8 @@
- - 175 + + 150
@@ -258,6 +263,7 @@ + @@ -268,7 +274,7 @@
-

Site-plan style: roads (light blue), buildings (purple, hatched in DXF), trees (green), open land (light green), parking (red rectangles). Generate drawing from imagery uses edge trace (optional OSM snap). Server-side ML uses Python segmentation when enabled; Threshold mode uses NYPL map-vectorizer-style brightness/contrast/threshold for line-drawing maps. Export DXF embeds the satellite image in a single ZIP (unzip to use in CAD). Use Set image bounds (orange box) to choose the satellite image extent. Center = map origin. Drag to pan, scroll to zoom.

+

Site-plan style: roads (light blue), buildings (purple, hatched in DXF), trees (green), open land (light green), parking (red rectangles). Generate drawing from imagery uses edge trace (optional OSM snap). Server-side ML uses Python segmentation when enabled; Threshold mode uses NYPL map-vectorizer-style brightness/contrast/threshold for line-drawing maps. Export DXF downloads a ZIP: unzip and open the DXF — the satellite image is already attached and scaled to the selected extent (orange box, or current view). Center = map origin. Zoom stops at the sharpest tile that exists. Drag to pan, scroll to zoom.

@@ -293,6 +299,11 @@ let showSatellite = false; const tileCache = {}; const TILE_SIZE = 256; + const ADVERTISED_MAX_ZOOM = { esri: 19, clarity: 19, usgs: 16 }; + const nativeMaxZoomBySource = { esri: 19, clarity: 19, usgs: 16 }; + const nativeZoomHits = {}; + let tileProbeGen = 0; + let clampRedrawTimer = null; const METERS_PER_LAT = 111132.92; let drawLotMode = false; let editLotMode = false; @@ -371,8 +382,13 @@ const el = document.getElementById('chkLayer_' + key); opts[key] = el ? el.checked : true; }); + opts.locationMarker = showLocationMarker(); return opts; } + function showLocationMarker() { + const el = document.getElementById('chkLocationMarker'); + return !el || el.checked; + } function refreshPreviewFromLayers() { if (osmData && centerOrigin) { previewData = buildPreviewData(osmData, centerOrigin, getLayerOptions()); @@ -403,9 +419,68 @@ y: (lat - centerOrigin.lat) * METERS_PER_LAT }; } + function advertisedMaxZoomForSource(source) { + return ADVERTISED_MAX_ZOOM[source] || 21; + } + function getMaxNativeTileZoom() { + const source = getEffectiveTileSource(); + const advertised = advertisedMaxZoomForSource(source); + const n = nativeMaxZoomBySource[source]; + return Math.max(1, Math.min(advertised, n != null ? n : advertised)); + } function capTileZoom(z) { - const maxZ = getEffectiveTileSource() === 'usgs' ? 16 : 19; - return Math.max(0, Math.min(maxZ, z)); + return Math.max(0, Math.min(getMaxNativeTileZoom(), z)); + } + function metersPerPixelForZoom(z) { + if (!centerOrigin) return 156543.03392 / Math.pow(2, z); + return 156543.03392 * Math.cos((centerOrigin.lat * Math.PI) / 180) / Math.pow(2, z); + } + function maxScaleForNativeTiles() { + return 1 / metersPerPixelForZoom(getMaxNativeTileZoom()); + } + function getMaxAllowedScale() { + if (!showSatellite || !centerOrigin) return MAX_SCALE; + return Math.min(MAX_SCALE, maxScaleForNativeTiles()); + } + function clampScaleToNativeTiles() { + if (!showSatellite || !centerOrigin) return false; + const maxS = getMaxAllowedScale(); + if (scale <= maxS) return false; + const mx = canvas.width / 2; + const my = canvas.height / 2; + const wx = (mx - offsetX) / scale; + const wy = (offsetY - my) / scale; + scale = maxS; + offsetX = mx - wx * scale; + offsetY = my + wy * scale; + return true; + } + function scheduleClampToNativeTiles() { + if (clampRedrawTimer) return; + clampRedrawTimer = setTimeout(function() { + clampRedrawTimer = null; + if (clampScaleToNativeTiles()) draw(); + }, 0); + } + function resetTileZoomCap() { + const source = getEffectiveTileSource(); + nativeMaxZoomBySource[source] = advertisedMaxZoomForSource(source); + nativeZoomHits[source] = {}; + } + function noteTileZoomPresent(source, z) { + const rec = nativeZoomHits[source] || (nativeZoomHits[source] = {}); + rec[z] = rec[z] || { ok: 0, miss: 0 }; + rec[z].ok++; + } + function noteTileZoomMissing(source, z) { + const rec = nativeZoomHits[source] || (nativeZoomHits[source] = {}); + rec[z] = rec[z] || { ok: 0, miss: 0 }; + rec[z].miss++; + if (rec[z].ok > 0) return; + if (z <= nativeMaxZoomBySource[source]) { + nativeMaxZoomBySource[source] = Math.max(1, z - 1); + scheduleClampToNativeTiles(); + } } function getTileZoom() { if (!centerOrigin) return 15; @@ -476,10 +551,7 @@ 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); - let zBase = capTileZoom(Math.round(z)); - const span = Math.max(w, h); - if (getSatelliteSource() !== 'usgs' && span < 400) zBase = capTileZoom(zBase + 1); - return zBase; + return capTileZoom(Math.round(z)); } function getTilesInViewForExtent(minX, maxX, minY, maxY, z) { const tl = worldToLatLon(minX, maxY); @@ -519,7 +591,7 @@ } tiles.forEach(({ tx, ty, z: zz }) => { getTileImage(zz, tx, ty, (img) => { - if (!img.complete || !img.naturalWidth) { done(); return; } + if (!tileIsReady(img)) { done(); return; } const b = tileToLatLonBounds(tx, ty, zz); const tl = latLonToWorld(b.latMax, b.lonMin); const br = latLonToWorld(b.latMin, b.lonMax); @@ -534,16 +606,6 @@ }); }); } - 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) => { @@ -560,7 +622,7 @@ } tiles.forEach(({ tx, ty, z: zz }) => { getTileImage(zz, tx, ty, (img) => { - if (!img.complete || !img.naturalWidth) { done(); return; } + if (!tileIsReady(img)) { done(); return; } const b = tileToLatLonBounds(tx, ty, zz); const tl = latLonToWorld(b.latMax, b.lonMin); const br = latLonToWorld(b.latMin, b.lonMax); @@ -574,35 +636,175 @@ }); }); } + function tileIsReady(t) { + if (!t || t.pending || t.missing) return false; + if (t.naturalWidth > 0) return true; + return t.tagName === 'CANVAS' && t.width > 0; + } + function tileIsNoDataImage(img) { + if (!img || !tileIsReady(img)) return false; + try { + const s = 32; + const c = document.createElement('canvas'); + c.width = s; + c.height = s; + const ctx = c.getContext('2d', { willReadFrequently: true }); + if (!ctx) return false; + ctx.drawImage(img, 0, 0, s, s); + const data = ctx.getImageData(0, 0, s, s).data; + let sum = 0; + let sum2 = 0; + let satSum = 0; + const n = s * s; + for (let i = 0; i < data.length; i += 4) { + const r = data[i]; + const g = data[i + 1]; + const b = data[i + 2]; + const y = 0.299 * r + 0.587 * g + 0.114 * b; + sum += y; + sum2 += y * y; + const mx = r > g ? (r > b ? r : b) : (g > b ? g : b); + const mn = r < g ? (r < b ? r : b) : (g < b ? g : b); + satSum += mx - mn; + } + const mean = sum / n; + const variance = sum2 / n - mean * mean; + const sat = satSum / n; + return sat < 22 && variance < 500 && mean > 150 && mean < 230; + } catch (e) { + return false; + } + } + function cacheDecodedTile(key, blob) { + return new Promise(function(resolve, reject) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + const objUrl = URL.createObjectURL(blob); + img.onload = function() { + URL.revokeObjectURL(objUrl); + tileCache[key] = img; + resolve(img); + }; + img.onerror = function() { + URL.revokeObjectURL(objUrl); + delete tileCache[key]; + reject(new Error('tile decode failed')); + }; + img.src = objUrl; + }); + } function getTileImage(z, tx, ty, onLoad, onError) { const source = getEffectiveTileSource(); const key = source + '_' + z + '_' + tx + '_' + ty; if (tileCache[key]) { - if (tileCache[key].complete && tileCache[key].naturalWidth) onLoad(tileCache[key]); - else { - tileCache[key].addEventListener('load', () => onLoad(tileCache[key])); - tileCache[key].addEventListener('error', () => (onError && onError())); + if (tileIsReady(tileCache[key])) onLoad(tileCache[key]); + else if (tileCache[key].pending) tileCache[key].waiters.push({ onLoad: onLoad, onError: onError }); + else if (onError) onError(); + return; + } + const pending = { pending: true, waiters: [{ onLoad: onLoad, onError: onError }] }; + tileCache[key] = pending; + const ac = new AbortController(); + const timer = setTimeout(function() { ac.abort(); }, 20000); + fetch('/api/tile/' + z + '/' + ty + '/' + tx + '?source=' + encodeURIComponent(source), { signal: ac.signal }) + .then(function(r) { + clearTimeout(timer); + if (r.status === 404) { + noteTileZoomMissing(source, z); + throw new Error('missing'); + } + if (!r.ok) throw new Error('tile ' + r.status); + return r.blob(); + }) + .then(function(blob) { return cacheDecodedTile(key, blob); }) + .then(function(img) { + if (tileIsNoDataImage(img)) { + tileCache[key] = { missing: true }; + noteTileZoomMissing(source, z); + pending.waiters.forEach(function(w) { if (w.onError) w.onError(); }); + return; + } + noteTileZoomPresent(source, z); + pending.waiters.forEach(function(w) { w.onLoad(img); }); + }) + .catch(function() { + clearTimeout(timer); + if (tileIsReady(tileCache[key])) { + pending.waiters.forEach(function(w) { w.onLoad(tileCache[key]); }); + return; + } + delete tileCache[key]; + pending.waiters.forEach(function(w) { if (w.onError) w.onError(); }); + }); + } + async function probeNativeMaxZoom(force) { + if (!centerOrigin) return; + if (!showSatellite && !force) return; + const gen = ++tileProbeGen; + const source = getEffectiveTileSource(); + let best = 0; + const hits = nativeZoomHits[source]; + if (hits) { + Object.keys(hits).forEach(function(z) { + if (hits[z].ok > 0) best = Math.max(best, Number(z)); + }); + } + if (best > 0) { + nativeMaxZoomBySource[source] = best; + if (!force) { + clampScaleToNativeTiles(); + draw(); } return; } - const img = new Image(); - img.crossOrigin = 'anonymous'; - tileCache[key] = img; - const timer = setTimeout(function() { - if (!img.complete) { - img.src = ''; - if (onError) onError(); + const advertised = advertisedMaxZoomForSource(source); + for (let z = advertised; z >= 14; z--) { + if (gen !== tileProbeGen) return; + const t = latLonToTile(centerOrigin.lat, centerOrigin.lon, z); + const key = source + '_' + z + '_' + t.tx + '_' + t.ty; + let ok = false; + try { + if (tileCache[key] && tileCache[key].missing) { + ok = false; + } else if (tileIsReady(tileCache[key])) { + if (tileIsNoDataImage(tileCache[key])) { + tileCache[key] = { missing: true }; + ok = false; + } else { + ok = true; + } + } else { + const r = await fetch('/api/tile/' + z + '/' + t.ty + '/' + t.tx + '?source=' + encodeURIComponent(source)); + if (gen !== tileProbeGen) return; + if (r.ok) { + const img = await cacheDecodedTile(key, await r.blob()); + if (tileIsNoDataImage(img)) { + tileCache[key] = { missing: true }; + ok = false; + } else { + ok = true; + } + } + } + } catch (e) { + ok = false; } - }, 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); + if (ok) { + noteTileZoomPresent(source, z); + nativeMaxZoomBySource[source] = z; + if (!force) { + clampScaleToNativeTiles(); + draw(); + } + return; + } + noteTileZoomMissing(source, z); + } + nativeMaxZoomBySource[source] = 14; + if (!force) { + clampScaleToNativeTiles(); + draw(); + } } function drawSatelliteLayer() { if (!centerOrigin || !showSatellite) return; @@ -623,7 +825,7 @@ } tiles.forEach(({ tx, ty, z: zz }) => { getTileImage(zz, tx, ty, (img) => { - if (!img.complete || !img.naturalWidth) { done(); return; } + if (!tileIsReady(img)) { done(); return; } const b = tileToLatLonBounds(tx, ty, zz); const tl = latLonToWorld(b.latMax, b.lonMin); const br = latLonToWorld(b.latMin, b.lonMax); @@ -915,7 +1117,7 @@ drawImageryTraceLayer(); drawLotsLayer(); } - if (centerOrigin) drawOriginCrosshair(); + if (centerOrigin && showLocationMarker()) drawOriginCrosshair(); if (!hasMap && hasSite && !showSatellite) { ctx.fillStyle = 'rgba(166, 173, 200, 0.85)'; ctx.font = '13px sans-serif'; @@ -962,6 +1164,7 @@ scale = Math.min((cw - 2 * padding) / w, (ch - 2 * padding) / h); offsetX = cw / 2; offsetY = ch / 2; + clampScaleToNativeTiles(); draw(); } @@ -971,8 +1174,8 @@ } 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))); + const closeBig = Math.min(14, Math.max(6, Math.round(spanM / 16))); + const closeMid = Math.min(8, Math.max(3, Math.round(spanM / 32))); return { closeBig: closeBig, closeMid: closeMid }; } @@ -986,7 +1189,7 @@ 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 thresholdBlack = parseInt(document.getElementById('traceThreshold').value, 10) || 150; const useThreshold = !!(document.getElementById('chkThreshold') && document.getElementById('chkThreshold').checked); const buildingFootprints = !!(document.getElementById('chkBuildingFootprints') && document.getElementById('chkBuildingFootprints').checked); const traceFences = !!(document.getElementById('chkTraceFences') && document.getElementById('chkTraceFences').checked); @@ -1056,19 +1259,23 @@ try { const loc = await resolveLocation(input); centerOrigin = { lat: loc.lat, lon: loc.lon }; - const zoomM = getSiteZoomMeters(); + resetTileZoomCap(); + const zoomM = loc.viewMeters != null + ? Math.min(500, Math.max(50, loc.viewMeters)) + : getSiteZoomMeters(); zoomToSiteView(zoomM); const sat = document.getElementById('chkSatellite'); if (sat && !sat.checked) { sat.checked = true; showSatellite = true; - draw(); } + await probeNativeMaxZoom(); + draw(); const label = loc.displayName ? loc.displayName.split(',').slice(0, 2).join(',') : (loc.lat.toFixed(5) + ', ' + loc.lon.toFixed(5)); - setStatus('Centered on ' + label + ' (zoom ~' + zoomM + ' m — scroll out to see more). Load preview for roads/OSM.', false, true); - btnFit.disabled = false; + setStatus('Centered on ' + label + ' (zoom ~' + zoomM + ' m — scroll out to see more). Load preview for OSM roads, or Export DXF from satellite.', false, true); + enableDrawingTools(); if (document.getElementById('chkImageryTrace') && document.getElementById('chkImageryTrace').checked) { updatePreviewImageryTrace(); } @@ -1085,6 +1292,7 @@ scale = Math.min((cw - 2 * padding) / b.w, (ch - 2 * padding) / b.h); offsetX = cw / 2 - (b.minX + b.w / 2) * scale; offsetY = ch / 2 + (b.minY + b.h / 2) * scale; + clampScaleToNativeTiles(); draw(); scheduleTraceRefresh(); } @@ -1092,7 +1300,7 @@ 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)); + scale = Math.max(MIN_SCALE, Math.min(getMaxAllowedScale(), scale * factor)); offsetX = mx - wx * scale; offsetY = my + wy * scale; draw(); @@ -1221,7 +1429,7 @@ 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.'); + setStatus('Area set. Use "Detect buildings in boundary" for buildings inside this box, "Add selection as lot" for the property line, or "Detect lots" to auto-detect lots.'); draw(); return; } @@ -1257,14 +1465,30 @@ document.getElementById('chkSatellite').addEventListener('change', (e) => { showSatellite = e.target.checked; - draw(); + if (showSatellite) { + draw(); + probeNativeMaxZoom(); + } else { + draw(); + } scheduleTraceRefresh(); }); + const chkLocationMarker = document.getElementById('chkLocationMarker'); + if (chkLocationMarker) { + chkLocationMarker.addEventListener('change', () => { + if (osmData && centerOrigin) refreshPreviewFromLayers(); + else draw(); + }); + } const selSatelliteSource = document.getElementById('selSatelliteSource'); if (selSatelliteSource) { selSatelliteSource.addEventListener('change', () => { clearTileCache(); - draw(); + resetTileZoomCap(); + if (showSatellite) { + draw(); + probeNativeMaxZoom(); + } else draw(); scheduleTraceRefresh(); }); } @@ -1313,7 +1537,7 @@ 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()); + return fetchOsmForBbox(bbox, getSiteTraceOsmLayers(), { quiet: true }); } const PREVIEW_TRACE_SIZE = 1024; @@ -1782,8 +2006,8 @@ 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; + const lumOk = l >= curLum - 75 && l >= 60; + const colorOk = sat < 110 || l >= 130; if (lumOk && colorOk) { visited[ni] = 1; mask[ni] = 255; @@ -1797,10 +2021,13 @@ function permissiveRoofMask(data, gray, w, h, minLum) { const n = w * h; const out = new Uint8Array(n); + const min = minLum != null ? minLum : 95; for (let i = 0; i < n; i++) { const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2]; + if (g > r + 14 && g > b + 10 && g > 70) continue; const sat = Math.max(r, g, b) - Math.min(r, g, b); - if (gray[i] >= minLum && (sat < 75 || gray[i] >= 170)) out[i] = 255; + const l = gray[i]; + if (l >= min && (sat < 95 || l >= 130)) out[i] = 255; } return out; } @@ -1831,26 +2058,42 @@ components.sort((a, b) => b.length - a.length); return components; } + function grayStructureMask(data, gray, w, h) { + const n = w * h; + const out = new Uint8Array(n); + for (let i = 0; i < n; i++) { + const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2]; + if (g > r + 12 && g > b + 8 && g > 65) continue; + const sat = Math.max(r, g, b) - Math.min(r, g, b); + const l = gray[i]; + if (l < 48 || l > 242) continue; + if (sat > 80 && l < 150) continue; + out[i] = 255; + } + return out; + } function extractBuildingFootprintsFromImagery(data, gray, ow, oh, minX, maxX, minY, maxY, options) { const worldW = maxX - minX; const worldH = maxY - minY; const worldAreaM2 = worldW * worldH; const spanM = Math.max(worldW, worldH); const pxPerM2 = (ow * oh) / Math.max(worldAreaM2, 1); - const minAreaM2 = spanM <= 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 minAreaM2 = spanM <= 160 + ? Math.max(18, worldAreaM2 * 0.004) + : Math.max(40, worldAreaM2 * 0.002); + const minPx = Math.max(20, Math.floor(minAreaM2 * pxPerM2 * 0.35)); + const maxPx = Math.floor(120000 * pxPerM2); + const roofBright = options.roofBright != null ? options.roofBright : 150; const brightness = options.brightness != null ? options.brightness : 0; const contrast = options.contrast != null ? options.contrast : 1; const tuned = applyBrightnessContrast(gray, ow, oh, brightness, contrast); const radii = morphCloseRadii(spanM); const maskBuilders = [ - () => permissiveRoofMask(data, tuned, ow, oh, roofBright - 30), - () => permissiveRoofMask(data, tuned, ow, oh, roofBright - 45), - () => seedGrowRoofMask(data, tuned, ow, oh, 0.9), + () => permissiveRoofMask(data, tuned, ow, oh, Math.max(70, roofBright - 55)), + () => permissiveRoofMask(data, tuned, ow, oh, Math.max(55, roofBright - 80)), + () => seedGrowRoofMask(data, tuned, ow, oh, 0.82), + () => seedGrowRoofMask(data, tuned, ow, oh, 0.7), + () => grayStructureMask(data, tuned, ow, oh), () => localAdaptiveRoofMask(data, tuned, ow, oh, roofBright) ]; let bestPolys = []; @@ -1861,7 +2104,7 @@ 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++) { + for (let ci = 0; ci < components.length && ci < 14; ci++) { const poly = componentToAabbPolygon(components[ci], ow, oh, minX, maxX, minY, maxY); if (polygonAreaWorld(poly) >= minAreaM2) polylines.push(poly); } @@ -1871,7 +2114,7 @@ bestScore = filteredScore; bestPolys = filtered; } - if (filtered.length >= 1 && filteredScore > worldAreaM2 * 0.015) break; + if (filtered.length >= 1 && filteredScore > worldAreaM2 * 0.008) break; } return bestPolys; } @@ -1954,10 +2197,10 @@ return fences.sort((a, b) => polygonPerimeter(b) - polygonPerimeter(a)).slice(0, 24); } function filterBuildingFootprints(polylines, minAreaM2) { - const minArea = minAreaM2 != null ? minAreaM2 : 150; + const minArea = minAreaM2 != null ? minAreaM2 : 40; return polylines.filter((poly) => { const area = polygonAreaWorld(poly); - if (area < minArea || area > 80000) return false; + if (area < minArea || area > 120000) return false; let perim = 0; for (let i = 0; i < poly.length; i++) { const a = poly[i], b = poly[(i + 1) % poly.length]; @@ -2291,12 +2534,120 @@ draw(); } + function rectToPolygon(r) { + return [ + { x: r.minX, y: r.minY }, + { x: r.maxX, y: r.minY }, + { x: r.maxX, y: r.maxY }, + { x: r.minX, y: r.maxY } + ]; + } + function polygonBounds(poly) { + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; + poly.forEach(function(p) { + if (p.x < minX) minX = p.x; + if (p.x > maxX) maxX = p.x; + if (p.y < minY) minY = p.y; + if (p.y > maxY) maxY = p.y; + }); + return { minX: minX, maxX: maxX, minY: minY, maxY: maxY }; + } + function getActiveBoundary() { + if (detectionRect) { + return { poly: rectToPolygon(detectionRect), bounds: detectionRect, label: 'selected area' }; + } + if (lots.length) { + const poly = lots[lots.length - 1]; + if (poly && poly.length >= 3) { + return { poly: poly, bounds: polygonBounds(poly), label: 'drawn lot' }; + } + } + return null; + } + function polyInsideBoundary(poly, boundary) { + if (!poly || poly.length < 1 || !boundary) return false; + const c = polyCentroid(poly); + if (pointInPolygon(c.x, c.y, boundary)) return true; + let hits = 0; + for (let i = 0; i < poly.length; i++) { + if (pointInPolygon(poly[i].x, poly[i].y, boundary)) hits++; + } + return hits >= Math.min(3, poly.length); + } + async function detectBuildingsInBoundary() { + if (!centerOrigin) { + setStatus('Go to an address first, then select a detection area or draw a lot.', true); + return; + } + const boundary = getActiveBoundary(); + if (!boundary) { + setStatus('Select a detection area (blue box) or draw a lot first, then detect buildings in that boundary.', true); + return; + } + const sat = document.getElementById('chkSatellite'); + if (sat && !sat.checked) { + sat.checked = true; + showSatellite = true; + } + const r = boundary.bounds; + const spanM = Math.max(r.maxX - r.minX, r.maxY - r.minY); + if (spanM < 8) { + setStatus('Boundary is too small. Draw a larger area around the buildings.', true); + return; + } + setStatus('Detecting buildings inside ' + boundary.label + '…'); + const spec = extentToImagePixels(r.minX, r.maxX, r.minY, r.maxY, getTracePixelSize(spanM)); + const off = await drawSatelliteForExtent(r.minX, r.maxX, r.minY, r.maxY, spec.width, spec.height); + if (!off) { + setStatus('Could not load satellite tiles for that boundary.', true); + draw(); + return; + } + const octx = off.getContext('2d'); + let id; + try { + id = octx.getImageData(0, 0, off.width, off.height); + } catch (e) { + setStatus('Canvas access blocked. Run with Start.bat and open http://localhost:3456.', true); + return; + } + const gray = grayscale(id.data, off.width, off.height); + const blurred = blur(gray, off.width, off.height); + const tune = getTraceTuneOptions(); + let buildings = extractBuildingFootprintsFromImagery(id.data, blurred, off.width, off.height, r.minX, r.maxX, r.minY, r.maxY, tune); + buildings = buildings.filter(function(poly) { return polyInsideBoundary(poly, boundary.poly); }); + let osmN = 0; + if (osmData && centerOrigin && typeof getOSMBuildingFootprints === 'function') { + const osm = getOSMBuildingFootprints(osmData, centerOrigin).filter(function(poly) { + return polyInsideBoundary(poly, boundary.poly); + }); + previewOsmBuildingPolylines = osm; + osmN = osm.length; + } + previewImageryTracePolylines = buildings; + const n = buildings.length; + setStatus( + n > 0 + ? n + ' building(s) inside ' + boundary.label + (osmN ? ' (+' + osmN + ' OSM)' : '') + '. Export DXF to keep them on IMAGERY_BUILDINGS.' + : 'No buildings found in ' + boundary.label + '. Zoom to the roofs, use Esri, lower roof threshold, or draw the lot tighter around the building.', + n === 0, + n > 0 + ); + draw(); + } + const btnDetectLots = document.getElementById('btnDetectLots'); btnDetectLots.addEventListener('click', () => { btnDetectLots.disabled = true; detectLotsFromImagery().finally(() => { btnDetectLots.disabled = false; }); }); + const btnDetectBuildings = document.getElementById('btnDetectBuildings'); + btnDetectBuildings.addEventListener('click', () => { + btnDetectBuildings.disabled = true; + detectBuildingsInBoundary().finally(() => { btnDetectBuildings.disabled = false; }); + }); + const btnSelectArea = document.getElementById('btnSelectArea'); btnSelectArea.addEventListener('click', () => { if (selectAreaMode) { @@ -2382,27 +2733,46 @@ } async function resolveLocation(input) { - if (isGoogleEarthSearchUrl(input)) { - const coords = extractCoordinates(input); + let s = String(input).trim(); + if (typeof isGoogleMapsLink === 'function' && isGoogleMapsLink(s)) { + setStatus('Reading Google Maps pin…'); + const rr = await fetch('/api/maps-pin?url=' + encodeURIComponent(s)); + const pin = await rr.json(); + if (!rr.ok) throw new Error(pin.error || 'Could not read that Maps link.'); + return { + lat: pin.lat, + lon: pin.lon, + viewMeters: pin.viewMeters, + fromUrl: true, + displayName: pin.display_name || '' + }; + } + if (isGoogleEarthSearchUrl(s)) { + const coords = extractCoordinates(s); if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true }; - const earthSearch = extractGoogleEarthSearchQuery(input); + const earthSearch = extractGoogleEarthSearchQuery(s); if (earthSearch !== null) { const coordLike = /^-?\d+\.?\d*\s*,\s*-?\d+\.?\d*$/.test(earthSearch); if (coordLike) { const [lat, lon] = earthSearch.split(',').map((n) => parseFloat(n.trim())); if (!isNaN(lat) && !isNaN(lon)) return { lat, lon, viewMeters: undefined, fromUrl: true }; } - setStatus('Looking up Google Earth search…'); + setStatus('Looking up address…'); const res = await fetch('/api/geocode?q=' + encodeURIComponent(earthSearch)); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Geocoding failed'); return { lat: data.lat, lon: data.lon, viewMeters: undefined, fromUrl: false, displayName: data.display_name }; } } - const coords = extractCoordinates(input); + const coords = extractCoordinates(s); if (coords) return { lat: coords.lat, lon: coords.lon, viewMeters: coords.viewMeters, fromUrl: true }; + const mapsAddress = typeof extractAddressFromMapsUrl === 'function' ? extractAddressFromMapsUrl(s) : null; + const query = mapsAddress || s; + if (/^https?:/i.test(query)) { + throw new Error('Could not read a pin from that link. Open Google Maps, click the building, copy the URL, and paste that — or type the street address.'); + } setStatus('Looking up address…'); - const res = await fetch('/api/geocode?q=' + encodeURIComponent(input)); + const res = await fetch('/api/geocode?q=' + encodeURIComponent(query)); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Geocoding failed'); return { lat: data.lat, lon: data.lon, viewMeters: undefined, fromUrl: false, displayName: data.display_name }; @@ -2430,7 +2800,8 @@ return { version: 0.6, elements: elements }; } - async function fetchOsmForBbox(bbox, layers) { + async function fetchOsmForBbox(bbox, layers, options) { + const quiet = options && options.quiet; const planRes = await fetch('/api/overpass/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -2441,21 +2812,36 @@ 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; + if (!quiet) { + setStatus(tiles.length > 1 + ? 'Fetching map data (' + (i + 1) + ' of ' + tiles.length + ') — throttled to avoid rate limits…' + : 'Fetching map data (throttled so OSM stays available)…'); } - results.push(data); + let lastErr = null; + for (let attempt = 0; attempt < 3; attempt++) { + const res = await fetch('/api/overpass', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...tiles[i], layers: layers }) + }); + let data = {}; + try { data = await res.json(); } catch (_) {} + if (res.ok) { + results.push(data); + lastErr = null; + break; + } + lastErr = new Error(data.error || 'Request failed'); + lastErr.status = res.status; + const waitMs = data.retryAfterMs || (res.status === 429 ? 8000 : 2500 * (attempt + 1)); + if (attempt < 2 && (res.status === 429 || res.status === 502 || res.status === 503)) { + if (!quiet) setStatus('Map server busy — waiting ' + Math.round(waitMs / 1000) + 's then retrying…'); + await new Promise(function(r) { setTimeout(r, waitMs); }); + continue; + } + throw lastErr; + } + if (lastErr) throw lastErr; } const merged = mergeOsmResults(results); if (tiles.length > 1) { @@ -2464,6 +2850,21 @@ return merged; } + function enableDrawingTools() { + btnFit.disabled = false; + btnExport.disabled = false; + btnDrawLot.disabled = false; + btnCloseLot.disabled = false; + btnClearLots.disabled = false; + document.getElementById('btnEditLots').disabled = false; + document.getElementById('btnDetectLots').disabled = false; + document.getElementById('btnDetectBuildings').disabled = false; + document.getElementById('btnSelectArea').disabled = false; + document.getElementById('btnClearArea').disabled = false; + document.getElementById('btnSetImageBounds').disabled = false; + document.getElementById('btnClearImageBounds').disabled = false; + } + function bboxFromCenter(lat, lon, radiusMeters) { const cosLat = Math.cos((lat * Math.PI) / 180); viewRadiusLatDeg = radiusMeters / 111320; @@ -2486,6 +2887,7 @@ try { const loc = await resolveLocation(input); centerOrigin = { lat: loc.lat, lon: loc.lon }; + resetTileZoomCap(); const radiusM = getAreaRadiusMeters(loc); const bbox = bboxFromCenter(loc.lat, loc.lon, radiusM); const layers = getLayerOptions(); @@ -2494,25 +2896,17 @@ 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); + enableDrawingTools(); + setStatus('No OSM features in this area. Satellite is still available — generate drawing from imagery and Export DXF.', true); return; } previewData = buildPreviewData(osmData, centerOrigin, layers); previewImageryTracePolylines = []; previewImageryFencePolylines = []; - 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; + enableDrawingTools(); fitView(); zoomToSiteView(getSiteZoomMeters()); + if (showSatellite) await probeNativeMaxZoom(); let msg = loc.fromUrl ? 'Preview loaded. Click Export DXF to download.' : 'Found: ' + (loc.displayName || '').split(',').slice(0, 2).join(',') + '. Preview loaded.'; if (data._meta && data._meta.tiles > 1) { msg += ' (' + data._meta.elementCount + ' features from ' + data._meta.tiles + ' map tiles)'; @@ -2524,10 +2918,11 @@ updatePreviewImageryTrace(); } } catch (e) { + if (centerOrigin) enableDrawingTools(); 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); + ? ' OSM is rate-limited. Wait, then retry Load preview — or use satellite + Generate drawing from imagery and Export DXF now.' + : ' You can still use satellite imagery, Generate drawing from imagery, and Export DXF without OSM.'; + setStatus((e.message || 'Failed to load OSM map data.') + hint, true); } finally { btnLoad.disabled = false; } @@ -2536,10 +2931,11 @@ btnFit.addEventListener('click', fitView); btnExport.addEventListener('click', async () => { - if (!osmData || !centerOrigin) { - setStatus('Load a preview first.', true); + if (!centerOrigin) { + setStatus('Go to an address or load a preview first.', true); return; } + if (!osmData) osmData = { elements: [] }; const baseName = 'Map_RailFixed_' + centerOrigin.lat + '_' + centerOrigin.lon; const dxfFileName = baseName + '.dxf'; const pngFileName = baseName + '.png'; @@ -2608,9 +3004,15 @@ } } if (!useImageryTrace) setStatus('Exporting (building satellite image)…'); + await probeNativeMaxZoom(true); + if (!imageryTraceClassified && (!imageryTracePolylines || !imageryTracePolylines.length) && previewImageryTracePolylines.length) { + imageryTracePolylines = previewImageryTracePolylines; + } + if ((!imageryFencePolylines || !imageryFencePolylines.length) && previewImageryFencePolylines.length) { + imageryFencePolylines = previewImageryFencePolylines; + } const imgSpec = extentToImagePixels(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, IMAGE_MAX_EDGE); - const imgCanvasRaw = await drawSatelliteForExtent(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, imgSpec.width, imgSpec.height); - const imgCanvas = imgCanvasRaw ? flipCanvasVertical(imgCanvasRaw) : null; + const imgCanvas = await drawSatelliteForExtent(exportExtent.minX, exportExtent.maxX, exportExtent.minY, exportExtent.maxY, imgSpec.width, imgSpec.height); let dxfContent = generateHighDetailDXF(osmData, centerOrigin, getLayerOptions(), exportExtent); if (imageryTraceClassified) { if (imageryTraceClassified.buildings.length) dxfContent = appendImageryTraceToDXF(dxfContent, imageryTraceClassified.buildings, 0.2, 0.5, 'IMAGERY_BUILDINGS'); @@ -2623,17 +3025,16 @@ dxfContent = appendImageryTraceToDXF(dxfContent, imageryFencePolylines, 0.2, 1, 'IMAGERY_FENCES'); } dxfContent = appendLotsToDXF(dxfContent, lots); - const EMBEDDED_IMAGE_FILENAME = 'satellite.png'; - const PGW_FILENAME = 'satellite.pgw'; + const pgwFileName = baseName + '.pgw'; if (imgCanvas) { - dxfContent = appendSatelliteImageToDXF(dxfContent, EMBEDDED_IMAGE_FILENAME, exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height); + dxfContent = appendSatelliteImageToDXF(dxfContent, pngFileName, exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height); } if (imgCanvas && typeof JSZip !== 'undefined') { const zip = new JSZip(); zip.file(dxfFileName, dxfContent, { binary: false }); const pngBlob = await new Promise((res) => imgCanvas.toBlob(res, 'image/png')); - zip.file(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 }); + zip.file(pngFileName, pngBlob, { binary: true }); + zip.file(pgwFileName, generateWorldFilePgw(exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height, false), { binary: false }); const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipUrl = URL.createObjectURL(zipBlob); const aZip = document.createElement('a'); @@ -2657,19 +3058,19 @@ 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 pgwBlob = new Blob([generateWorldFilePgw(exportExtent.minX, exportExtent.minY, exportExtent.maxX, exportExtent.maxY, imgSpec.width, imgSpec.height, false)], { type: 'text/plain' }); const pgwUrl = URL.createObjectURL(pgwBlob); const aPgw = document.createElement('a'); aPgw.href = pgwUrl; - aPgw.download = 'satellite.pgw'; + aPgw.download = pgwFileName; aPgw.click(); URL.revokeObjectURL(pgwUrl); } } let statusMsg = imgCanvas && typeof JSZip !== 'undefined' - ? 'Downloaded ' + baseName + '.zip (DXF + satellite.png + satellite.pgw). Unzip and open the DXF in CAD — 1 unit = 1 meter.' + ? 'Downloaded ' + baseName + '.zip. Unzip and open the DXF — satellite is already attached and scaled to the selected extent (1 unit = 1 meter).' : imgCanvas - ? 'Downloaded ' + dxfFileName + ' and ' + pngFileName + '. Keep both in the same folder for CAD.' + ? 'Downloaded ' + dxfFileName + ' and ' + pngFileName + '. Keep both in the same folder so CAD can show the attached image.' : 'Downloaded: ' + dxfFileName; if (imgCanvas) { statusMsg += ' Image extent: ' + imgSpec.widthMeters.toFixed(1) + ' m × ' + imgSpec.heightMeters.toFixed(1) diff --git a/server.js b/server.js index d53234e..679ee7a 100644 --- a/server.js +++ b/server.js @@ -4,50 +4,100 @@ */ const express = require('express'); const path = require('path'); -const { exec } = require('child_process'); +const { exec, spawn, execSync } = require('child_process'); +const fs = require('fs'); const multer = require('multer'); const app = express(); const PORT = process.env.PORT || 3456; -const URL = `http://localhost:${PORT}`; +const APP_URL = `http://localhost:${PORT}`; const ML_SEGMENT_URL = process.env.ML_SEGMENT_URL || 'http://127.0.0.1:3457'; const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 16 * 1024 * 1024 } }); function openBrowser() { const plat = process.platform; - const cmd = plat === 'win32' ? `start "" "${URL}"` : plat === 'darwin' ? `open "${URL}"` : `xdg-open "${URL}"`; + const cmd = plat === 'win32' ? `start "" "${APP_URL}"` : plat === 'darwin' ? `open "${APP_URL}"` : `xdg-open "${APP_URL}"`; exec(cmd, () => {}); } app.use(express.json({ limit: '1mb' })); app.use(express.static(path.join(__dirname, 'public'))); -// Public Overpass mirrors; rotated and retried on 429/503/504. +// Public Overpass mirrors. Prefer instances without tight rate limits; skip a host after it fails. const OVERPASS_ENDPOINTS = [ - 'https://overpass.kumi.systems/api/interpreter', - 'https://overpass-api.de/api/interpreter', 'https://overpass.openstreetmap.fr/api/interpreter', + 'https://overpass-api.de/api/interpreter', + 'https://lz4.overpass-api.de/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_USER_AGENT = 'MAPS-to-DXF-standalone/1.1 (local CAD export tool; contact: local user)'; +const OVERPASS_MIN_INTERVAL_MS = Number(process.env.OVERPASS_MIN_INTERVAL_MS) || 800; +const OVERPASS_FAILOVER_GAP_MS = 200; +const OVERPASS_BACKOFF_BASE_MS = Number(process.env.OVERPASS_BACKOFF_BASE_MS) || 800; 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]); +const OVERPASS_CACHE_TTL_MS = Number(process.env.OVERPASS_CACHE_TTL_MS) || 5 * 60 * 1000; +const OVERPASS_TIMEOUT_FAST_MS = Number(process.env.OVERPASS_TIMEOUT_FAST_MS) || 8000; +const OVERPASS_TIMEOUT_SLOW_MS = Number(process.env.OVERPASS_TIMEOUT_SLOW_MS) || 12000; +const RETRYABLE_OVERPASS_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 524]); let lastOverpassRequestAt = 0; +let lastGoodEndpointIdx = 0; +let throttleChain = Promise.resolve(); +const overpassCache = new Map(); +const endpointCooldownUntil = new Map(); 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 throttleOverpass(intervalMs) { + const min = intervalMs == null ? OVERPASS_MIN_INTERVAL_MS : intervalMs; + const run = throttleChain.then(async () => { + const now = Date.now(); + const wait = min - (now - lastOverpassRequestAt); + if (wait > 0) await sleep(wait); + lastOverpassRequestAt = Date.now(); + }); + throttleChain = run.catch(() => {}); + return run; +} + +function isRetryableOverpassError(e) { + if (!e) return false; + if (e.retryable === true) return true; + if (RETRYABLE_OVERPASS_STATUSES.has(e.status)) return true; + if (e.name === 'AbortError' || /timed out|timeout|rate.?limit|too many|unavailable|error page/i.test(e.message || '')) return true; + return e.retryable !== false; +} + +function markEndpointCooldown(url, ms) { + const until = Date.now() + Math.max(ms, 5000); + endpointCooldownUntil.set(url, until); +} + +function isEndpointCooling(url) { + return Date.now() < (endpointCooldownUntil.get(url) || 0); +} + +function cacheKey(bbox, layers) { + return JSON.stringify({ bbox, layers: layers || null }); +} + +function cacheGet(key) { + const hit = overpassCache.get(key); + if (!hit) return null; + if (Date.now() - hit.at > OVERPASS_CACHE_TTL_MS) { + overpassCache.delete(key); + return null; + } + return hit.data; +} + +function cacheSet(key, data) { + overpassCache.set(key, { at: Date.now(), data }); + if (overpassCache.size > 40) { + overpassCache.delete(overpassCache.keys().next().value); + } } function layerEnabled(layers, key) { @@ -81,7 +131,7 @@ function buildOverpassQuery(bbox, layers) { if (parts.length === 0) { parts.push(`way["highway"]${b};`); } - return `[out:json][timeout:15];(${parts.join('')});(._;>;);out body;`; + return `[out:json][timeout:10];(${parts.join('')});(._;>;);out body qt;`; } function splitBbox(bbox) { @@ -114,36 +164,51 @@ function splitBbox(bbox) { function parseOverpassResponse(text, status) { const looksLikeJson = /^\s*[\{\[]/.test(text); if (!looksLikeJson) { - const err = /<[?]xml| controller.abort(), timeoutMs); try { const r = await fetch(url, { method: 'POST', - body: query, + body: new URLSearchParams({ data: query }).toString(), headers: { - 'Content-Type': 'text/plain', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'Accept': 'application/json', 'User-Agent': OVERPASS_USER_AGENT }, signal: controller.signal @@ -153,15 +218,16 @@ async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) { 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.retryable = parsed.retryable !== false; err.status = r.status; const retryAfter = parseInt(r.headers.get('Retry-After'), 10); if (retryAfter > 0) err.retryAfterMs = retryAfter * 1000; + else if (r.status === 429) err.retryAfterMs = 30000; 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.'); + const err = new Error('Request timed out. Trying another map server…'); err.retryable = true; throw err; } @@ -169,26 +235,46 @@ async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) { } } -async function fetchOverpass(query, timeoutMs = 25000, skipThrottle) { +async function fetchOverpass(query) { 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++) { + const n = OVERPASS_ENDPOINTS.length; + const startIdx = lastGoodEndpointIdx; + const timeouts = [OVERPASS_TIMEOUT_FAST_MS, OVERPASS_TIMEOUT_SLOW_MS]; + for (let round = 0; round < timeouts.length; round++) { + let tried = 0; + for (let i = 0; i < n; i++) { + const idx = (startIdx + i) % n; + const url = OVERPASS_ENDPOINTS[idx]; + if (isEndpointCooling(url)) continue; + tried++; + const gap = tried === 1 && round === 0 ? OVERPASS_MIN_INTERVAL_MS : OVERPASS_FAILOVER_GAP_MS; try { - return await fetchOverpassOnce(query, url, timeoutMs, skipThrottle && endpointOffset === 0 && attempt === 0); + const data = await fetchOverpassOnce(query, url, timeouts[round], gap); + lastGoodEndpointIdx = idx; + return data; } 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; + const timedOut = e.name === 'AbortError' || /timed out/i.test(e.message || ''); + const cooldownMs = e.status === 429 + ? (e.retryAfterMs || 30000) + : (timedOut ? 45000 : (e.status === 503 || e.status === 504 ? 12000 : 0)); + if (cooldownMs) markEndpointCooldown(url, cooldownMs); + console.warn(`Overpass ${url}: ${e.message}`); } } + if (!tried) { + let waitMs = OVERPASS_BACKOFF_BASE_MS; + endpointCooldownUntil.forEach((until) => { + const left = until - Date.now(); + if (left > 0 && left < waitMs) waitMs = left; + }); + console.warn('All Overpass endpoints in cooldown; waiting ' + waitMs + 'ms'); + await sleep(Math.max(waitMs, 400)); + } else if (round === 0) { + await sleep(OVERPASS_BACKOFF_BASE_MS); + } } - throw lastError || new Error('All Overpass servers failed. Wait a few minutes and try again, or use a smaller map area.'); + throw lastError || new Error('All Overpass servers failed. Wait a minute and try again, or use a smaller map area.'); } app.post('/api/overpass/plan', (req, res) => { @@ -206,62 +292,265 @@ app.post('/api/overpass', async (req, res) => { return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' }); } const bbox = { south, west, north, east }; + const key = cacheKey(bbox, layers); + const cached = cacheGet(key); + if (cached) return res.json(cached); try { const query = buildOverpassQuery(bbox, layers); - const data = await fetchOverpass(query, 25000, true); + const data = await fetchOverpass(query); + cacheSet(key, data); res.json(data); } catch (e) { const msg = e.message || 'Overpass request failed'; console.error('Overpass error:', msg); const status = e.status === 429 ? 429 : 502; - res.status(status).json({ error: msg }); + res.status(status).json({ error: msg, retryAfterMs: e.retryAfterMs || 8000 }); } }); -// Geocode address/place via OpenStreetMap Nominatim (no API key; use respectful User-Agent) +// Geocode via OpenStreetMap Nominatim + Photon (no Google API key). const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search'; -const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool)'; +const PHOTON_URL = 'https://photon.komoot.io/api/'; +const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.1 (local CAD export tool)'; + +function isAllowedMapsHost(hostname) { + const h = String(hostname || '').toLowerCase(); + return ( + h === 'maps.app.goo.gl' || + h === 'goo.gl' || + h === 'google.com' || + h.endsWith('.google.com') || + h === 'maps.google.com' + ); +} + +function scoreGeocodeHit(item, query) { + let s = Number(item.importance) || 0; + const addr = item.address || {}; + const house = String(addr.house_number || ''); + const qHouse = query.match(/\b(\d{1,6})\b/); + if (house && qHouse && house === qHouse[1]) s += 3; + else if (house) s += 1.2; + const cls = item.class || ''; + const type = item.type || ''; + if (cls === 'building' || type === 'house' || type === 'residential' && cls === 'building') s += 1.5; + if (cls === 'amenity' || cls === 'shop' || cls === 'industrial' || cls === 'office') s += 1; + if (cls === 'highway') s -= 0.9; + if (cls === 'place' && /city|town|village|county|state|suburb/.test(type)) s -= 1.6; + const name = String(item.display_name || '').toLowerCase(); + const tokens = query.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).filter((t) => t.length > 1); + tokens.forEach((t) => { if (name.includes(t)) s += 0.12; }); + return s; +} + +function pickBestGeocode(hits, query) { + if (!hits || !hits.length) return null; + let best = hits[0]; + let bestScore = scoreGeocodeHit(best, query); + for (let i = 1; i < hits.length; i++) { + const sc = scoreGeocodeHit(hits[i], query); + if (sc > bestScore) { + best = hits[i]; + bestScore = sc; + } + } + return best; +} + +function normalizeNominatimHits(data) { + return (data || []).map((x) => ({ + lat: parseFloat(x.lat), + lon: parseFloat(x.lon), + display_name: x.display_name || '', + class: x.class, + type: x.type, + importance: x.importance, + address: x.address || {} + })).filter((x) => !isNaN(x.lat) && !isNaN(x.lon)); +} + +function normalizePhotonHits(data) { + return ((data && data.features) || []).map((f) => { + const p = f.properties || {}; + const c = (f.geometry && f.geometry.coordinates) || []; + const parts = [p.name, p.housenumber, p.street, p.city, p.state, p.country].filter(Boolean); + return { + lat: parseFloat(c[1]), + lon: parseFloat(c[0]), + display_name: parts.join(', '), + class: p.osm_key, + type: p.osm_value, + importance: 0.4, + address: { house_number: p.housenumber, road: p.street, city: p.city } + }; + }).filter((x) => !isNaN(x.lat) && !isNaN(x.lon)); +} + +async function nominatimSearch(q) { + const params = new URLSearchParams({ + q: q, + format: 'jsonv2', + limit: '8', + addressdetails: '1' + }); + const r = await fetch(NOMINATIM_URL + '?' + params, { + headers: { 'User-Agent': GEOCODE_USER_AGENT, 'Accept-Language': 'en' } + }); + const text = await r.text(); + if (!r.ok || !/^\s*[\{\[]/.test(text)) return []; + try { + return normalizeNominatimHits(JSON.parse(text)); + } catch (_) { + return []; + } +} + +async function photonSearch(q) { + const r = await fetch(PHOTON_URL + '?limit=8&q=' + encodeURIComponent(q), { + headers: { 'User-Agent': GEOCODE_USER_AGENT } + }); + const text = await r.text(); + if (!r.ok || !/^\s*[\{\[]/.test(text)) return []; + try { + return normalizePhotonHits(JSON.parse(text)); + } catch (_) { + return []; + } +} + +function extractMapsLocationFromText(s) { + if (!s) return null; + const pins = []; + const pinRe = /!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/g; + let m; + while ((m = pinRe.exec(s)) !== null) { + pins.push({ lat: parseFloat(m[1]), lon: parseFloat(m[2]) }); + } + const at = s.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/); + const zoomM = s.match(/@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*m\b/i); + let lat; + let lon; + if (pins.length) { + lat = pins[pins.length - 1].lat; + lon = pins[pins.length - 1].lon; + } else if (at) { + lat = parseFloat(at[1]); + lon = parseFloat(at[2]); + } else { + return null; + } + if (isNaN(lat) || isNaN(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null; + let displayName = null; + const place = s.match(/\/maps\/place\/([^/@?#]+)/i); + if (place && place[1]) { + try { + displayName = decodeURIComponent(place[1].replace(/\+/g, ' ')).trim(); + } catch (_) { + displayName = place[1].replace(/\+/g, ' '); + } + } + return { + lat, + lon, + viewMeters: zoomM ? Math.min(50000, Math.max(50, parseFloat(zoomM[1]))) : undefined, + display_name: displayName || '' + }; +} + +async function fetchGoogleMapsPin(rawUrl) { + const current = new URL(rawUrl.trim()); + if (current.protocol !== 'https:' || !isAllowedMapsHost(current.hostname)) { + const err = new Error('Paste a Google Maps or maps.app.goo.gl link.'); + err.status = 400; + throw err; + } + const r = await fetch(current.href, { + method: 'GET', + redirect: 'follow', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + 'Accept-Language': 'en-US,en;q=0.9' + } + }); + const html = await r.text(); + const finalUrl = r.url || current.href; + const loc = extractMapsLocationFromText(finalUrl) || extractMapsLocationFromText(html); + if (!loc) { + const err = new Error('Could not read a pin from that Google Maps link.'); + err.status = 404; + throw err; + } + return { + lat: loc.lat, + lon: loc.lon, + viewMeters: loc.viewMeters, + display_name: loc.display_name || '', + url: finalUrl + }; +} + +app.get('/api/maps-pin', async (req, res) => { + const raw = req.query.url; + if (!raw || typeof raw !== 'string') { + return res.status(400).json({ error: 'Missing url' }); + } + try { + const data = await fetchGoogleMapsPin(raw); + res.json(data); + } catch (e) { + if (e.code === 'ERR_INVALID_URL' || e.message === 'Invalid URL') { + return res.status(400).json({ error: 'Invalid URL' }); + } + console.error('Maps pin error:', e.message); + res.status(e.status || 502).json({ error: e.message || 'Could not open that Maps link.' }); + } +}); + +app.get('/api/resolve-url', async (req, res) => { + const raw = req.query.url; + if (!raw || typeof raw !== 'string') { + return res.status(400).json({ error: 'Missing url' }); + } + try { + const data = await fetchGoogleMapsPin(raw); + res.json(data); + } catch (e) { + res.status(e.status || 502).json({ error: e.message || 'Could not expand that Maps link.' }); + } +}); app.get('/api/geocode', async (req, res) => { const q = req.query.q; if (!q || typeof q !== 'string' || q.trim().length === 0) { return res.status(400).json({ error: 'Missing or empty query (q)' }); } - const params = new URLSearchParams({ - q: q.trim(), - format: 'json', - limit: '5', - addressdetails: '0' - }); + let query = q.trim(); + if (/^https?:/i.test(query)) { + return res.status(400).json({ error: 'That looks like a link, not an address. Paste a Google Maps URL with a pin, or type the street address.' }); + } + if (/\b[A-Z]{2}\b/.test(query) && !/united states|\busa\b/i.test(query)) { + query = query + ', USA'; + } try { - const r = await fetch(`${NOMINATIM_URL}?${params}`, { - headers: { 'User-Agent': GEOCODE_USER_AGENT } - }); - const text = await r.text(); - if (!r.ok) { - return res.status(502).json({ error: 'Geocoding service unavailable' }); - } - if (!/^\s*[\{\[]/.test(text)) { - if (/<\?xml| ({ lat: parseFloat(x.lat), lon: parseFloat(x.lon), display_name: x.display_name || '' })) + lat: best.lat, + lon: best.lon, + display_name: best.display_name || '', + results: hits.slice(0, 5).map((x) => ({ lat: x.lat, lon: x.lon, display_name: x.display_name || '' })) }); } catch (e) { console.error('Geocode error:', e.message); @@ -275,6 +564,7 @@ app.get('/', (req, res) => { const TILE_SOURCES = { esri: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile', + clarity: 'https://clarity.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile', usgs: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile' }; @@ -336,13 +626,54 @@ app.post('/api/segment', upload.single('image'), async (req, res) => { } catch (e) { console.error('Segment proxy error:', e.message); res.status(503).json({ - error: 'Server-side ML not available. Start the Python server: cd ml_server && pip install -r requirements.txt && python segment_server.py' + error: 'Server-side ML not available. Restart with Start.bat (Python is optional). Satellite tracing still works.' }); } }); +function resolvePython() { + const cmds = process.platform === 'win32' ? ['python', 'py'] : ['python3', 'python']; + for (let i = 0; i < cmds.length; i++) { + try { + execSync(cmds[i] + ' --version', { stdio: 'ignore' }); + return cmds[i]; + } catch (_) {} + } + return null; +} + +let mlChild = null; +function stopMlServer() { + if (!mlChild) return; + try { mlChild.kill(); } catch (_) {} + mlChild = null; +} + +function startMlServer() { + const dir = path.join(__dirname, 'ml_server'); + const script = path.join(dir, 'segment_server.py'); + if (!fs.existsSync(script)) return; + const py = resolvePython(); + if (!py) { + console.log('Python not found — ML segmentation off. Satellite tracing still works.'); + return; + } + mlChild = spawn(py, [script], { + cwd: dir, + stdio: 'ignore', + windowsHide: true + }); + mlChild.on('error', () => { mlChild = null; }); + mlChild.on('exit', () => { mlChild = null; }); + process.on('exit', stopMlServer); + process.on('SIGINT', () => { stopMlServer(); process.exit(0); }); + process.on('SIGTERM', () => { stopMlServer(); process.exit(0); }); +} + +startMlServer(); + const server = app.listen(PORT, () => { - console.log('MAPS to DXF — ' + URL); + console.log('MAPS to DXF — ' + APP_URL); openBrowser(); }); server.on('error', (err) => {