feat: add standalone maps-to-dxf web application
Node.js/Express server with web GUI for converting Google Maps links to DXF files. Includes optional Python ML server for satellite lot detection. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b035ed1763
commit
7c20a404bf
14 files changed
+4491
No files matched your search
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* 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 } = require('child_process');
|
||||
const multer = require('multer');
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3456;
|
||||
const 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}"`;
|
||||
exec(cmd, () => {});
|
||||
}
|
||||
|
||||
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.
|
||||
const OVERPASS_ENDPOINTS = [
|
||||
'https://overpass-api.de/api/interpreter',
|
||||
'https://overpass.kumi.systems/api/interpreter',
|
||||
'https://overpass.openstreetmap.fr/api/interpreter'
|
||||
];
|
||||
const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool; https://github.com)';
|
||||
|
||||
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
|
||||
});
|
||||
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;
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch (parseErr) {
|
||||
lastError = new Error('Overpass returned invalid JSON. Try again later.');
|
||||
continue;
|
||||
}
|
||||
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') {
|
||||
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;
|
||||
`;
|
||||
try {
|
||||
const data = await fetchOverpass(query);
|
||||
res.json(data);
|
||||
} catch (e) {
|
||||
const msg = e.message || 'Overpass request failed';
|
||||
console.error('Overpass error:', msg);
|
||||
res.status(502).json({ error: msg });
|
||||
}
|
||||
});
|
||||
|
||||
// Geocode address/place via OpenStreetMap Nominatim (no API key; use respectful User-Agent)
|
||||
const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search';
|
||||
const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool)';
|
||||
|
||||
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'
|
||||
});
|
||||
try {
|
||||
const r = await fetch(`${NOMINATIM_URL}?${params}`, {
|
||||
headers: { 'User-Agent': GEOCODE_USER_AGENT }
|
||||
});
|
||||
const text = await r.text();
|
||||
if (!r.ok) {
|
||||
return res.status(502).json({ error: 'Geocoding service unavailable' });
|
||||
}
|
||||
if (!/^\s*[\{\[]/.test(text)) {
|
||||
if (/<\?xml|<!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.' });
|
||||
}
|
||||
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 || '' }))
|
||||
});
|
||||
} 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_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)
|
||||
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. Start the Python server: cd ml_server && pip install -r requirements.txt && python segment_server.py'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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, () => {
|
||||
console.log('MAPS to DXF — ' + URL);
|
||||
openBrowser();
|
||||
});
|
||||
Reference in new issue
Block a user