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

+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;
});