ficed Bug when wrong Object is selected initialy

This commit is contained in:
PxlLoewe
2025-06-17 21:10:44 -07:00
parent fe77ef2c03
commit 29b57b2c37
3 changed files with 58 additions and 23 deletions

View File

@@ -0,0 +1,50 @@
import { OSMWay } from "@repo/db";
import { centroid, distance } from "@turf/turf";
function toPolygonFeature(nodes: { lat: number; lon: number }[]) {
if (!nodes || nodes.length < 3) return null;
const coords = nodes.map((n) => [n.lon, n.lat]);
const isClosed =
coords.length >= 1 &&
coords[0]![0] === coords[coords.length - 1]![0] &&
coords[0]![1] === coords[coords.length - 1]![1];
if (!isClosed) coords.push(coords[0]!); // Polygon schließen
return {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [coords],
},
properties: {},
};
}
// Hauptfunktion: findet das nächstgelegene Polygon zu einem Punkt
export function findClosestPolygon(
ways: OSMWay[],
referencePoint: {
lat: number;
lon: number;
},
): OSMWay | null {
let closest: OSMWay | null = null;
let minDistance = Infinity;
for (const way of ways) {
const polygon = toPolygonFeature(way.nodes);
if (!polygon) continue;
const center = centroid(polygon as any).geometry.coordinates; // [lon, lat]
const newDistance = distance([referencePoint.lon, referencePoint.lat], center);
if (newDistance < minDistance) {
minDistance = newDistance;
closest = way;
}
}
return closest;
}