-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
417 lines (352 loc) · 10.7 KB
/
app.js
File metadata and controls
417 lines (352 loc) · 10.7 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
// OSMTimeMachine - Client-side application
// All logic runs in the browser for GitHub Pages deployment
// Global state
let map = null;
let currentPolygon = null;
let coordinates = [];
let TimeMachine = {};
let slider = null;
// Color palette for polygons
const colorPalette = [
'#667eea', '#764ba2', '#f093fb', '#f5576c',
'#4facfe', '#00f2fe', '#43e97b', '#38f9d7',
'#fa709a', '#fee140', '#30cfd0', '#330867'
];
// DOM elements
const searchForm = document.getElementById('searchForm');
const wayIdInput = document.getElementById('wayIdInput');
const loadingOverlay = document.getElementById('loadingOverlay');
const errorAlert = document.getElementById('errorAlert');
const errorMessage = document.getElementById('errorMessage');
const emptyState = document.getElementById('emptyState');
const mapContainer = document.getElementById('mapContainer');
const wayBadgeContainer = document.getElementById('wayBadgeContainer');
const wayIdDisplay = document.getElementById('wayIdDisplay');
const osmLink = document.getElementById('osmLink');
const historyContent = document.getElementById('historyContent');
/**
* Validate way ID input
*/
function validateWayId(wayId) {
if (!wayId || !wayId.trim()) {
return { valid: false, error: 'Way ID is required' };
}
const trimmedId = wayId.trim();
const wayIdInt = parseInt(trimmedId, 10);
if (isNaN(wayIdInt)) {
return { valid: false, error: 'Way ID must be a valid number' };
}
if (wayIdInt <= 0) {
return { valid: false, error: 'Way ID must be a positive number' };
}
return { valid: true, wayId: wayIdInt };
}
/**
* Show error message
*/
function showError(message) {
errorMessage.textContent = message;
errorAlert.classList.remove('hidden');
}
/**
* Hide error message
*/
function hideError() {
errorAlert.classList.add('hidden');
}
/**
* Show loading overlay
*/
function showLoading() {
loadingOverlay.classList.add('active');
}
/**
* Hide loading overlay
*/
function hideLoading() {
loadingOverlay.classList.remove('active');
}
/**
* Fetch way history from Overpass API
*/
async function fetchWayHistory(wayId) {
const overpassQuery = `
[out:json];
timeline(way,${wayId});
foreach(
out;
retro(u(t["created"]))
(
way(${wayId}); out meta geom;
>; out meta;
);
);
`;
const overpassUrl = 'https://overpass-api.de/api/interpreter';
try {
const response = await fetch(overpassUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `data=${encodeURIComponent(overpassQuery)}`,
});
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
if (!data || typeof data !== 'object' || !data.elements) {
throw new Error('Invalid response structure from API');
}
return { success: true, data };
} catch (error) {
console.error('Error fetching way history:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
return {
success: false,
error: 'Unable to connect to Overpass API. Please check your internet connection.'
};
}
return {
success: false,
error: error.message || 'An unexpected error occurred'
};
}
}
/**
* Process API response into coordinates
*/
function processWayData(data) {
const coords = [];
if (!data || !data.elements) {
return coords;
}
for (const element of data.elements) {
if (element.type === 'way' && element.geometry && element.geometry.length > 0) {
coords.push({
geometry: element.geometry,
version: element.version || 'Unknown',
timestamp: element.timestamp || 'Unknown',
user: element.user || 'Unknown',
tags: element.tags || {}
});
}
}
return coords;
}
/**
* Initialize map
*/
function initializeMap(firstCoord) {
if (map) {
map.remove();
}
map = L.map('map').setView([firstCoord.lat, firstCoord.lon], 18);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
maxZoom: 20,
}).addTo(map);
}
/**
* Format timestamp to human-readable format
*/
function formatTimestamp(timestamp) {
if (!timestamp || timestamp === 'Unknown') {
return 'Unknown';
}
try {
const date = new Date(timestamp);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
} catch (e) {
return timestamp;
}
}
/**
* Update history display
*/
function updateHistory(index) {
const coord = coordinates[index];
// Build tags HTML
let tagsHTML = '';
if (coord.tags && Object.keys(coord.tags).length > 0) {
const tagElements = Object.entries(coord.tags)
.map(([key, value]) => `<span class="tag">${key}: ${value}</span>`)
.join('');
tagsHTML = `
<div class="history-item tags-container">
<div class="history-item-label">Tags</div>
<div class="tag-list">${tagElements}</div>
</div>
`;
} else {
tagsHTML = `
<div class="history-item tags-container">
<div class="history-item-label">Tags</div>
<div class="history-item-value" style="color: var(--text-muted);">No tags</div>
</div>
`;
}
historyContent.innerHTML = `
<div class="history-item">
<div class="history-item-label">Version</div>
<div class="history-item-value">${coord.version}</div>
</div>
<div class="history-item">
<div class="history-item-label">Timestamp</div>
<div class="history-item-value">${formatTimestamp(coord.timestamp)}</div>
</div>
<div class="history-item">
<div class="history-item-label">Editor</div>
<div class="history-item-value">${coord.user || 'Unknown'}</div>
</div>
${tagsHTML}
`;
}
/**
* Create and initialize slider
*/
function initializeSlider() {
const sliderElement = document.getElementById('slider');
if (slider) {
slider.destroy();
}
const maxVersion = coordinates.length;
slider = noUiSlider.create(sliderElement, {
start: 1,
range: {
'min': 1,
'max': maxVersion,
},
step: 1,
connect: "lower",
pips: {
mode: 'steps',
stepped: true,
density: maxVersion > 20 ? 5 : 2
},
tooltips: {
to: function (value) {
return 'v' + Math.round(value);
}
}
});
// Update polygon on slider change
slider.on('update', function (values, handle) {
const index = parseInt(values[handle]) - 1;
const coord = coordinates[index];
// Update history display
updateHistory(index);
// Remove old polygon
if (currentPolygon) {
map.removeLayer(currentPolygon);
}
// Add new polygon with color
const colorIndex = index % colorPalette.length;
currentPolygon = L.polygon(TimeMachine[coord.version], {
color: colorPalette[colorIndex],
fillColor: colorPalette[colorIndex],
fillOpacity: 0.4,
weight: 3
}).addTo(map);
// Fit map to polygon bounds
try {
map.fitBounds(currentPolygon.getBounds(), { padding: [50, 50] });
} catch (e) {
console.warn('Could not fit bounds:', e);
}
});
}
/**
* Display way data on the map
*/
function displayWayData(wayId) {
// Process coordinates into TimeMachine format
TimeMachine = {};
coordinates.forEach((coord) => {
const geometry = coord.geometry;
const version = coord.version;
const polygonPoints = geometry.map(point => [point.lat, point.lon]);
TimeMachine[version] = polygonPoints;
});
// Show UI elements
emptyState.classList.add('hidden');
wayBadgeContainer.classList.remove('hidden');
mapContainer.classList.remove('hidden');
// Update badge
wayIdDisplay.textContent = wayId;
osmLink.href = `https://www.openstreetmap.org/way/${wayId}`;
// Initialize map
const firstCoord = coordinates[0].geometry[0];
initializeMap(firstCoord);
// Add initial polygon
const colorIndex = 0;
currentPolygon = L.polygon(TimeMachine[coordinates[0].version], {
color: colorPalette[colorIndex],
fillColor: colorPalette[colorIndex],
fillOpacity: 0.4,
weight: 3
}).addTo(map);
// Initialize slider
initializeSlider();
// Initialize history display
updateHistory(0);
}
/**
* Handle form submission
*/
async function handleSubmit(event) {
event.preventDefault();
hideError();
const wayId = wayIdInput.value;
// Validate input
const validation = validateWayId(wayId);
if (!validation.valid) {
showError(validation.error);
return;
}
// Show loading
showLoading();
// Fetch data
const result = await fetchWayHistory(validation.wayId);
hideLoading();
if (!result.success) {
showError(result.error);
return;
}
// Process data
coordinates = processWayData(result.data);
if (coordinates.length === 0) {
showError(
`No way data found for ID ${validation.wayId}. ` +
`This might not be a valid way, or it might be a node or relation instead.`
);
return;
}
// Display data
displayWayData(validation.wayId);
// Update URL without page reload
const url = new URL(window.location);
url.searchParams.set('way', validation.wayId);
window.history.pushState({}, '', url);
}
/**
* Load way from URL parameter on page load
*/
function loadFromURL() {
const urlParams = new URLSearchParams(window.location.search);
const wayId = urlParams.get('way');
if (wayId) {
wayIdInput.value = wayId;
handleSubmit({ preventDefault: () => { } });
}
}
// Event listeners
searchForm.addEventListener('submit', handleSubmit);
// Load from URL on page load
window.addEventListener('DOMContentLoaded', loadFromURL);