-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_polyline_map.html
More file actions
733 lines (610 loc) · 28 KB
/
Copy pathsqlite_polyline_map.html
File metadata and controls
733 lines (610 loc) · 28 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQLite Polyline Map Viewer</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css" />
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background: #f5f5f5;
}
.container {
display: flex;
height: 100vh;
}
.sidebar {
width: 320px;
background: white;
padding: 20px;
box-shadow: 2px 0 10px rgba(0,0,0,0.1);
overflow-y: auto;
}
.map-container {
flex: 1;
position: relative;
}
#map {
height: 100%;
width: 100%;
}
.control-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #333;
}
input[type="date"] {
width: 100%;
padding: 8px;
border: 2px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
input[type="date"]:focus {
border-color: #4CAF50;
outline: none;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
width: 100%;
margin-top: 10px;
transition: transform 0.2s, box-shadow 0.2s;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
button:active {
transform: translateY(0);
}
.stats {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 15px;
border-radius: 8px;
margin-top: 20px;
}
.stats h3 {
margin: 0 0 10px 0;
font-size: 16px;
}
.stats p {
margin: 5px 0;
font-size: 14px;
}
.file-upload {
margin-bottom: 20px;
padding: 15px;
border: 2px dashed #ddd;
border-radius: 8px;
text-align: center;
background: #fafafa;
}
.file-upload input[type="file"] {
margin-top: 10px;
}
.legend {
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
position: absolute;
top: 10px;
right: 10px;
z-index: 1000;
min-width: 150px;
}
.legend-item {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.date-range-container {
margin-bottom: 20px;
padding: 15px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
display: none;
}
.date-range-slider {
position: relative;
height: 40px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 20px;
margin: 15px 0;
}
.date-range-track {
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 4px;
background: rgba(255,255,255,0.3);
transform: translateY(-50%);
border-radius: 2px;
}
.date-range-fill {
position: absolute;
top: 50%;
height: 4px;
background: white;
transform: translateY(-50%);
border-radius: 2px;
transition: all 0.2s ease;
}
.date-range-handle {
position: absolute;
top: 50%;
width: 20px;
height: 20px;
background: white;
border: 3px solid #667eea;
border-radius: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
transition: all 0.2s ease;
}
.date-range-handle:hover {
transform: translate(-50%, -50%) scale(1.2);
box-shadow: 0 3px 8px rgba(0,0,0,0.3);
}
.date-range-handle.active {
border-color: #764ba2;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.3);
}
.date-labels {
display: flex;
justify-content: space-between;
font-size: 12px;
color: #666;
margin-top: 10px;
}
.date-selection {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
padding: 10px;
background: #f8f9fa;
border-radius: 6px;
}
.date-value {
font-weight: bold;
color: #333;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<div class="sidebar">
<h2 style="margin-top: 0; color: #333;">GPS Track Viewer</h2>
<div class="file-upload">
<h4 style="margin-top: 0;">Upload SQLite File</h4>
<p style="font-size: 12px; color: #666;">Select your SQLite file with GPS data</p>
<input type="file" id="sqliteFile" accept=".sqlite,.sqlite3,.db" />
</div>
<div class="control-group">
<label for="tableName">Table Name:</label>
<input type="text" id="tableName" value="locations" placeholder="Enter table name"
style="width: 100%; padding: 8px; border: 2px solid #ddd; border-radius: 4px; font-size: 14px;" />
<p style="font-size: 12px; color: #666; margin-top: 5px;">Default: locations</p>
</div>
<div class="date-range-container" id="dateRangeContainer">
<h4 style="margin: 0 0 15px 0; color: #333;">Date Range Selection</h4>
<div class="date-range-slider" id="dateRangeSlider">
<div class="date-range-track"></div>
<div class="date-range-fill" id="dateRangeFill"></div>
<div class="date-range-handle" id="startHandle" style="left: 0%;"></div>
<div class="date-range-handle" id="endHandle" style="left: 100%;"></div>
</div>
<div class="date-labels" id="dateLabels">
<span id="minDateLabel">-</span>
<span id="maxDateLabel">-</span>
</div>
<div class="date-selection">
<div>
<small>Start:</small>
<div class="date-value" id="selectedStartDate">-</div>
</div>
<div>
<small>End:</small>
<div class="date-value" id="selectedEndDate">-</div>
</div>
</div>
</div>
<button onclick="updateMap()">Update Map</button>
<button onclick="reloadTable()" style="background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%); margin-top: 5px;">Reload Table</button>
<button onclick="loadSampleData()" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">Load Sample Data</button>
<div class="stats" id="stats" style="display: none;">
<h3>Track Statistics</h3>
<p id="pointCount">Points: 0</p>
<p id="dateRange">Date Range: -</p>
<p id="trackCount">Tracks: 0</p>
</div>
</div>
<div class="map-container">
<div id="map"></div>
<div class="legend" id="legend" style="display: none;">
<h4 style="margin: 0 0 10px 0;">Date Legend</h4>
<div id="legendContent"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.min.js"></script>
<script>
let map;
let trackData = [];
let polylineGroup = L.layerGroup();
let db = null;
let dateRange = { min: null, max: null };
let selectedRange = { start: 0, end: 100 }; // percentages
let isDragging = false;
let activeHandle = null;
// Initialize date range slider
function initDateRangeSlider() {
const slider = document.getElementById('dateRangeSlider');
const startHandle = document.getElementById('startHandle');
const endHandle = document.getElementById('endHandle');
function handleMouseDown(e, handle) {
e.preventDefault();
isDragging = true;
activeHandle = handle;
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
handle.classList.add('active');
}
function handleMouseMove(e) {
if (!isDragging || !activeHandle) return;
const rect = slider.getBoundingClientRect();
const percentage = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
if (activeHandle === startHandle) {
selectedRange.start = Math.min(percentage, selectedRange.end - 1);
} else {
selectedRange.end = Math.max(percentage, selectedRange.start + 1);
}
updateSliderUI();
updateSelectedDates();
}
function handleMouseUp() {
isDragging = false;
if (activeHandle) {
activeHandle.classList.remove('active');
activeHandle = null;
}
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
updateMap();
}
startHandle.addEventListener('mousedown', (e) => handleMouseDown(e, startHandle));
endHandle.addEventListener('mousedown', (e) => handleMouseDown(e, endHandle));
// Touch events for mobile
startHandle.addEventListener('touchstart', (e) => handleMouseDown(e.touches[0], startHandle));
endHandle.addEventListener('touchstart', (e) => handleMouseDown(e.touches[0], endHandle));
slider.addEventListener('touchmove', (e) => {
if (isDragging) {
e.preventDefault();
handleMouseMove(e.touches[0]);
}
});
slider.addEventListener('touchend', handleMouseUp);
}
// Update slider visual elements
function updateSliderUI() {
const startHandle = document.getElementById('startHandle');
const endHandle = document.getElementById('endHandle');
const fill = document.getElementById('dateRangeFill');
startHandle.style.left = selectedRange.start + '%';
endHandle.style.left = selectedRange.end + '%';
fill.style.left = selectedRange.start + '%';
fill.style.width = (selectedRange.end - selectedRange.start) + '%';
}
// Update selected date display
function updateSelectedDates() {
if (!dateRange.min || !dateRange.max) return;
const totalDays = (dateRange.max - dateRange.min) / (1000 * 60 * 60 * 24);
const startDays = (selectedRange.start / 100) * totalDays;
const endDays = (selectedRange.end / 100) * totalDays;
const startDate = new Date(dateRange.min.getTime() + startDays * 24 * 60 * 60 * 1000);
const endDate = new Date(dateRange.min.getTime() + endDays * 24 * 60 * 60 * 1000);
document.getElementById('selectedStartDate').textContent = startDate.toISOString().split('T')[0];
document.getElementById('selectedEndDate').textContent = endDate.toISOString().split('T')[0];
}
// Setup date range slider with data
function setupDateRangeSlider(minDate, maxDate) {
dateRange.min = minDate;
dateRange.max = maxDate;
// Update labels
document.getElementById('minDateLabel').textContent = minDate.toISOString().split('T')[0];
document.getElementById('maxDateLabel').textContent = maxDate.toISOString().split('T')[0];
// Reset to full range
selectedRange = { start: 0, end: 100 };
updateSliderUI();
updateSelectedDates();
// Show the date range container
document.getElementById('dateRangeContainer').style.display = 'block';
}
// Get selected date range
function getSelectedDateRange() {
if (!dateRange.min || !dateRange.max) return null;
const totalDays = (dateRange.max - dateRange.min) / (1000 * 60 * 60 * 24);
const startDays = (selectedRange.start / 100) * totalDays;
const endDays = (selectedRange.end / 100) * totalDays;
const startDate = new Date(dateRange.min.getTime() + startDays * 24 * 60 * 60 * 1000);
const endDate = new Date(dateRange.min.getTime() + endDays * 24 * 60 * 60 * 1000);
return {
start: startDate.toISOString().split('T')[0],
end: endDate.toISOString().split('T')[0]
};
}
function initMap() {
map = L.map('map').setView([45.5017, -73.5673], 10); // Montreal coordinates
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
polylineGroup.addTo(map);
}
// Generate sample data for demonstration
function generateSampleData() {
const sampleData = [];
const startDate = new Date('2024-01-01');
const endDate = new Date('2024-01-10');
// Montreal area coordinates
const baseLat = 45.5017;
const baseLng = -73.5673;
for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
const pointsPerDay = 50 + Math.floor(Math.random() * 100);
for (let i = 0; i < pointsPerDay; i++) {
const timestamp = new Date(d);
timestamp.setHours(Math.floor(Math.random() * 24));
timestamp.setMinutes(Math.floor(Math.random() * 60));
// Create a meandering path
const offset = i * 0.001;
const randomOffset = (Math.random() - 0.5) * 0.01;
sampleData.push({
timestamp: timestamp.toISOString().split('T')[0],
latitude: baseLat + offset + randomOffset,
longitude: baseLng + offset * 0.5 + randomOffset
});
}
}
return sampleData.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
}
// Load sample data
function loadSampleData() {
trackData = generateSampleData();
// Set up date range slider
const dates = trackData.map(d => new Date(d.timestamp));
const minDate = new Date(Math.min(...dates));
const maxDate = new Date(Math.max(...dates));
setupDateRangeSlider(minDate, maxDate);
updateMap();
}
// Load SQLite file
async function loadSQLiteFile(file) {
try {
const arrayBuffer = await file.arrayBuffer();
const SQL = await initSqlJs({
locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
});
db = new SQL.Database(new Uint8Array(arrayBuffer));
// Get list of tables
const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
if (tables.length === 0) {
alert('No tables found in SQLite file');
return;
}
const tableNames = tables[0].values.map(row => row[0]);
console.log('Available tables:', tableNames);
// Try to guess the best table name
let guessedTableName = 'locations'; // Default
// Look for common GPS table names
const gpsTableNames = ['locations', 'location', 'gps', 'tracks', 'track', 'points', 'coordinates', 'coords'];
for (const name of gpsTableNames) {
if (tableNames.find(t => t.toLowerCase() === name.toLowerCase())) {
guessedTableName = tableNames.find(t => t.toLowerCase() === name.toLowerCase());
break;
}
}
// If no GPS-related table found, use the first table
if (!tableNames.find(t => t.toLowerCase() === guessedTableName.toLowerCase()) && tableNames.length > 0) {
guessedTableName = tableNames[0];
}
// Update the UI with the guessed table name
document.getElementById('tableName').value = guessedTableName;
// Load data from the guessed table
loadDataFromTable(guessedTableName);
} catch (error) {
console.error('Error loading SQLite file:', error);
alert('Error loading SQLite file. Please check the file format.');
}
}
// Load data from specified table
function loadDataFromTable(tableName) {
if (!db) {
alert('No SQLite file loaded');
return;
}
try {
// Query the data - adjust column names as needed
const result = db.exec(`SELECT * FROM "${tableName}" LIMIT 1000`);
if (result.length === 0) {
alert(`No data found in table: ${tableName}`);
return;
}
const columns = result[0].columns;
const rows = result[0].values;
console.log('Table columns:', columns);
console.log('Sample row:', rows[0]);
// Map the data (adjust column indices based on your SQLite structure)
trackData = rows.map(row => {
const record = {};
columns.forEach((col, index) => {
record[col.toLowerCase()] = row[index];
});
// Try to find timestamp, latitude, longitude columns
const timestamp = record.timestamp || record.date || record.time || record.datetime || record.created_at || record.recorded_at;
const latitude = record.latitude || record.lat || record.y;
const longitude = record.longitude || record.lng || record.lon || record.x;
// Handle timestamp - could be in seconds or milliseconds
let processedTimestamp = '2024-01-01';
if (timestamp) {
let timestampMs;
if (typeof timestamp === 'number') {
// If timestamp is a number, check if it's in seconds or milliseconds
// Timestamps in seconds are typically 10 digits, in milliseconds are 13 digits
timestampMs = timestamp.toString().length <= 10 ? timestamp * 1000 : timestamp;
} else {
// If it's a string, try to parse it directly
timestampMs = new Date(timestamp).getTime();
}
if (!isNaN(timestampMs)) {
processedTimestamp = new Date(timestampMs).toISOString().split('T')[0];
}
}
return {
timestamp: processedTimestamp,
latitude: parseFloat(latitude) || 0,
longitude: parseFloat(longitude) || 0
};
}).filter(record => record.latitude !== 0 && record.longitude !== 0);
if (trackData.length === 0) {
alert(`No valid GPS coordinates found in table: ${tableName}. Please check the table structure and column names.`);
return;
}
console.log(`Loaded ${trackData.length} GPS points from table: ${tableName}`);
// Set up date range slider
const dates = trackData.map(d => new Date(d.timestamp));
const minDate = new Date(Math.min(...dates));
const maxDate = new Date(Math.max(...dates));
setupDateRangeSlider(minDate, maxDate);
updateMap();
} catch (error) {
console.error('Error loading data from table:', error);
alert(`Error loading data from table: ${tableName}. Please check the table name and structure.`);
}
}
// Generate color for date
function getColorForDate(dateStr, allDates) {
const date = new Date(dateStr);
const minDate = Math.min(...allDates.map(d => new Date(d)));
const maxDate = Math.max(...allDates.map(d => new Date(d)));
const ratio = (date - minDate) / (maxDate - minDate);
const hue = ratio * 300; // 0 to 300 degrees (red to purple)
return `hsl(${hue}, 70%, 50%)`;
}
// Update map with filtered data
function updateMap() {
const dateSelection = getSelectedDateRange();
if (!dateSelection || trackData.length === 0) {
return;
}
const startDate = dateSelection.start;
const endDate = dateSelection.end;
// Clear existing polylines
polylineGroup.clearLayers();
// Filter data by date range
const filteredData = trackData.filter(point => {
return point.timestamp >= startDate && point.timestamp <= endDate;
});
if (filteredData.length === 0) {
document.getElementById('stats').style.display = 'none';
document.getElementById('legend').style.display = 'none';
return;
}
// Group by date
const dateGroups = {};
filteredData.forEach(point => {
if (!dateGroups[point.timestamp]) {
dateGroups[point.timestamp] = [];
}
dateGroups[point.timestamp].push([point.latitude, point.longitude]);
});
// Get all unique dates for color generation
const allDates = Object.keys(dateGroups).sort();
// Create polylines for each date
const legendContent = document.getElementById('legendContent');
legendContent.innerHTML = '';
let totalPoints = 0;
Object.keys(dateGroups).forEach(date => {
const points = dateGroups[date];
if (points.length > 1) {
const color = getColorForDate(date, allDates);
const polyline = L.polyline(points, {
color: color,
weight: 3,
opacity: 0.8
}).bindPopup(`Date: ${date}<br>Points: ${points.length}`);
polylineGroup.addLayer(polyline);
totalPoints += points.length;
// Add to legend
const legendItem = document.createElement('div');
legendItem.className = 'legend-item';
legendItem.innerHTML = `
<div class="legend-color" style="background-color: ${color};"></div>
<span style="font-size: 12px;">${date}</span>
`;
legendContent.appendChild(legendItem);
}
});
// Fit map to show all tracks
if (polylineGroup.getLayers().length > 0) {
const group = L.featureGroup(polylineGroup.getLayers());
map.fitBounds(group.getBounds(), { padding: [20, 20] });
}
// Update statistics
document.getElementById('pointCount').textContent = `Points: ${totalPoints}`;
document.getElementById('dateRange').textContent = `Date Range: ${startDate} to ${endDate}`;
document.getElementById('trackCount').textContent = `Tracks: ${Object.keys(dateGroups).length}`;
document.getElementById('stats').style.display = 'block';
document.getElementById('legend').style.display = allDates.length > 1 ? 'block' : 'none';
}
// Reload data from the specified table
function reloadTable() {
const tableName = document.getElementById('tableName').value.trim();
if (!tableName) {
alert('Please enter a table name');
return;
}
if (!db) {
alert('No SQLite file loaded. Please upload a file first.');
return;
}
loadDataFromTable(tableName);
}
// File upload handler
document.getElementById('sqliteFile').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
loadSQLiteFile(file);
}
});
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initMap();
// Set default dates
const today = new Date();
const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
document.getElementById('startDate').value = weekAgo.toISOString().split('T')[0];
document.getElementById('endDate').value = today.toISOString().split('T')[0];
});
</script>
</body>
</html>