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:
Michael-A-SloanandCursor committed 2026-06-25 15:30:38 -04:00
1 parent b035ed1763
commit 7c20a404bf
14 files changed
+4491

No files matched your search

+807
View File
@@ -0,0 +1,807 @@
/**
* Client-side logic: coords, preview data, DXF generation (ported from Apps Script).
* 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 extractCoordinates(url) {
const s = String(url).trim();
// Google Maps: ...@lat,lon... Google Earth Web: ...@lat,lon... or ...@lat,lon,altitudea,distanced...
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
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])));
else if (altMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(altMatch[1]) * 2));
return { lat, lon, viewMeters };
}
var DEFAULT_LAYER_OPTIONS = {
buildings: true,
roads: true,
railways: true,
paths: true,
water: true,
parks: true,
landuse: true,
parkingOutline: true,
parkingSpaces: true,
trees: true,
barriers: true,
power: true,
boundary: true,
man_made: true
};
function getWayLayerKey(el) {
if (!el.tags) return null;
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) return 'railways';
if (el.tags.building) return 'buildings';
if (el.tags.amenity === 'parking') return 'parkingOutline';
if (el.tags.landuse) return 'landuse';
if (el.tags.natural === 'water' || el.tags.water) return 'water';
if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') return 'parks';
if (el.tags.barrier) return 'barriers';
if (el.tags.highway) return ['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway) ? 'paths' : 'roads';
if (el.tags.power) return 'power';
if (el.tags.boundary) return 'boundary';
if (el.tags.man_made) return 'man_made';
return null;
}
function getNodeLayerKey(tags) {
if (!tags) return null;
if (tags.natural === 'tree' || tags.natural === 'tree_row') return 'trees';
if (tags.amenity === 'parking_space') return 'parkingSpaces';
return null;
}
function buildPreviewData(osmData, origin, layerOptions) {
const opts = layerOptions || DEFAULT_LAYER_OPTIONS;
const on = function (key) { return opts[key] !== false; };
const r2 = (v) => Math.round(v * 100) / 100;
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
const out = [];
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags
};
}
});
const s = 8;
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;
for (const id in nodes) {
const n = nodes[id];
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
if (n.tags.natural === 'tree' || n.tags.natural === 'tree_row') {
out.push(['C', r2(n.x), r2(n.y), 2.5, 3]);
} else if (n.tags.amenity === 'parking_space') {
out.push(['R', r2(n.x), r2(n.y), PARKING_SPOT_HW, PARKING_SPOT_HH, 9]);
}
}
}
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let color = '7';
let isRoad = false;
let roadHalfWidth = 0;
let isRail = false;
if (el.tags) {
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) {
isRail = true;
color = '6';
} else if (el.tags.building) color = '1';
else if (el.tags.amenity === 'parking') color = '9';
else if (el.tags.landuse) color = '253';
else if (el.tags.natural === 'water' || el.tags.water) color = '5';
else if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') color = '3';
else if (el.tags.barrier) color = '8';
else if (el.tags.power) color = '8';
else if (el.tags.boundary) color = '253';
else if (el.tags.man_made) color = '8';
else if (el.tags.highway) {
if (['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway)) color = '2';
else {
isRoad = true;
if (['motorway', 'trunk'].includes(el.tags.highway)) roadHalfWidth = 8;
else if (['primary', 'secondary'].includes(el.tags.highway)) roadHalfWidth = 5;
else if (el.tags.highway === 'service') roadHalfWidth = 2.5;
else roadHalfWidth = 3;
if (['motorway', 'trunk'].includes(el.tags.highway)) color = '6';
else if (['primary', 'secondary'].includes(el.tags.highway)) color = '4';
else if (el.tags.highway === 'service') color = '8';
else color = '2';
}
}
}
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (!n1 || !n2) continue;
const dx = n2.x - n1.x;
const dy = n2.y - n1.y;
const len = Math.sqrt(dx * dx + dy * dy);
let nx = 0, ny = 0;
if (len > 0) {
nx = -dy / len;
ny = dx / len;
}
if (isRail && len > 0) {
const halfGauge = 0.72, tieSpacing = 2.0, tieHalfLen = 1.2, ux = dx / len, uy = dy / len;
out.push(['L', r2(n1.x + nx * halfGauge), r2(n1.y + ny * halfGauge), r2(n2.x + nx * halfGauge), r2(n2.y + ny * halfGauge), 6]);
out.push(['L', r2(n1.x - nx * halfGauge), r2(n1.y - ny * halfGauge), r2(n2.x - nx * halfGauge), r2(n2.y - ny * halfGauge), 6]);
if (len < tieSpacing) {
const midX = (n1.x + n2.x) / 2, midY = (n1.y + n2.y) / 2;
out.push(['L', r2(midX - nx * tieHalfLen), r2(midY - ny * tieHalfLen), r2(midX + nx * tieHalfLen), r2(midY + ny * tieHalfLen), 8]);
} else {
for (let dist = 0; dist <= len; dist += tieSpacing) {
const posX = n1.x + ux * dist, posY = n1.y + uy * dist;
out.push(['L', r2(posX - nx * tieHalfLen), r2(posY - ny * tieHalfLen), r2(posX + nx * tieHalfLen), r2(posY + ny * tieHalfLen), 8]);
}
}
} else if (isRoad && roadHalfWidth > 0 && len > 0) {
out.push(['L', r2(n1.x + nx * roadHalfWidth), r2(n1.y + ny * roadHalfWidth), r2(n2.x + nx * roadHalfWidth), r2(n2.y + ny * roadHalfWidth), color]);
out.push(['L', r2(n1.x - nx * roadHalfWidth), r2(n1.y - ny * roadHalfWidth), r2(n2.x - nx * roadHalfWidth), r2(n2.y - ny * roadHalfWidth), color]);
} else {
out.push(['L', r2(n1.x), r2(n1.y), r2(n2.x), r2(n2.y), color]);
}
}
});
return out;
}
function generateHighDetailDXF(osmData, origin, layerOptions) {
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);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags
};
}
});
let dxf = '0\nSECTION\n2\nHEADER\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';
const s = 8;
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;
for (const id in nodes) {
const n = nodes[id];
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
if (n.tags.natural === 'tree' || n.tags.natural === 'tree_row') {
dxf += `0\nCIRCLE\n8\nLANDSCAPE_TREES\n62\n3\n10\n${n.x}\n20\n${n.y}\n40\n2.5\n`;
} else if (n.tags.amenity === 'parking_space') {
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x - PARKING_HW}\n20\n${n.y - PARKING_HH}\n11\n${n.x + PARKING_HW}\n21\n${n.y - PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x + PARKING_HW}\n20\n${n.y - PARKING_HH}\n11\n${n.x + PARKING_HW}\n21\n${n.y + PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x + PARKING_HW}\n20\n${n.y + PARKING_HH}\n11\n${n.x - PARKING_HW}\n21\n${n.y + PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x - PARKING_HW}\n20\n${n.y + PARKING_HH}\n11\n${n.x - PARKING_HW}\n21\n${n.y - PARKING_HH}\n`;
}
}
}
function addHatchForPolygon(layerName, points, colorCode, patternName, scale) {
if (!points || points.length < 3) return '';
const n = points.length;
const sc = scale != null ? scale : 1;
let s = `0\nHATCH\n8\n${layerName}\n62\n${colorCode}\n2\n${patternName}\n70\n1\n71\n0\n41\n${sc}\n91\n1\n92\n2\n93\n${n}\n72\n0\n73\n1\n`;
points.forEach(function(p) { s += `10\n${p.x}\n20\n${p.y}\n`; });
return s;
}
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;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
const points = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const nn = nodes[el.nodes[i]];
if (nn) points.push({ x: nn.x, y: nn.y });
}
if (points.length < 3) return;
if (el.tags && el.tags.building) {
dxf += addHatchForPolygon('BUILDINGS_HATCH', points, 1, 'ANSI31', 0.8);
} else if (el.tags && el.tags.landuse) {
dxf += addHatchForPolygon('OPEN_LAND', points, 3, 'ANSI31', 0.5);
}
});
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let layer = '0', color = '7', isRoad = false, roadHalfWidth = 0, isRail = false, lineType = 'CONTINUOUS';
if (el.tags) {
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) {
isRail = true;
layer = 'RAILWAY_RAILS';
color = '6';
} else if (el.tags.building) {
layer = 'BUILDINGS';
color = '1';
} else if (el.tags.amenity === 'parking') {
layer = 'PARKING_OUTLINE';
color = '1'; /* red (original site-plan) */
} else if (el.tags.landuse) {
layer = 'SITE_BOUNDARIES';
color = '253';
lineType = 'DASHED';
} else if (el.tags.natural === 'water' || el.tags.water) {
layer = 'WATER';
color = '5';
} else if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') {
layer = 'PARKS';
color = '3';
} else if (el.tags.barrier) {
layer = 'SITE_FENCES';
color = '8';
} else if (el.tags.power) {
layer = 'POWER';
color = '8';
} else if (el.tags.boundary) {
layer = 'BOUNDARY';
color = '253';
lineType = 'DASHED';
} else if (el.tags.man_made) {
layer = 'MAN_MADE';
color = '8';
} else if (el.tags.highway) {
if (['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway)) {
layer = 'ROADS_PATH';
color = '2';
} else {
isRoad = true;
if (['motorway', 'trunk'].includes(el.tags.highway)) {
layer = 'ROADS_HIGHWAY';
color = '6';
roadHalfWidth = 8;
} else if (['primary', 'secondary'].includes(el.tags.highway)) {
layer = 'ROADS_MAJOR';
color = '4';
roadHalfWidth = 5;
} else if (el.tags.highway === 'service') {
layer = 'ROADS_SERVICE';
color = '8';
roadHalfWidth = 2.5;
} else {
layer = 'ROADS_MINOR';
color = '2';
roadHalfWidth = 3;
}
}
}
}
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (!n1 || !n2) continue;
const dx = n2.x - n1.x;
const dy = n2.y - n1.y;
const len = Math.sqrt(dx * dx + dy * dy);
let nx = 0, ny = 0;
if (len > 0) {
nx = -dy / len;
ny = dx / len;
}
if (isRail && len > 0) {
const halfGauge = 0.72, tieSpacing = 2.0, tieHalfLen = 1.2, ux = dx / len, uy = dy / len;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x + nx * halfGauge}\n20\n${n1.y + ny * halfGauge}\n11\n${n2.x + nx * halfGauge}\n21\n${n2.y + ny * halfGauge}\n`;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x - nx * halfGauge}\n20\n${n1.y - ny * halfGauge}\n11\n${n2.x - nx * halfGauge}\n21\n${n2.y - ny * halfGauge}\n`;
if (len < tieSpacing) {
const midX = (n1.x + n2.x) / 2, midY = (n1.y + n2.y) / 2;
dxf += `0\nLINE\n8\nRAILWAY_TIES\n62\n8\n10\n${midX - nx * tieHalfLen}\n20\n${midY - ny * tieHalfLen}\n11\n${midX + nx * tieHalfLen}\n21\n${midY + ny * tieHalfLen}\n`;
} else {
for (let dist = 0; dist <= len; dist += tieSpacing) {
const posX = n1.x + ux * dist, posY = n1.y + uy * dist;
dxf += `0\nLINE\n8\nRAILWAY_TIES\n62\n8\n10\n${posX - nx * tieHalfLen}\n20\n${posY - ny * tieHalfLen}\n11\n${posX + nx * tieHalfLen}\n21\n${posY + ny * tieHalfLen}\n`;
}
}
} else if (isRoad && roadHalfWidth > 0 && len > 0) {
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x + nx * roadHalfWidth}\n20\n${n1.y + ny * roadHalfWidth}\n11\n${n2.x + nx * roadHalfWidth}\n21\n${n2.y + ny * roadHalfWidth}\n`;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x - nx * roadHalfWidth}\n20\n${n1.y - ny * roadHalfWidth}\n11\n${n2.x - nx * roadHalfWidth}\n21\n${n2.y - ny * roadHalfWidth}\n`;
} else {
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n6\n${lineType}\n10\n${n1.x}\n20\n${n1.y}\n11\n${n2.x}\n21\n${n2.y}\n`;
}
}
if (el.tags && el.tags.name && (isRoad || isRail)) {
const midIdx = Math.floor((el.nodes.length - 1) / 2);
const p1 = nodes[el.nodes[midIdx]];
const p2 = nodes[el.nodes[midIdx + 1]];
if (p1 && p2) {
const pdx = p2.x - p1.x, pdy = p2.y - p1.y;
let angle = (Math.atan2(pdy, pdx) * 180) / Math.PI;
if (angle > 90) angle -= 180;
if (angle < -90) angle += 180;
const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;
const safeName = String(el.tags.name).replace(/[\\{}]/g, '');
const txtLayer = isRail ? 'LABELS_RAIL' : 'LABELS_ROADS';
dxf += `0\nTEXT\n8\n${txtLayer}\n62\n7\n10\n${mx}\n20\n${my}\n40\n5.0\n50\n${angle}\n1\n${safeName}\n72\n1\n73\n2\n11\n${mx}\n21\n${my}\n`;
}
}
});
dxf += '0\nENDSEC\n0\nEOF';
return dxf;
}
/**
* Convex hull (Graham scan). Returns hull points in CCW order.
*/
function convexHull(points) {
if (points.length < 3) return points.slice();
const pts = points.slice();
const start = pts.reduce((min, p, i) => (p.y < min.y || (p.y === min.y && p.x < min.x)) ? p : min, pts[0]);
pts.sort((a, b) => {
const ax = a.x - start.x, ay = a.y - start.y;
const bx = b.x - start.x, by = b.y - start.y;
const cross = ax * by - ay * bx;
if (Math.abs(cross) > 1e-10) return cross > 0 ? -1 : 1;
return (ax * ax + ay * ay) - (bx * bx + by * by);
});
const hull = [pts[0], pts[1]];
for (let i = 2; i < pts.length; i++) {
let p = pts[i];
while (hull.length >= 2) {
const a = hull[hull.length - 2], b = hull[hull.length - 1];
const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
if (cross <= 0) hull.pop();
else break;
}
hull.push(p);
}
return hull;
}
const CLUSTER_DISTANCE_METERS = 75;
const MAX_SITE_AREA = 25000;
const MAX_EDGE_METERS = 38;
function segmentIntersect(a1, a2, b1, b2) {
const ax = a2.x - a1.x, ay = a2.y - a1.y;
const bx = b2.x - b1.x, by = b2.y - b1.y;
const d = ax * by - ay * bx;
if (Math.abs(d) < 1e-10) return false;
const t = ((b1.x - a1.x) * by - (b1.y - a1.y) * bx) / d;
const u = ((b1.x - a1.x) * ay - (b1.y - a1.y) * ax) / d;
return t > 1e-6 && t < 1 - 1e-6 && u > 1e-6 && u < 1 - 1e-6;
}
function pointInPolygon(p, poly) {
let inside = false;
const n = poly.length;
for (let i = 0, j = n - 1; i < n; j = i++) {
const xi = poly[i].x, yi = poly[i].y, xj = poly[j].x, yj = poly[j].y;
if (((yi > p.y) !== (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi)) inside = !inside;
}
return inside;
}
/**
* Concave hull: tighten convex hull by splitting edges longer than maxEdge.
* Keeps boundary closer to buildings so it's less likely to cross roads/lot lines.
*/
function concaveHull(points, maxEdge) {
if (points.length < 3) return points.slice();
let hull = convexHull(points);
const max2 = maxEdge * maxEdge;
for (let round = 0; round < 50; round++) {
let changed = false;
for (let i = 0; i < hull.length; i++) {
const a = hull[i];
const b = hull[(i + 1) % hull.length];
const len2 = (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
if (len2 <= max2) continue;
let best = null;
let bestMax2 = len2;
for (const p of points) {
if (p === a || p === b) continue;
const d1 = (p.x - a.x) ** 2 + (p.y - a.y) ** 2;
const d2 = (p.x - b.x) ** 2 + (p.y - b.y) ** 2;
if (d1 >= len2 || d2 >= len2) continue;
const testHull = hull.slice(0, i + 1).concat([p], hull.slice(i + 1));
let cross = false;
for (let j = 0; j < testHull.length && !cross; j++) {
const c = testHull[j], d = testHull[(j + 1) % testHull.length];
if (c === a || c === b || c === p || d === a || d === b || d === p) continue;
if (segmentIntersect(a, p, c, d) || segmentIntersect(p, b, c, d)) cross = true;
}
if (cross) continue;
const mp = Math.max(d1, d2);
if (mp < bestMax2) {
bestMax2 = mp;
best = p;
}
}
if (best) {
hull = hull.slice(0, i + 1).concat([best], hull.slice(i + 1));
changed = true;
break;
}
}
if (!changed) break;
}
return hull;
}
/**
* Site boundary = concave hull per cluster (tighter than convex so boundaries don't cross roads).
* Clusters buildings within ~75m; uses max edge length so lot lines/gaps are respected.
*/
function getOSMSiteBoundaryAsLot(osmData, origin) {
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat
};
}
});
const features = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 3) return;
const closed = el.nodes[0] === el.nodes[el.nodes.length - 1];
const isBuilding = el.tags && el.tags.building;
const isParking = el.tags && el.tags.amenity === 'parking';
if (!closed || (!isBuilding && !isParking)) return;
const points = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const n = nodes[el.nodes[i]];
if (n) points.push({ x: n.x, y: n.y });
}
if (points.length < 3) return;
const cx = points.reduce((s, p) => s + p.x, 0) / points.length;
const cy = points.reduce((s, p) => s + p.y, 0) / points.length;
features.push({ points, centroid: { x: cx, y: cy } });
});
if (features.length === 0) return [];
const clusters = [];
for (const f of features) {
let best = -1;
let bestDist = CLUSTER_DISTANCE_METERS;
for (let i = 0; i < clusters.length; i++) {
const c = clusters[i];
const d = Math.hypot(f.centroid.x - c.cx, f.centroid.y - c.cy);
if (d < bestDist) {
bestDist = d;
best = i;
}
}
if (best >= 0) {
const c = clusters[best];
c.points.push(...f.points);
const n = c.count + 1;
c.cx = (c.cx * c.count + f.centroid.x) / n;
c.cy = (c.cy * c.count + f.centroid.y) / n;
c.count = n;
} else {
clusters.push({
points: f.points.slice(),
cx: f.centroid.x,
cy: f.centroid.y,
count: 1
});
}
}
const polygons = [];
for (const c of clusters) {
if (c.points.length < 3) continue;
const hull = concaveHull(c.points, MAX_EDGE_METERS);
const area = polygonAreaOSM(hull);
if (area >= 100 && area <= MAX_SITE_AREA) polygons.push(hull);
}
return polygons;
}
/**
* Get closed OSM landuse-only polygons as lot candidates (no buildings).
* Used when imagery finds no contours. For "whole property" use getOSMSiteBoundaryAsLot instead.
*/
function getOSMLotsAsPolygons(osmData, origin) {
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat
};
}
});
const polygons = [];
const MAX_LOT_AREA = 8000;
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
const closed = el.nodes[0] === el.nodes[el.nodes.length - 1];
if (!closed) return;
if (!el.tags || !el.tags.landuse) return;
const poly = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const n = nodes[el.nodes[i]];
if (n) poly.push({ x: n.x, y: n.y });
}
if (poly.length >= 3) {
const area = polygonAreaOSM(poly);
if (area >= 20 && area <= MAX_LOT_AREA) polygons.push(poly);
}
});
return polygons;
}
function polygonAreaOSM(points) {
let a = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
a += points[i].x * points[j].y - points[j].x * points[i].y;
}
return Math.abs(a) / 2;
}
/**
* Append user-drawn lot polygons to DXF (same coordinate system as map).
* lots: array of polygons, each polygon = array of { x, y } in meters from origin.
*/
function appendLotsToDXF(dxfContent, lots) {
if (!lots || lots.length === 0) return dxfContent;
let block = '';
lots.forEach((poly) => {
if (!poly || poly.length < 2) return;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
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');
}
/**
* Polygon area in world coords (m²). Poly is array of { x, y }, closed.
*/
function polygonAreaWorld(poly) {
if (!poly || poly.length < 3) return 0;
let a = 0;
for (let i = 0; i < poly.length; i++) {
const j = (i + 1) % poly.length;
a += poly[i].x * poly[j].y - poly[j].x * poly[i].y;
}
return Math.abs(a) / 2;
}
/**
* Polygon perimeter in world coords (meters).
*/
function polygonPerimeter(poly) {
if (!poly || poly.length < 2) return 0;
let p = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
p += Math.hypot(b.x - a.x, b.y - a.y);
}
return p;
}
/**
* Classify an imagery contour for land-lot drawing: 'tree' | 'building' | 'lot' | null.
* Trees: small, round. Buildings: medium, compact. Lots: parcel-like (compact, not thin strips).
*/
function classifyImageryContour(poly) {
if (!poly || poly.length < 3) return null;
const area = polygonAreaWorld(poly);
const perim = polygonPerimeter(poly);
if (perim < 0.5) return null;
const compactness = (4 * Math.PI * area) / (perim * perim);
if (area >= 2 && area <= 55 && compactness > 0.35) return 'tree';
if (area >= 15 && area <= 900 && compactness > 0.10) return 'building';
// Lots: parcel-like shape (compactness > 0.08), 150–20k m² — avoids thin strips and noise
if (area >= 150 && area <= 20000 && compactness > 0.08) return 'lot';
return null;
}
/**
* Filter imagery polylines to only those suitable for land lot drawings (trees, buildings, lots).
* Returns { trees: [], buildings: [], lots: [], all: [] }.
*/
function filterImageryPolylinesForLotDrawing(polylines) {
const out = { trees: [], buildings: [], lots: [], all: [] };
if (!polylines || !polylines.length) return out;
polylines.forEach((poly) => {
const kind = classifyImageryContour(poly);
if (!kind) return;
out[kind].push(poly);
out.all.push(poly);
});
return out;
}
/**
* Build nodes map { id: { x, y, tags } } in meters from origin. Used for OSM snap and DXF.
*/
function getOSMNodesInMeters(osmData, origin) {
if (!osmData || !origin) return {};
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags || {}
};
}
});
return nodes;
}
/**
* Collect OSM way segments (buildings, roads, etc.) for snapping. Returns array of { a: {x,y}, b: {x,y} }.
*/
function getOSMSnapSegments(osmData, nodes) {
if (!osmData || !osmData.elements || !nodes) return [];
const segments = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const hasBuilding = el.tags && el.tags.building;
const hasHighway = el.tags && el.tags.highway;
const hasLanduse = el.tags && el.tags.landuse;
if (!hasBuilding && !hasHighway && !hasLanduse) return;
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (n1 && n2) segments.push({ a: { x: n1.x, y: n1.y }, b: { x: n2.x, y: n2.y } });
}
});
return segments;
}
/**
* Project point p onto segment a-b. Returns { x, y, dist } of closest point and distance.
*/
function projectPointOnSegment(p, a, b) {
const dx = b.x - a.x, dy = b.y - a.y;
const lenSq = dx * dx + dy * dy;
if (lenSq < 1e-20) return { x: a.x, y: a.y, dist: Math.hypot(p.x - a.x, p.y - a.y) };
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq;
t = Math.max(0, Math.min(1, t));
const x = a.x + t * dx, y = a.y + t * dy;
return { x, y, dist: Math.hypot(p.x - x, p.y - y) };
}
/**
* Snap imagery trace polylines to OSM ways (buildings, roads, landuse) within maxSnapMeters.
* Returns new array of polylines with points snapped to nearest OSM segment when within distance.
*/
function snapTracePolylinesToOSM(polylines, osmData, nodes, maxSnapMeters) {
if (!polylines || polylines.length === 0) return polylines;
const segments = getOSMSnapSegments(osmData, nodes);
if (segments.length === 0) return polylines;
const maxD = maxSnapMeters != null ? maxSnapMeters : 1.5;
return polylines.map((poly) => {
if (!poly || poly.length < 2) return poly;
return poly.map((p) => {
let best = { x: p.x, y: p.y, dist: Infinity };
for (let i = 0; i < segments.length; i++) {
const proj = projectPointOnSegment(p, segments[i].a, segments[i].b);
if (proj.dist < best.dist && proj.dist <= maxD) best = { x: proj.x, y: proj.y, dist: proj.dist };
}
return { x: best.x, y: best.y };
});
});
}
/**
* Append vectorized satellite/imagery edges to DXF as lines.
* polylines: array of polylines. layerName: DXF layer (default IMAGERY_TRACE).
* minSegmentMeters, minLengthMeters: filter very short segments/lines.
*/
function appendImageryTraceToDXF(dxfContent, polylines, minSegmentMeters, minLengthMeters, layerName) {
if (!polylines || polylines.length === 0) return dxfContent;
const minSeg = minSegmentMeters != null ? minSegmentMeters : 0.2;
const minLen = minLengthMeters != null ? minLengthMeters : 0.5;
const layer = layerName || 'IMAGERY_TRACE';
let block = '';
polylines.forEach((poly) => {
if (!poly || poly.length < 2) return;
let totalLen = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
totalLen += Math.hypot(b.x - a.x, b.y - a.y);
}
if (totalLen < minLen) return;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (len < minSeg) continue;
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');
}
/**
* 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.
*/
function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX, maxY, widthPx, heightPx) {
const handle = '1F0';
const w = maxX - minX;
const h = maxY - minY;
const uPerPx = w / widthPx;
const vPerPx = h / heightPx;
/* 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 =
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${minX}\n20\n${minY}\n30\n0\n11\n${maxX}\n21\n${minY}\n31\n0\n` +
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${maxX}\n20\n${minY}\n30\n0\n11\n${maxX}\n21\n${maxY}\n31\n0\n` +
`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` +
`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`;
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 + imageEntity + '0\nENDSEC\n' + objectsSection);
}
+1681
View File
File diff suppressed because it is too large. Load diff