feat: harden maps export for CAD and improve satellite/OSM workflow

Cap zoom to real imagery, attach a BricsCAD-safe DXF IMAGE at the selected extent, and consolidate startup plus Overpass/address handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michael-A-SloanandCursor committed 2026-08-31 15:43:01 -04:00
1 parent fadfb807ec
commit 7769a4412e
8 files changed
+1169 -313

No files matched your search

+3 -9
View File
@@ -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.
+55 -42
View File
@@ -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
-40
View File
@@ -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
+1 -1
View File
@@ -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/
+4 -2
View File
@@ -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
+178 -23
View File
@@ -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;
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;
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);
}
+521 -120
View File
File diff suppressed because it is too large. Load diff
+407 -76
View File
@@ -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;
function throttleOverpass(intervalMs) {
const min = intervalMs == null ? OVERPASS_MIN_INTERVAL_MS : intervalMs;
const run = throttleChain.then(async () => {
const now = Date.now();
const wait = OVERPASS_MIN_INTERVAL_MS - (now - lastOverpassRequestAt);
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|<!DOCTYPE|<html/i.test(text)
? new Error('OpenStreetMap Overpass server returned an error page instead of data. Wait a minute and try again, or use a smaller map area.')
const html = /<[?]xml|<!DOCTYPE|<html/i.test(text);
const err = html
? new Error('OpenStreetMap Overpass server is busy. Retrying another server…')
: new Error('Overpass returned invalid response. Try again.');
err.retryable = RETRYABLE_OVERPASS_STATUSES.has(status);
err.retryable = true;
return { error: err };
}
let data;
try {
data = JSON.parse(text);
} catch (_) {
return { error: new Error('Overpass returned invalid JSON. Try again later.') };
const err = new Error('Overpass returned invalid JSON. Try again later.');
err.retryable = true;
return { error: err };
}
if (data.remark && /timeout|rate.?limit|too many|slot/i.test(String(data.remark))) {
if (!Array.isArray(data.elements) || data.elements.length === 0) {
const err = new Error(String(data.remark));
err.retryable = true;
return { error: err };
}
}
if (data.error && (!status || status < 400)) {
const err = new Error(typeof data.error === 'string' ? data.error : 'Overpass error');
err.retryable = true;
return { error: err };
}
if (data.error) return { error: new Error(data.error) };
if (!status || status < 400) return { data };
let msg = `Overpass ${status}`;
if (data.remark) msg = data.remark;
else if (typeof data.error === 'string') msg = data.error;
return { error: new Error(msg), retryable: RETRYABLE_OVERPASS_STATUSES.has(status) };
return { error: new Error(msg), retryable: RETRYABLE_OVERPASS_STATUSES.has(status) || status === 406 };
}
async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) {
await throttleOverpass(skipThrottle);
async function fetchOverpassOnce(query, url, timeoutMs, intervalMs) {
await throttleOverpass(intervalMs);
const controller = new AbortController();
const to = setTimeout(() => 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' });
let hits = await nominatimSearch(query);
if (!hits.length) hits = await photonSearch(q.trim());
else {
const best = pickBestGeocode(hits, q.trim());
const weak = !best || (best.class === 'highway') || (best.class === 'place' && /city|town|village/.test(best.type || ''));
if (weak) {
const extra = await photonSearch(q.trim());
hits = hits.concat(extra);
}
if (!/^\s*[\{\[]/.test(text)) {
if (/<\?xml|<!DOCTYPE|<html/i.test(text)) {
return res.status(502).json({ error: 'Geocoding service returned an error page. Try again in a moment.' });
}
return res.status(502).json({ error: 'Geocoding service returned invalid response.' });
const best = pickBestGeocode(hits, q.trim());
if (!best) {
return res.status(404).json({ error: 'No location found for this address. Paste a Google Maps link to the pin for an exact spot.' });
}
let data;
try {
data = JSON.parse(text);
} catch (parseErr) {
return res.status(502).json({ error: 'Geocoding service returned invalid data. Try again.' });
}
if (!Array.isArray(data) || data.length === 0) {
return res.status(404).json({ error: 'No location found for this address or place name.' });
}
const first = data[0];
res.json({
lat: parseFloat(first.lat),
lon: parseFloat(first.lon),
display_name: first.display_name || '',
results: data.slice(0, 5).map((x) => ({ 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) => {