-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
452 lines (383 loc) · 15.1 KB
/
Copy pathserver.js
File metadata and controls
452 lines (383 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/**
* server.js — Express HTTP server (entry point)
*
* Responsibilities:
* - Serve the static frontend from /public.
* - POST /api/graph → fetch + build road graph for a city (legacy).
* - POST /api/graph-bbox → fetch + merge road graph for a bounding box.
* - POST /api/route → find shortest path between two GPS points.
* - Single merged in-memory graph that grows as the user explores.
*/
const express = require("express");
const path = require("path");
const axios = require("axios");
const { fetchRoadGraph, fetchRoadGraphByBBox, fetchCorridorRoads } = require("./src/overpass");
const { buildGraph, haversineDistance, buildGridIndex } = require("./src/graph");
const { dijkstra } = require("./src/dijkstra");
const { astar } = require("./src/astar");
const { bfs } = require("./src/bfs");
const { dfs } = require("./src/dfs");
const { bidirectionalDijkstra } = require("./src/bidirectional");
const app = express();
const PORT = process.env.PORT || 3000;
// ── Middleware ───────────────────────────────────────────────────────
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// ── Single merged graph ─────────────────────────────────────────────
// Instead of per-city caching, we keep ONE global graph that merges
// new data as the user pans around.
let globalNodes = {}; // id → {lat, lon}
let globalGraph = new Map(); // adjacency list
let globalGrid = new Map(); // spatial index
// Track which bbox tiles have been loaded (0.05° grid)
const loadedTiles = new Set();
// Track which long-distance corridors have been loaded (quantized start-end key)
const loadedCorridors = new Set();
/**
* Quantize a bbox into 0.05° tile keys and return which ones are new.
*/
function getNewTiles(south, west, north, east) {
const TILE_SIZE = 0.05;
const newTiles = [];
for (let lat = Math.floor(south / TILE_SIZE) * TILE_SIZE; lat < north; lat += TILE_SIZE) {
for (let lon = Math.floor(west / TILE_SIZE) * TILE_SIZE; lon < east; lon += TILE_SIZE) {
const key = `${lat.toFixed(3)},${lon.toFixed(3)}`;
if (!loadedTiles.has(key)) {
newTiles.push(key);
}
}
}
return newTiles;
}
/**
* Merge new OSM data into the global graph.
*/
function mergeIntoGlobal(osmData) {
// Merge nodes
Object.assign(globalNodes, osmData.nodes);
// Build a temporary graph from the new data
const newGraph = buildGraph(osmData);
// Merge edges into globalGraph
for (const [nodeId, neighbors] of newGraph.entries()) {
if (!globalGraph.has(nodeId)) {
globalGraph.set(nodeId, []);
}
const existing = globalGraph.get(nodeId);
const existingSet = new Set(existing.map(e => e.neighborId));
for (const edge of neighbors) {
if (!existingSet.has(edge.neighborId)) {
existing.push(edge);
}
}
}
// Rebuild grid index (fast — it's just a hash map scan)
globalGrid = buildGridIndex(globalNodes, globalGraph);
}
// ── Helpers ─────────────────────────────────────────────────────────
function findNearestNode(lat, lon) {
const latBucket = Math.floor(lat * 100);
const lonBucket = Math.floor(lon * 100);
const candidates = [];
for (let i = -3; i <= 3; i++) {
for (let j = -3; j <= 3; j++) {
const key = `${latBucket + i},${lonBucket + j}`;
if (globalGrid.has(key)) {
candidates.push(...globalGrid.get(key));
}
}
}
if (candidates.length === 0) {
// Fallback: search all nodes
for (const ids of globalGrid.values()) candidates.push(...ids);
}
let bestId = null;
let bestDist = Infinity;
for (const id of candidates) {
const coord = globalNodes[id] ?? globalNodes[Number(id)];
if (!coord) continue;
const d = haversineDistance(lat, lon, coord.lat, coord.lon);
if (d < bestDist) {
bestDist = d;
bestId = String(id);
}
}
return bestId;
}
function countEdges(graph) {
let total = 0;
for (const neighbors of graph.values()) {
total += neighbors.length;
}
return total;
}
// Mutex to prevent concurrent Overpass requests
let fetchInProgress = false;
// ── Routes ──────────────────────────────────────────────────────────
/**
* POST /api/graph-bbox
* Body: { south, west, north, east }
* Fetches road data for the visible map area and merges into the global graph.
*/
app.post("/api/graph-bbox", async (req, res) => {
try {
const { south, west, north, east } = req.body;
if ([south, west, north, east].some(v => typeof v !== "number")) {
return res.status(400).json({ error: "south, west, north, east must be numbers" });
}
// Check which tiles are new
const newTiles = getNewTiles(south, west, north, east);
if (newTiles.length === 0) {
return res.json({
cached: true,
nodeCount: globalGraph.size,
edgeCount: countEdges(globalGraph),
newNodes: 0
});
}
if (fetchInProgress) {
return res.json({
cached: true,
nodeCount: globalGraph.size,
edgeCount: countEdges(globalGraph),
newNodes: 0,
busy: true
});
}
fetchInProgress = true;
try {
const nodesBefore = globalGraph.size;
const osmData = await fetchRoadGraphByBBox(south, west, north, east);
mergeIntoGlobal(osmData);
// Mark all tiles in this bbox as loaded
for (const tile of newTiles) {
loadedTiles.add(tile);
}
const newNodes = globalGraph.size - nodesBefore;
console.log(`[server] Merged bbox → total ${globalGraph.size} nodes, ${countEdges(globalGraph)} edges (+${newNodes} new nodes)`);
return res.json({
cached: false,
nodeCount: globalGraph.size,
edgeCount: countEdges(globalGraph),
newNodes
});
} finally {
fetchInProgress = false;
}
} catch (err) {
fetchInProgress = false;
console.error("[server] /api/graph-bbox error:", err.message);
return res.status(500).json({ error: err.message });
}
});
/**
* POST /api/graph (legacy — still works for city-name loading)
*/
app.post("/api/graph", async (req, res) => {
try {
const { city } = req.body;
if (!city || typeof city !== "string") {
return res.status(400).json({ error: "Missing or invalid 'city' field" });
}
const osmData = await fetchRoadGraph(city);
mergeIntoGlobal(osmData);
return res.json({
cached: false,
nodeCount: globalGraph.size,
edgeCount: countEdges(globalGraph)
});
} catch (err) {
console.error("[server] /api/graph error:", err.message);
return res.status(500).json({ error: err.message });
}
});
/**
* POST /api/route
* Body: { startLat, startLon, endLat, endLon, algorithm }
* No more "city" field needed — uses the global merged graph.
*/
app.post("/api/route", async (req, res) => {
try {
const { startLat, startLon, endLat, endLon, algorithm } = req.body;
if ([startLat, startLon, endLat, endLon].some(v => typeof v !== "number")) {
return res.status(400).json({ error: "startLat, startLon, endLat, endLon must be numbers" });
}
// Auto-fetch corridor if needed (for inter-city / long distance routes)
const clickDist = haversineDistance(startLat, startLon, endLat, endLon);
console.log(`[route] Click distance: ${(clickDist/1000).toFixed(1)} km`);
if (clickDist > 2000000) {
// Distance > 2000km — Overpass will crash Node's memory limit if we try to fetch it
return res.status(400).json({ error: "Distance too large. Maximum supported routing distance is 2,000km." });
}
if (clickDist > 5000) {
// Create a unique key for this corridor (quantized to ~10km precision to handle slight marker drags)
const corridorKey = `${(startLat).toFixed(1)},${(startLon).toFixed(1)}|${(endLat).toFixed(1)},${(endLon).toFixed(1)}`;
if (loadedCorridors.has(corridorKey)) {
console.log(`[route] Corridor for ${corridorKey} already loaded. Skipping fetch.`);
} else {
console.log(`[route] Long distance detected. Auto-fetching corridor...`);
try {
const corridorData = await fetchCorridorRoads(startLat, startLon, endLat, endLon);
if (corridorData.ways.length > 0) {
mergeIntoGlobal(corridorData);
loadedCorridors.add(corridorKey);
console.log(`[route] Corridor merged → ${globalGraph.size} total nodes`);
}
} catch (err) {
console.warn(`[route] Corridor fetch failed: ${err.message}`);
}
}
}
if (globalGraph.size === 0) {
return res.status(400).json({ error: "No graph data loaded. Pan the map to load roads first." });
}
const startId = findNearestNode(startLat, startLon);
const endId = findNearestNode(endLat, endLon);
if (startId) {
const sc = globalNodes[startId] ?? globalNodes[Number(startId)];
if (sc) console.log(`[route] Start: (${startLat.toFixed(4)},${startLon.toFixed(4)}) → node ${startId}, dist=${haversineDistance(startLat, startLon, sc.lat, sc.lon).toFixed(0)}m`);
}
if (endId) {
const ec = globalNodes[endId] ?? globalNodes[Number(endId)];
if (ec) console.log(`[route] End: (${endLat.toFixed(4)},${endLon.toFixed(4)}) → node ${endId}, dist=${haversineDistance(endLat, endLon, ec.lat, ec.lon).toFixed(0)}m`);
}
if (!startId || !endId) {
return res.status(400).json({ error: "Could not find graph nodes near the given coordinates." });
}
if (!algorithm) {
return res.status(400).json({ error: "Missing 'algorithm' field" });
}
const result = runAlgorithm(algorithm, startId, endId);
if (result.error) return res.status(400).json({ error: result.error });
return res.json({
path: toCoords(result.path),
exploredNodes: toCoordsExplored(result.exploredNodes),
totalDistance: result.totalDistance,
nodesExplored: result.exploredNodes.length,
});
} catch (err) {
console.error("[server] /api/route error:", err.message);
return res.status(500).json({ error: err.message });
}
});
// ── Shared Helpers for Route Endpoints ──────────────────────────────
function runAlgorithm(name, startId, endId) {
switch (name.toLowerCase()) {
case "dijkstra":
return dijkstra(globalGraph, startId, endId);
case "astar":
return astar(globalGraph, startId, endId, globalNodes);
case "bfs":
return bfs(globalGraph, startId, endId);
case "dfs":
return dfs(globalGraph, startId, endId);
case "bidirectional":
return bidirectionalDijkstra(globalGraph, startId, endId);
default:
return { error: `Unknown algorithm: ${name}` };
}
}
function toCoords(ids) {
return ids.map(id => {
const n = globalNodes[id] ?? globalNodes[Number(id)];
return n ? { lat: n.lat, lon: n.lon } : null;
}).filter(Boolean);
}
function toCoordsExplored(items) {
return items.map(item => {
const isObj = typeof item === "object" && item !== null;
const id = isObj ? item.id : item;
const n = globalNodes[id] ?? globalNodes[Number(id)];
if (!n) return null;
if (isObj && item.direction) {
return { lat: n.lat, lon: n.lon, direction: item.direction };
}
return { lat: n.lat, lon: n.lon };
}).filter(Boolean);
}
/**
* POST /api/route-compare
* Body: { startLat, startLon, endLat, endLon, algorithmA, algorithmB }
* Runs two algorithms and returns both results for side-by-side comparison.
*/
app.post("/api/route-compare", async (req, res) => {
try {
const { startLat, startLon, endLat, endLon, algorithmA, algorithmB } = req.body;
if ([startLat, startLon, endLat, endLon].some(v => typeof v !== "number")) {
return res.status(400).json({ error: "startLat, startLon, endLat, endLon must be numbers" });
}
// Auto-fetch corridor for long distances
const clickDist = haversineDistance(startLat, startLon, endLat, endLon);
if (clickDist > 5000) {
try {
const corridorData = await fetchCorridorRoads(startLat, startLon, endLat, endLon);
if (corridorData.ways.length > 0) mergeIntoGlobal(corridorData);
} catch (err) {
console.warn(`[compare] Corridor fetch failed: ${err.message}`);
}
}
if (globalGraph.size === 0) {
return res.status(400).json({ error: "No graph data loaded." });
}
const startId = findNearestNode(startLat, startLon);
const endId = findNearestNode(endLat, endLon);
if (!startId || !endId) {
return res.status(400).json({ error: "Could not find graph nodes near the given coordinates." });
}
const resultA = runAlgorithm(algorithmA, startId, endId);
const resultB = runAlgorithm(algorithmB, startId, endId);
if (resultA.error) return res.status(400).json({ error: resultA.error });
if (resultB.error) return res.status(400).json({ error: resultB.error });
console.log(`[compare] ${algorithmA}: ${resultA.exploredNodes.length} explored, ${resultA.path.length} path | ${algorithmB}: ${resultB.exploredNodes.length} explored, ${resultB.path.length} path`);
return res.json({
a: {
path: toCoords(resultA.path),
exploredNodes: toCoordsExplored(resultA.exploredNodes),
totalDistance: resultA.totalDistance,
nodesExplored: resultA.exploredNodes.length,
},
b: {
path: toCoords(resultB.path),
exploredNodes: toCoordsExplored(resultB.exploredNodes),
totalDistance: resultB.totalDistance,
nodesExplored: resultB.exploredNodes.length,
}
});
} catch (err) {
console.error("[server] /api/route-compare error:", err.message);
return res.status(500).json({ error: err.message });
}
});
/**
* GET /api/geocode?q=search&viewbox=west,north,east,south
* Proxies to Nominatim with viewport bias to resolve place names.
*/
app.get("/api/geocode", async (req, res) => {
try {
const { q, viewbox } = req.query;
if (!q) return res.status(400).json({ error: "Missing 'q' parameter" });
const params = {
q,
format: "json",
limit: 5,
"accept-language": "en",
};
// Bias results to the current map viewport
if (viewbox) {
params.viewbox = viewbox;
params.bounded = 0; // prefer but don't restrict to viewbox
}
const response = await axios.get("https://nominatim.openstreetmap.org/search", {
params,
headers: { "User-Agent": "PathFinderApp/1.0" },
timeout: 10000,
});
return res.json(response.data);
} catch (err) {
console.error("[geocode] Error:", err.message);
return res.status(500).json({ error: err.message });
}
});
// ── Start ───────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});