fix(export): georeference satellite image for correct CAD scaling

Export rectangular PNGs with uniform m/px, Y-flip for DXF IMAGE alignment,
satellite.pgw world file, INSUNITS=meters, and extent clipping. Adds imagery
fence tracing, Esri/USGS tiles, Overpass retry/throttle, go-to-address/site
zoom, and Start.bat port 3456 cleanup.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michael-A-SloanandCursor committed 2026-06-30 13:29:09 -04:00
1 parent 7c20a404bf
commit fadfb807ec
4 files changed
+1505 -259

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ if exist "ml_server\segment_server.py" (
)
echo Starting MAPS to DXF...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":3456" ^| findstr "LISTENING"') do taskkill /PID %%a /F >nul 2>&1
echo Browser will open. Keep this window open while using the app.
if exist "ml_server\segment_server.py" echo (ML server started in the other window - enable "Use server-side ML segmentation" in the app.)
echo.
+131 -14
View File
@@ -5,19 +5,36 @@
*/
function extractCoordinates(url) {
const s = String(url).trim();
// Google Maps: ...@lat,lon... Google Earth Web: ...@lat,lon... or ...@lat,lon,altitudea,distanced...
let lat;
let lon;
const placePins = [];
const placePinRegex = /!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/g;
let pinMatch;
while ((pinMatch = placePinRegex.exec(s)) !== null) {
placePins.push({ lat: parseFloat(pinMatch[1]), lon: parseFloat(pinMatch[2]) });
}
const coordRegex = /@(-?\d+\.?\d*),(-?\d+\.?\d*)/;
const coordMatch = s.match(coordRegex);
if (!coordMatch || coordMatch.length < 3) return null;
const lat = parseFloat(coordMatch[1]);
const lon = parseFloat(coordMatch[2]);
let viewMeters = undefined;
// Google Earth Web: optional altitude (e.g. ,1234a) or distance (e.g. ,50000d) in meters; order may be ,100a,50000d
if (placePins.length > 0) {
const pin = placePins[placePins.length - 1];
lat = pin.lat;
lon = pin.lon;
} else if (coordMatch && coordMatch.length >= 3) {
lat = parseFloat(coordMatch[1]);
lon = parseFloat(coordMatch[2]);
} else {
return null;
}
if (isNaN(lat) || isNaN(lon)) return null;
let viewMeters;
const mapsZoomM = s.match(/@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*m\b/i);
const distRegex = /@-?\d+\.?\d*,-?\d+\.?\d*(?:,\d+(?:\.\d*)?\s*a)?\s*,(\d+(?:\.\d*)?)\s*d/i;
const altRegex = /@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*a/i;
const distMatch = s.match(distRegex);
const altMatch = s.match(altRegex);
if (distMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(distMatch[1])));
if (mapsZoomM) viewMeters = Math.min(50000, Math.max(50, parseFloat(mapsZoomM[1])));
else if (distMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(distMatch[1])));
else if (altMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(altMatch[1]) * 2));
return { lat, lon, viewMeters };
}
@@ -32,10 +49,10 @@ var DEFAULT_LAYER_OPTIONS = {
landuse: true,
parkingOutline: true,
parkingSpaces: true,
trees: true,
barriers: true,
power: true,
boundary: true,
trees: false,
barriers: false,
power: false,
boundary: false,
man_made: true
};
@@ -177,12 +194,28 @@ function buildPreviewData(osmData, origin, layerOptions) {
return out;
}
function generateHighDetailDXF(osmData, origin, layerOptions) {
function generateHighDetailDXF(osmData, origin, layerOptions, clipBounds) {
const opts = layerOptions || DEFAULT_LAYER_OPTIONS;
const on = function (key) { return opts[key] !== false; };
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
const clipMargin = 8;
function inClip(x, y) {
if (!clipBounds) return true;
return x >= clipBounds.minX - clipMargin && x <= clipBounds.maxX + clipMargin
&& y >= clipBounds.minY - clipMargin && y <= clipBounds.maxY + clipMargin;
}
function wayTouchesClip(el) {
if (!clipBounds || !el.nodes) return true;
for (let i = 0; i < el.nodes.length; i++) {
const n = nodes[el.nodes[i]];
if (n && inClip(n.x, n.y)) return true;
}
return false;
}
osmData.elements.forEach((el) => {
if (el.type === 'node') {
@@ -194,7 +227,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
}
});
let dxf = '0\nSECTION\n2\nHEADER\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n';
let dxf = '0\nSECTION\n2\nHEADER\n9\n$INSUNITS\n70\n6\n9\n$MEASUREMENT\n70\n1\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n';
dxf += '0\nLTYPE\n2\nDASHED\n70\n0\n3\n_ _ _ _ _ _\n72\n65\n73\n2\n40\n2.0\n49\n1.25\n49\n-0.75\n0\nENDTAB\n0\nENDSEC\n';
dxf += '0\nSECTION\n2\nENTITIES\n';
@@ -207,6 +240,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
const PARKING_HH = 2.5;
for (const id in nodes) {
const n = nodes[id];
if (!inClip(n.x, n.y)) continue;
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
@@ -233,6 +267,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
if (el.nodes[0] !== el.nodes[el.nodes.length - 1]) return;
if (!wayTouchesClip(el)) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
const points = [];
@@ -250,6 +285,7 @@ function generateHighDetailDXF(osmData, origin, layerOptions) {
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
if (!wayTouchesClip(el)) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let layer = '0', color = '7', isRoad = false, roadHalfWidth = 0, isRail = false, lineType = 'CONTINUOUS';
@@ -651,6 +687,47 @@ function classifyImageryContour(poly) {
return null;
}
/**
* Closed OSM building footprints in world meters (for trace overlay / export).
*/
function getOSMBuildingFootprints(osmData, origin) {
if (!osmData || !origin) return [];
const nodes = getOSMNodesInMeters(osmData, origin);
const polygons = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
if (!el.tags || !el.tags.building) return;
const ids = el.nodes[0] === el.nodes[el.nodes.length - 1] ? el.nodes.slice(0, -1) : el.nodes;
const pts = [];
ids.forEach((id) => {
const n = nodes[id];
if (n) pts.push({ x: n.x, y: n.y });
});
if (pts.length >= 3) polygons.push(pts);
});
return polygons;
}
/**
* OSM barrier/fence ways as polylines in world meters (open or closed).
*/
function getOSMBarrierPolylines(osmData, origin) {
if (!osmData || !origin) return [];
const nodes = getOSMNodesInMeters(osmData, origin);
const lines = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
if (!el.tags || !el.tags.barrier) return;
const pts = [];
el.nodes.forEach((id) => {
const n = nodes[id];
if (n) pts.push({ x: n.x, y: n.y });
});
if (pts.length >= 2) lines.push(pts);
});
return lines;
}
/**
* Filter imagery polylines to only those suitable for land lot drawings (trees, buildings, lots).
* Returns { trees: [], buildings: [], lots: [], all: [] }.
@@ -774,6 +851,43 @@ function appendImageryTraceToDXF(dxfContent, polylines, minSegmentMeters, minLen
return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF');
}
/**
* Pixel size for export: preserves geographic aspect ratio; 1 DXF unit = 1 meter.
*/
function extentToImagePixels(minX, maxX, minY, maxY, maxLongEdge) {
const w = maxX - minX;
const h = maxY - minY;
const long = Math.max(w, h, 1);
const maxPx = maxLongEdge || 2048;
const metersPerPixel = long / maxPx;
return {
width: Math.max(1, Math.round(w / metersPerPixel)),
height: Math.max(1, Math.round(h / metersPerPixel)),
metersPerPixel: metersPerPixel,
widthMeters: w,
heightMeters: h
};
}
/**
* ESRI world file (.pgw) for georeferenced raster attach in CAD/GIS.
* Coordinates match DXF: origin at map center, X east, Y north, units = meters.
*/
function generateWorldFilePgw(minX, minY, maxX, maxY, widthPx, heightPx, rowZeroAtSouth) {
const pixelW = (maxX - minX) / widthPx;
const pixelH = (maxY - minY) / heightPx;
const A = pixelW;
const C = minX + A / 2;
if (rowZeroAtSouth) {
const E = pixelH;
const F = minY + E / 2;
return A + '\n0\n0\n' + E + '\n' + C + '\n' + F + '\n';
}
const E = -pixelH;
const F = maxY + E / 2;
return A + '\n0\n0\n' + E + '\n' + C + '\n' + F + '\n';
}
/**
* Append satellite imagery reference to DXF so CAD shows the image as background.
* Also adds a visible bounding box (rectangle) on layer IMAGE_BOUNDS so the image extent is visible in CAD.
@@ -787,6 +901,9 @@ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX,
const h = maxY - minY;
const uPerPx = w / widthPx;
const vPerPx = h / heightPx;
const scaleNote =
`0\nTEXT\n8\nIMAGE_SCALE\n62\n3\n10\n${minX}\n20\n${minY - Math.max(3, h * 0.02)}\n40\n${Math.max(2, Math.min(w, h) * 0.03)}\n1\n` +
`Satellite ${w.toFixed(1)}m x ${h.toFixed(1)}m | ${uPerPx.toFixed(4)} m/px | INSUNITS=meters\n`;
/* Visible bounding box in CAD: four LINE entities (color 4 = cyan) so user sees the image extent */
const layer = 'IMAGE_BOUNDS';
const color = '4';
@@ -803,5 +920,5 @@ function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX,
`0\nSECTION\n2\nOBJECTS\n` +
`0\nIMAGEDEF\n90\n${handle}\n1\n${imageFilename}\n13\n${widthPx}\n23\n${heightPx}\n` +
`0\nENDSEC\n0\nEOF`;
return dxfContent.replace('0\nENDSEC\n0\nEOF', boxLines + imageEntity + '0\nENDSEC\n' + objectsSection);
return dxfContent.replace('0\nENDSEC\n0\nEOF', boxLines + scaleNote + imageEntity + '0\nENDSEC\n' + objectsSection);
}
+1163 -142
View File
File diff suppressed because it is too large. Load diff
+210 -103
View File
@@ -21,108 +21,200 @@ function openBrowser() {
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// Multiple public Overpass API instances; we try each until one returns valid JSON.
// Public Overpass mirrors; rotated and retried on 429/503/504.
const OVERPASS_ENDPOINTS = [
'https://overpass-api.de/api/interpreter',
'https://overpass.kumi.systems/api/interpreter',
'https://overpass.openstreetmap.fr/api/interpreter'
'https://overpass-api.de/api/interpreter',
'https://overpass.openstreetmap.fr/api/interpreter',
'https://overpass.private.coffee/api/interpreter'
];
const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool; https://github.com)';
const OVERPASS_MIN_INTERVAL_MS = Number(process.env.OVERPASS_MIN_INTERVAL_MS) || 1000;
const OVERPASS_MAX_RETRIES = Number(process.env.OVERPASS_MAX_RETRIES) || 3;
const OVERPASS_BACKOFF_BASE_MS = Number(process.env.OVERPASS_BACKOFF_BASE_MS) || 2000;
const OVERPASS_TILE_MAX_DEG = Number(process.env.OVERPASS_TILE_MAX_DEG) || 0.018;
const OVERPASS_MAX_TILES = Number(process.env.OVERPASS_MAX_TILES) || 9;
const RETRYABLE_OVERPASS_STATUSES = new Set([429, 502, 503, 504]);
async function fetchOverpass(query, timeoutMs = 45000) {
let lastError;
for (const url of OVERPASS_ENDPOINTS) {
const controller = new AbortController();
const to = setTimeout(() => controller.abort(), timeoutMs);
try {
const r = await fetch(url, {
method: 'POST',
body: query,
headers: {
'Content-Type': 'text/plain',
'User-Agent': OVERPASS_USER_AGENT
},
signal: controller.signal
let lastOverpassRequestAt = 0;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function throttleOverpass(skip) {
if (skip) return;
const now = Date.now();
const wait = OVERPASS_MIN_INTERVAL_MS - (now - lastOverpassRequestAt);
if (wait > 0) await sleep(wait);
lastOverpassRequestAt = Date.now();
}
function layerEnabled(layers, key) {
return !layers || layers[key] !== false;
}
function buildOverpassQuery(bbox, layers) {
const b = `(${bbox.south},${bbox.west},${bbox.north},${bbox.east})`;
const parts = [];
if (layerEnabled(layers, 'roads') || layerEnabled(layers, 'paths')) {
parts.push(`way["highway"]${b};`);
}
if (layerEnabled(layers, 'railways')) parts.push(`way["railway"]${b};`);
if (layerEnabled(layers, 'buildings')) parts.push(`way["building"]${b};`);
if (layerEnabled(layers, 'parkingOutline')) parts.push(`way["amenity"="parking"]${b};`);
if (layerEnabled(layers, 'landuse')) parts.push(`way["landuse"]${b};`);
if (layerEnabled(layers, 'water')) parts.push(`way["natural"="water"]${b};`);
if (layerEnabled(layers, 'parks')) parts.push(`way["leisure"]${b};`);
if (layerEnabled(layers, 'barriers')) parts.push(`way["barrier"]${b};`);
if (layerEnabled(layers, 'power')) parts.push(`way["power"]${b};`);
if (layerEnabled(layers, 'boundary')) parts.push(`way["boundary"]${b};`);
if (layerEnabled(layers, 'man_made')) {
parts.push(`way["man_made"="embankment"]${b};`);
parts.push(`way["man_made"="cutline"]${b};`);
}
if (layerEnabled(layers, 'trees')) {
parts.push(`node["natural"="tree"]${b};`);
parts.push(`node["natural"="tree_row"]${b};`);
}
if (layerEnabled(layers, 'parkingSpaces')) parts.push(`node["amenity"="parking_space"]${b};`);
if (parts.length === 0) {
parts.push(`way["highway"]${b};`);
}
return `[out:json][timeout:15];(${parts.join('')});(._;>;);out body;`;
}
function splitBbox(bbox) {
const latSpan = bbox.north - bbox.south;
const lonSpan = bbox.east - bbox.west;
let nLat = Math.max(1, Math.ceil(latSpan / OVERPASS_TILE_MAX_DEG));
let nLon = Math.max(1, Math.ceil(lonSpan / OVERPASS_TILE_MAX_DEG));
while (nLat * nLon > OVERPASS_MAX_TILES) {
if (nLat >= nLon && nLat > 1) nLat--;
else if (nLon > 1) nLon--;
else break;
}
if (nLat === 1 && nLon === 1) return [bbox];
const tiles = [];
const latStep = latSpan / nLat;
const lonStep = lonSpan / nLon;
for (let i = 0; i < nLat; i++) {
for (let j = 0; j < nLon; j++) {
tiles.push({
south: bbox.south + i * latStep,
north: bbox.south + (i + 1) * latStep,
west: bbox.west + j * lonStep,
east: bbox.west + (j + 1) * lonStep
});
const text = await r.text();
clearTimeout(to);
const looksLikeJson = /^\s*[\{\[]/.test(text);
if (!r.ok) {
let msg = `Overpass ${r.status}`;
if (looksLikeJson) {
try {
const err = JSON.parse(text);
if (err.error) msg = err.error;
} catch (_) {}
} else if (/<\?xml|<!DOCTYPE|<html/i.test(text)) {
msg = 'This Overpass server returned an error page (overloaded or rate limit).';
}
lastError = new Error(msg);
continue;
}
if (!looksLikeJson) {
if (/<\?xml|<!DOCTYPE|<html/i.test(text)) {
lastError = new Error('OpenStreetMap Overpass server returned an error page instead of data. Wait a minute and try again, or try a smaller map area.');
} else {
lastError = new Error('Overpass returned invalid response. Try again.');
}
continue;
}
let data;
}
}
return tiles;
}
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.')
: new Error('Overpass returned invalid response. Try again.');
err.retryable = RETRYABLE_OVERPASS_STATUSES.has(status);
return { error: err };
}
let data;
try {
data = JSON.parse(text);
} catch (_) {
return { error: new Error('Overpass returned invalid JSON. Try again later.') };
}
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) };
}
async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) {
await throttleOverpass(skipThrottle);
const controller = new AbortController();
const to = setTimeout(() => controller.abort(), timeoutMs);
try {
const r = await fetch(url, {
method: 'POST',
body: query,
headers: {
'Content-Type': 'text/plain',
'User-Agent': OVERPASS_USER_AGENT
},
signal: controller.signal
});
const text = await r.text();
clearTimeout(to);
const parsed = parseOverpassResponse(text, r.status);
if (parsed.data) return parsed.data;
const err = parsed.error || new Error(`Overpass ${r.status}`);
err.retryable = parsed.retryable ?? RETRYABLE_OVERPASS_STATUSES.has(r.status);
err.status = r.status;
const retryAfter = parseInt(r.headers.get('Retry-After'), 10);
if (retryAfter > 0) err.retryAfterMs = retryAfter * 1000;
throw err;
} catch (e) {
clearTimeout(to);
if (e.name === 'AbortError') {
const err = new Error('Request timed out. Try a smaller area or try again later.');
err.retryable = true;
throw err;
}
throw e;
}
}
async function fetchOverpass(query, timeoutMs = 25000, skipThrottle) {
let lastError;
const startIdx = Math.floor(Math.random() * OVERPASS_ENDPOINTS.length);
for (let endpointOffset = 0; endpointOffset < OVERPASS_ENDPOINTS.length; endpointOffset++) {
const url = OVERPASS_ENDPOINTS[(startIdx + endpointOffset) % OVERPASS_ENDPOINTS.length];
for (let attempt = 0; attempt < OVERPASS_MAX_RETRIES; attempt++) {
try {
data = JSON.parse(text);
} catch (parseErr) {
lastError = new Error('Overpass returned invalid JSON. Try again later.');
continue;
return await fetchOverpassOnce(query, url, timeoutMs, skipThrottle && endpointOffset === 0 && attempt === 0);
} catch (e) {
lastError = e;
const retryable = e.retryable !== false && (e.retryable || e.status === 429);
if (!retryable || attempt >= OVERPASS_MAX_RETRIES - 1) break;
const delay = e.retryAfterMs || OVERPASS_BACKOFF_BASE_MS * Math.pow(2, attempt);
console.warn(`Overpass retry ${attempt + 1}/${OVERPASS_MAX_RETRIES} on ${url} after ${delay}ms: ${e.message}`);
await sleep(delay);
skipThrottle = false;
}
if (data.error) {
lastError = new Error(data.error);
continue;
}
return data;
} catch (e) {
clearTimeout(to);
if (e.name === 'AbortError') lastError = new Error('Request timed out. Try a smaller area or try again later.');
else lastError = e;
}
}
throw lastError || new Error('All Overpass servers failed. Wait a few minutes and try again, or use a smaller map area.');
}
app.post('/api/overpass', async (req, res) => {
const bbox = req.body;
if (!bbox || typeof bbox.south !== 'number' || typeof bbox.north !== 'number') {
app.post('/api/overpass/plan', (req, res) => {
const { south, west, north, east } = req.body || {};
if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') {
return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' });
}
const query = `
[out:json][timeout:25];
(
way["highway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["railway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["building"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["amenity"="parking"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["landuse"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["natural"="water"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["leisure"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["barrier"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["power"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["boundary"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["man_made"="embankment"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
way["man_made"="cutline"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
node["natural"="tree"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
node["natural"="tree_row"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
node["amenity"="parking_space"](${bbox.south},${bbox.west},${bbox.north},${bbox.east});
);
(._;>;);
out body;
`;
const tiles = splitBbox({ south, west, north, east });
res.json({ tiles, count: tiles.length });
});
app.post('/api/overpass', async (req, res) => {
const { south, west, north, east, layers } = req.body || {};
if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') {
return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' });
}
const bbox = { south, west, north, east };
try {
const data = await fetchOverpass(query);
const query = buildOverpassQuery(bbox, layers);
const data = await fetchOverpass(query, 25000, true);
res.json(data);
} catch (e) {
const msg = e.message || 'Overpass request failed';
console.error('Overpass error:', msg);
res.status(502).json({ error: msg });
const status = e.status === 429 ? 429 : 502;
res.status(status).json({ error: msg });
}
});
@@ -181,8 +273,31 @@ app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
const TILE_BASE = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile';
// Proxy to Python ML segmentation server (run: cd ml_server && pip install -r requirements.txt && python segment_server.py)
const TILE_SOURCES = {
esri: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile',
usgs: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile'
};
app.get('/api/tile/:z/:y/:x', async (req, res) => {
const { z, y, x } = req.params;
const sourceKey = String(req.query.source || 'esri').toLowerCase();
const base = TILE_SOURCES[sourceKey] || TILE_SOURCES.esri;
const url = `${base}/${z}/${y}/${x}`;
try {
const r = await fetch(url);
if (!r.ok) {
res.status(r.status).end();
return;
}
const buf = await r.arrayBuffer();
res.set('Cache-Control', 'public, max-age=86400');
res.set('Access-Control-Allow-Origin', '*');
res.type('image/png').send(Buffer.from(buf));
} catch (e) {
res.status(502).end();
}
});
app.post('/api/segment', upload.single('image'), async (req, res) => {
if (!req.file || !req.file.buffer) {
return res.status(400).json({ error: 'Missing image file' });
@@ -226,25 +341,17 @@ app.post('/api/segment', upload.single('image'), async (req, res) => {
}
});
app.get('/api/tile/:z/:y/:x', async (req, res) => {
const { z, y, x } = req.params;
const url = `${TILE_BASE}/${z}/${y}/${x}`;
try {
const r = await fetch(url);
if (!r.ok) {
res.status(r.status).end();
return;
}
const buf = await r.arrayBuffer();
res.set('Cache-Control', 'public, max-age=86400');
res.set('Access-Control-Allow-Origin', '*');
res.type('image/png').send(Buffer.from(buf));
} catch (e) {
res.status(502).end();
}
});
app.listen(PORT, () => {
const server = app.listen(PORT, () => {
console.log('MAPS to DXF — ' + URL);
openBrowser();
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error('');
console.error('Port ' + PORT + ' is already in use.');
console.error('Close the other MAPS to DXF console window, or run Start.bat again (it will free the port).');
console.error('');
process.exit(1);
}
throw err;
});