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>
689 lines
23 KiB
JavaScript
689 lines
23 KiB
JavaScript
/**
|
|
* Standalone server: serves the GUI and proxies Overpass API (avoids CORS).
|
|
* Run: npm start then open http://localhost:3456
|
|
*/
|
|
const express = require('express');
|
|
const path = require('path');
|
|
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 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 "" "${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. Prefer instances without tight rate limits; skip a host after it fails.
|
|
const OVERPASS_ENDPOINTS = [
|
|
'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.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 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));
|
|
}
|
|
|
|
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) {
|
|
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:10];(${parts.join('')});(._;>;);out body qt;`;
|
|
}
|
|
|
|
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
|
|
});
|
|
}
|
|
}
|
|
return tiles;
|
|
}
|
|
|
|
function parseOverpassResponse(text, status) {
|
|
const looksLikeJson = /^\s*[\{\[]/.test(text);
|
|
if (!looksLikeJson) {
|
|
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 = true;
|
|
return { error: err };
|
|
}
|
|
let data;
|
|
try {
|
|
data = JSON.parse(text);
|
|
} catch (_) {
|
|
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 (!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) || status === 406 };
|
|
}
|
|
|
|
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: new URLSearchParams({ data: query }).toString(),
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
|
'Accept': 'application/json',
|
|
'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 !== 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. Trying another map server…');
|
|
err.retryable = true;
|
|
throw err;
|
|
}
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
async function fetchOverpass(query) {
|
|
let lastError;
|
|
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 {
|
|
const data = await fetchOverpassOnce(query, url, timeouts[round], gap);
|
|
lastGoodEndpointIdx = idx;
|
|
return data;
|
|
} catch (e) {
|
|
lastError = e;
|
|
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 minute and try again, or use a smaller map area.');
|
|
}
|
|
|
|
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 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 };
|
|
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);
|
|
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, retryAfterMs: e.retryAfterMs || 8000 });
|
|
}
|
|
});
|
|
|
|
// Geocode via OpenStreetMap Nominatim + Photon (no Google API key).
|
|
const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search';
|
|
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)' });
|
|
}
|
|
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 {
|
|
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);
|
|
}
|
|
}
|
|
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.' });
|
|
}
|
|
res.json({
|
|
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);
|
|
res.status(502).json({ error: e.message || 'Geocoding failed' });
|
|
}
|
|
});
|
|
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
|
});
|
|
|
|
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'
|
|
};
|
|
|
|
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' });
|
|
}
|
|
const minX = req.body.minX != null ? String(req.body.minX) : '';
|
|
const maxX = req.body.maxX != null ? String(req.body.maxX) : '';
|
|
const minY = req.body.minY != null ? String(req.body.minY) : '';
|
|
const maxY = req.body.maxY != null ? String(req.body.maxY) : '';
|
|
const form = new FormData();
|
|
form.append('image', new Blob([req.file.buffer]), req.file.originalname || 'image.png');
|
|
form.append('minX', minX);
|
|
form.append('maxX', maxX);
|
|
form.append('minY', minY);
|
|
form.append('maxY', maxY);
|
|
try {
|
|
const r = await fetch(`${ML_SEGMENT_URL}/segment`, {
|
|
method: 'POST',
|
|
body: form
|
|
});
|
|
const text = await r.text();
|
|
if (!r.ok) {
|
|
let err = { error: 'Segmentation server error' };
|
|
try {
|
|
const j = JSON.parse(text);
|
|
if (j.error) err = j;
|
|
} catch (_) {}
|
|
return res.status(r.status === 503 ? 503 : 502).json(err);
|
|
}
|
|
let data;
|
|
try {
|
|
data = JSON.parse(text);
|
|
} catch (_) {
|
|
return res.status(502).json({ error: 'Invalid response from segmentation server' });
|
|
}
|
|
res.json(data);
|
|
} catch (e) {
|
|
console.error('Segment proxy error:', e.message);
|
|
res.status(503).json({
|
|
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 — ' + APP_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;
|
|
});
|