forked from operte/location-history-visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
847 lines (763 loc) · 29.1 KB
/
index.js
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
(function ($, L, prettySize) {
var SCALAR_E7 = 0.0000001; // Since Google Takeout stores latlngs as integers
var RADIUS = 6371;
var ROUNDING = 0.5;
var PLAY_UPDATE = 1000/60;
var TILES_URL = location.protocol === "file:" ? 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' : 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png';
var map;
var tileLayer;
var points;
var pointsData;
var locations = {};
var locData;
var connections = {};
var lines;
var linesData;
var minTs, maxTs;
var playInterval;
var playPoints = [];
var playTimes = [];
var imagePoints = [];
var imageTimes = [];
var isPlaying = false;
var loopPlay = false;
var playSpeed = localStorage.getItem("playSpeed") || 2000;
var trailLength = localStorage.getItem("trailLength") || 12;
var minSize = localStorage.getItem("minSize") || 10;
var maxSize = localStorage.getItem("maxSize") || 10;
var divider = localStorage.getItem("divider") || 10;
var showPoints = localStorage.getItem("showPoints") === null ? true : localStorage.getItem("showPoints") === "true";
var showLines = localStorage.getItem("showLines") === null ? true : localStorage.getItem("showLines") === "true";
var excludeDriving = localStorage.getItem("excludeDriving") === null ? true : localStorage.getItem("excludeDriving") === "true";
var padding = localStorage.getItem("padding") || 100;
var maxZoom = localStorage.getItem("maxZoom") || 12;
var currentLoc;
var currentMs;
var startMs;
var endMs;
var isNightTime = false;
var urlParams = new URLSearchParams(window.location.search);
$("#playSpeed").val(playSpeed);
$("#trailLength").val(trailLength);
$("#minSize").val(minSize);
$("#maxSize").val(maxSize);
$("#divider").val(divider);
$("#padding").val(padding);
$("#maxZoom").val(maxZoom);
$("#showPoints")[0].checked = showPoints;
$("#showLines")[0].checked = showLines;
$("#excludeDriving")[0].checked = excludeDriving;
// Updates currentStatus field during data loading
function status(message) {
$('#currentStatus').text(message);
}
// If browser does not support 'date' inputs, use
// jquery-ui's datepicker
if ($('[type="date"]').prop('type') != 'date') {
$('[type="date"]').datepicker();
}
// Start at the beginning
stageOne();
function stageOne() {
var file = urlParams.get('file');
if (file) {
$('#intro').addClass('hidden');
$('#working').removeClass('hidden');
fetch(file).then(function(response) {
return response.text().then(function(text) {
loopPlay = true;
stageTwo(new File([text], file.split('/').reverse()[0], {
type: "application/json"
}));
});
});
}
else {
$("#intro").removeClass("hidden");
// Initialize the dropzone
var dropzone = new Dropzone(document.body, {
url: '/',
previewsContainer: document.createElement('div'), // >> /dev/null
clickable: false,
accept: function (file, done) {
stageTwo(file);
dropzone.disable(); // Your job is done, buddy
}
});
// For mobile browsers, allow direct file selection as well
$('#file').change(function () {
stageTwo(this.files[0]);
dropzone.disable();
});
}
$(window).keypress(onKeyPress);
// Initialize the map
map = L.map('map', { zoomControl: false }).setView([0, 0], 2);
tileLayer = L.tileLayer(TILES_URL, {
maxZoom: 18,
minZoom: 2,
zoomSnap: 0.5,
attribution: '© <a href="https://stadiamaps.com/">Stadia Maps</a>, © <a href="https://openmaptiles.org/">OpenMapTiles</a> © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
});
tileLayer.addTo(map);
}
function stageTwo(file) {
var type;
try {
if (/\.kml$/i.test(file.name)) {
type = 'kml';
} else {
type = 'json';
}
} catch (ex) {
status('Something went wrong generating your map. Ensure you\'re uploading a Google Takeout JSON file that contains location data and try again, or create an issue on GitHub if the problem persists. ( error: ' + ex.message + ' )');
return;
}
// First, change tabs
$('body').addClass('working');
$('#intro').addClass('hidden');
$('#working').removeClass('hidden');
var prevLocation;
// Use Oboe to stream Google Takeout data if file is JSON
var os = new oboe();
os.node('locations.*', function (location) {
location.lat = location.latitudeE7 * SCALAR_E7;
location.lon = location.longitudeE7 * SCALAR_E7;
// Handle negative latlngs due to google unsigned/signed integer bug.
if (location.lat > 180) location.lat = location.lat - (2 ** 32) * SCALAR_E7;
if (location.lon > 180) location.lon = location.lon - (2 ** 32) * SCALAR_E7;
location.timestampMs = parseInt(location.timestampMs);
calcRounded(location);
if (prevLocation) {
location.prev = prevLocation;
prevLocation.next = location;
}
prevLocation = location;
return oboe.drop;
}).done(function () {
status('Generating map...');
filterLocations();
collectConnections();
points = L.glify.points({
map,
size: (i, point) => {
var times = locData[point.toString()] ? locData[point.toString()][0].times : 0;
return Math.max(Math.min(times / divider, maxSize), minSize);
},
color: (i, point) => {
// quickfix
if (isPlaying) return L.glify.Points.defaults.color();
if (isPlaying && i === points.settings.data.length-1) {
return {r: 0.66, g: 0, b: isNightTime ? 0.08 : 0, a: 1};
}
return {
r: 0.66,
g: 0,
b: isNightTime ? 0.08 : 0,
a: isPlaying ? 1-(currentMs - playTimes[i]) / (trailLength*60*60*1000) : 1
};
},
click: (e, point) => {
if (!locData[point.toString()]) return;
var location = locData[point.toString()][0];
var dataPoints = locData[point.toString()].length;
//set up a standalone popup (use a popup as a layer)
L.popup()
.setLatLng(point)
.setContent('First time visited on:' + (new Date(parseInt(location.timestampMs))).toString() + '. Accuracy: ' + location.accuracy + '. Times: ' + location.times + ' / ' + dataPoints)
.openOn(map);
},
data: showPoints ? pointsData : []
});
lines = L.glify.lines({
map: map,
latitudeKey: 0,
longitudeKey: 1,
weight: 10,
color: (i, feature) => {
// quickfix
if (isPlaying) return L.glify.Lines.defaults.color();
if (isPlaying && i === lines.settings.data.features.length-1) {
return {r: 0.66, g: 0, b: isNightTime ? 0.08 : 0, a: 1};
}
return {
r: 0.66,
g: 0,
b: isNightTime ? 0.08 : 0,
a: isPlaying ? 1-(currentMs - playTimes[i]) / (trailLength*60*60*1000) : 1
};
},
click: (e, feature) => {
L.popup()
.setLatLng(e.latlng)
.setContent('You clicked on ' + feature.properties.name)
.openOn(map);
},
data: {
type: "FeatureCollection",
features: showLines ? linesData : []
}
});
stageThree( pointsData.length);
});
var fileSize = prettySize(file.size);
status('Preparing to import file ( ' + fileSize + ' )...');
// Now start working!
if (type === 'json') parseJSONFile(file, os);
if (type === 'kml') parseKMLFile(file);
}
function stageThree(numberProcessed) {
// Change tabs
$('body').removeClass('working');
$('#working').addClass('hidden');
//$('#done').removeClass('hidden');
// Update count
$('#numberProcessed').text(numberProcessed.toLocaleString());
//$('#launch').click(function () {
$('body').addClass('map-active');
// $('#done').fadeOut();
//});
initGui();
onPlay();
$("#streetview").on("load", function() {
$("#streetview").css("visibility", "visible");
});
}
function onKeyPress(event) {
switch (event.key) {
case 'p':
togglePlay();
break;
case 'g':
toggleGui();
break;
case 'm':
toggleMap();
break;
}
}
function initGui() {
$('#showMap').change(toggleMap);
$('#showPoints').change(renderPoints);
$('#showLines').change(renderLines);
$('#update').click(onUpdate);
$('#play').click(onPlay);
$('#stop').click(onStop);
$('#minSize').change(function() {
minSize = parseInt($('#minSize').val()) || minSize;
localStorage.setItem("minSize", minSize);
if (!isPlaying) {
renderPoints();
}
});
$('#maxSize').change(function() {
maxSize = parseInt($('#maxSize').val()) || maxSize;
localStorage.setItem("maxSize", maxSize);
if (!isPlaying) {
renderPoints();
}
});
$('#divider').change(function() {
divider = parseInt($('#divider').val()) || divider;
localStorage.setItem("divider", divider);
if (!isPlaying) {
renderPoints();
}
});
$('#trailLength').change(function() {
trailLength = Math.abs(parseInt($("#trailLength").val())) || trailLength;
localStorage.setItem("trailLength", trailLength);
});
$('#padding').change(function() {
padding = Math.abs(parseInt($("#padding").val())) || padding;
localStorage.setItem("padding", padding);
});
$('#maxZoom').change(function() {
maxZoom = Math.abs(parseInt($("#maxZoom").val())) || maxZoom;
localStorage.setItem("maxZoom", maxZoom);
});
$('#playSpeed').change(function() {
playSpeed = (parseInt($("#playSpeed").val()) || playSpeed);
localStorage.setItem("playSpeed", playSpeed);
});
$('#showPoints').change(function() {
showPoints = $("#showPoints").is(":checked");
localStorage.setItem("showPoints", showPoints);
});
$('#showLines').change(function() {
showLines = $("#showLines").is(":checked");
localStorage.setItem("showLines", showLines);
});
$('#excludeDriving').change(function() {
excludeDriving = $("#excludeDriving").is(":checked");
localStorage.setItem("excludeDriving", excludeDriving);
});
}
function toggleGui() {
$("#ui").toggle();
$("#ui").accordion();
}
function togglePlay() {
if (isPlaying) {
onStop();
}
else {
onPlay();
}
}
function toggleMap(event) {
if (!event) $("#showMap")[0].checked = !$("#showMap")[0].checked;
$('.leaflet-tile-pane').css("visibility", $('#showMap').is(':checked') ? 'visible' : 'hidden');
}
function renderPoints(data) {
points.settings.data = showPoints ? data || pointsData : [];
points.render();
}
function renderLines(data) {
lines.settings.data.features = showLines ? data || linesData : [];
lines.render();
}
function onUpdate() {
if (isPlaying) {
onStop();
}
$('body').addClass('working');
var rounding = parseFloat($('#rounding').val());
if (!isNaN(rounding) && rounding !== ROUNDING) {
ROUNDING = rounding;
updateLocations();
}
filterLocations();
renderPoints();
collectConnections();
renderLines();
$('body').removeClass('working');
}
function onPlay() {
isPlaying = true;
$("#play").hide();
$("#stop").show();
$("#seekbar").on('click', onSeek);
currentLoc = getFirstLoc();
startMs = currentLoc.timestampMs;
endMs = locData[pointsData[pointsData.length-1].toString()][0].timestampMs;
for (var i=0; i<locData[pointsData[pointsData.length-1].toString()].length; i++) {
if (locData[pointsData[pointsData.length-1].toString()][0].timestampMs > endMs) {
endMs = locData[pointsData[pointsData.length-1].toString()][0].timestampMs;
}
}
playPoints = [];
playTimes = [];
playFrame(0);
}
function playFrame(time) {
var nextLoc = getNextLoc(currentLoc);
renderPoint(currentLoc, nextLoc, time);
if (!nextLoc) {
if (loopPlay) {
playInterval = setTimeout(function() {
currentLoc = getFirstLoc();
playPoints = [];
playTimes = [];
playFrame(0);
}, PLAY_UPDATE);
}
else {
onStop();
}
return;
}
var ms = Math.max(0, Math.min(PLAY_UPDATE, (nextLoc.timestampMs - currentLoc.timestampMs) / (1000*60*60*24) * Math.max(1, playSpeed)));
playInterval = setTimeout(function() {
if ((time + ms) >= (nextLoc.timestampMs - currentLoc.timestampMs) / (1000*60*60*24) * Math.max(1, playSpeed)) {
currentLoc = nextLoc;
playFrame(0);
}
else {
playFrame(time + ms);
}
}, ms);
}
function renderPoint(currentLoc, nextLoc, time) {
var diff = nextLoc ? (nextLoc.timestampMs - currentLoc.timestampMs) : 0;
var progress = time / (diff / (1000*60*60*24) * Math.max(1, playSpeed));
currentMs = currentLoc.timestampMs + diff * progress;
var between = lerpLatLon(currentLoc.point, nextLoc ? nextLoc.point : null, progress);
var imagesChanged = false;
if (!imagePoints.length || imagePoints[imagePoints.length-1][0][0] !== currentLoc.point[0] ||
imagePoints[imagePoints.length-1][0][1] !== currentLoc.point[1]) {
imagePoints.push([currentLoc.point, 0]);
imageTimes.push(currentMs);
imagesChanged = true;
}
while (imageTimes.length > 1 && imageTimes[0] < currentMs - trailLength*60*60*1000) {
imagePoints.shift();
imageTimes.shift();
imagesChanged = true;
}
if (!playPoints.length || between[0] !== playPoints[playPoints.length-1][0] || between[1] !== playPoints[playPoints.length-1][1]) {
playPoints.push(between);
playTimes.push(currentMs);
}
while (playTimes.length > 1 && playTimes[0] < currentMs - trailLength*60*60*1000) {
playPoints.shift();
playTimes.shift();
}
var currentTZ = tzlookup(playPoints[playPoints.length-1][0], playPoints[playPoints.length-1][1]);
if (imagesChanged) {
updateImage(imagePoints);
}
updateClock(currentMs, currentTZ);
updateTimeline(currentMs);
renderPoints(playPoints);
if (showLines) {
var playLines = [{
type: "Feature",
properties: {
scalerank: 2,
name: "todo: should be times",
name_alt: null,
featureclass: "Connection"
},
geometry: {
type: "LineString",
coordinates: playPoints
}
}];
renderLines(playLines);
}
map.fitBounds(playPoints, {padding: [padding, padding], maxZoom: maxZoom});
}
function updateImage(points) {
//$("#streetview").css("visibility", "hidden");
var point = points[points.length-1];
for (var i=points.length-1; i>=0; i--) {
if (points[i][1] < point[1]) {
point = points[i];
}
if (point[1] === 0) {
break;
}
}
point[1]++;
var url = "https://maps.googleapis.com/maps/api/streetview?size=180x180&location="+point[0].join(",")+"&key=AIzaSyA8quqZg1EQz0yAXVe_THhg6OJe4VnTK7M&return_error_codes=true";
fetch(url).then(function(response) {
if (parseInt(response.headers.get("Content-Length")) > 4000) {
$("#streetview").prop("src", url);
}
});
}
function updateClock(ms, tz) {
var date = new Date(ms);
var tzDate = new Date(date.toLocaleString("en-US", {timeZone: tz}));
clock(tzDate);
$("#currentDate").text(tzDate.toLocaleString((navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en'));
$("#timezone").text(tz);
isNightTime = tzDate.getHours() > 20 || tzDate.getHours() < 6;
$(".visualizer").toggleClass("dark-mode", isNightTime);
}
function updateTimeline(ms) {
$("#position").css("left", (ms - startMs) / (endMs - startMs) * 100 + '%');
}
function getFirstLoc() {
return locData[pointsData[0].toString()][0];
}
function getNextLoc(currentLoc) {
var nextLoc = currentLoc.next;
while (nextLoc && !nextLoc.point) {
nextLoc = nextLoc.next;
}
return nextLoc;
}
function getPrevLoc(currentLoc) {
var prevLoc = currentLoc.prev;
while (prevLoc && !prevLoc.point) {
prevLoc = prevLoc.prev;
}
return prevLoc;
}
function onStop() {
isPlaying = false;
$("#seekbar").off('click', onSeek);
$("#stop").hide();
$("#play").show();
clearTimeout(playInterval);
$(".visualizer").removeClass("dark-mode");
onUpdate();
}
function onSeek(event) {
if (!isPlaying) return;
var offset = $('#seekbar').offset();
var x = event.pageX - offset.left;
var perc = x / $('#seekbar').width();
var ms = (endMs - startMs) * perc + startMs;
clearTimeout(playInterval);
if (ms > currentMs) {
while (currentLoc && ms > currentLoc.timestampMs) {
currentLoc = getNextLoc(currentLoc);
}
}
else {
while (currentLoc && ms < currentLoc.timestampMs) {
currentLoc = getPrevLoc(currentLoc);
}
}
if (!currentLoc) {
currentLoc = getFirstLoc();
}
playPoints = [];
playTimes = [];
playFrame(0);
}
function calcRounded(location) {
location.cartesian = calcCartesianCoord(location.lat, location.lon, RADIUS / ROUNDING);
var roundedCartesian = location.cartesian.map(function (x) {
return Math.round(x);
});
var roundedLatLon = calcLatLon(roundedCartesian, RADIUS / ROUNDING);
location.roundedLatLon = roundedLatLon;
if (!locations[roundedLatLon.toString()]) {
locations[roundedLatLon.toString()] = [location];
} else {
locations[roundedLatLon.toString()].push(location);
}
}
function calcTimes(locs) {
var times = 0;
for (var i=1; i<locs.length; i++) {
if (locs[i].timestampMs > (locs[(i-1)].timestampMs + 1000*60*60*4)) {
times++;
}
}
return times;
}
function isDriving(loc) {
if (loc.activity) {
for (var i=0; i<loc.activity[0].activity.length; i++) {
if (loc.activity[0].activity[i].type === "IN_VEHICLE" && loc.activity[0].activity[i].confidence >= 10) {
return true;
}
}
}
return false;
}
function updateLocations() {
var locations2 = locations;
locations = {};
for (var p2 in locations2) {
var locs2 = locations2[p2];
for (var i = 0; i < locs2.length; i++) {
calcRounded(locs2[i]);
}
}
}
function filterLocations() {
locData = {};
pointsData = [];
var fromDate = new Date($("#fromDate").val()).getTime();
var toDate = new Date($("#toDate").val()).getTime();
var maxAccuracy = parseInt($("#maxAccuracy").val());
var minData = parseInt($('#minData').val()) || 1;
var minTimes = parseInt($('#minTimes').val()) || 1;
for (var p in locations) {
var locs = locations[p].filter(function (loc) {
// quickfix
delete loc.point;
return (!maxAccuracy || loc.accuracy <= maxAccuracy) &&
(!fromDate || loc.timestampMs >= fromDate) &&
(!toDate || loc.timestampMs <= toDate) &&
(!excludeDriving || !isDriving(loc));
});
var times = calcTimes(locs);
if (locs.length < minData || times < minTimes) {
continue;
}
var point;
if (locs.length === 1) {
point = [locs[0].lat, locs[0].lon];
} else {
point = avarageLatLon(locs);
}
locs.map(function(loc) {
loc.point = point;
loc.times = times;
if (!minTs || loc.timestampMs < minTs) {
minTs = loc.timestampMs;
}
if (!maxTs || loc.timestampMs > maxTs) {
maxTs = loc.timestampMs;
}
});
locData[point.toString()] = locs;
pointsData.push(point);
}
$("#totalPoints").text(pointsData.length);
}
function collectConnections() {
connections = {};
linesData = [];
for (var p in locData) {
connections[p] = [];
for (var i=0; i<locData[p].length; i++) {
var prev = getPrevLoc(locData[p][i]);
if (prev && prev.point && connections[p].indexOf(prev.point) === -1) {
connections[p].push(prev.point);
var line = {
type: "Feature",
properties: {
scalerank: 2,
name: "todo: should be times",
name_alt: null,
featureclass: "Connection"
},
geometry: {
type: "LineString",
coordinates: [locData[p][0].point.slice(), prev.point.slice()]
}
};
linesData.push(line);
}
}
}
}
function avarageLatLon(locs) {
var sum = [0, 0, 0];
for (var i = 0; i < locs.length; i++) {
var loc = locs[i];
sum[0] += loc.cartesian[0];
sum[1] += loc.cartesian[1];
sum[2] += loc.cartesian[2];
}
var avg = [sum[0] / locs.length, sum[1] / locs.length, sum[2] / locs.length];
return calcLatLon(avg, RADIUS / ROUNDING);
}
function calcCartesianCoord(lat, lon, radius) {
var latRad = lat * (Math.PI / 180);
var lonRad = lon * (Math.PI / 180);
var x = radius * Math.cos(latRad) * Math.cos(lonRad);
var y = radius * Math.cos(latRad) * Math.sin(lonRad);
var z = radius * Math.sin(latRad);
return [x, y, z];
}
function lerpLatLon(point1, point2, fraction) {
if (fraction <= 0) return point1;
if (fraction >= 1) return point2;
if (point1[0] === point2[0] && point1[1] === point2[1]) {
return point1;
}
var lat1Rad = point1[0] * (Math.PI / 180);
var lon1Rad = point1[1] * (Math.PI / 180);
var lat2Rad = point2[0] * (Math.PI / 180);
var lon2Rad = point2[1] * (Math.PI / 180);
// distance between points
const deltaLat = lat2Rad - lat1Rad;
const deltaLon = lon2Rad - lon1Rad;
const a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
const g = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const A = Math.sin((1-fraction)*g) / Math.sin(g);
const B = Math.sin(fraction*g) / Math.sin(g);
const x = A * Math.cos(lat1Rad) * Math.cos(lon1Rad) + B * Math.cos(lat2Rad) * Math.cos(lon2Rad);
const y = A * Math.cos(lat1Rad) * Math.sin(lon1Rad) + B * Math.cos(lat2Rad) * Math.sin(lon2Rad);
const z = A * Math.sin(lat1Rad) + B * Math.sin(lat2Rad);
const lat3Rad = Math.atan2(z, Math.sqrt(x*x + y*y));
const lon3Rad = Math.atan2(y, x);
const lat = lat3Rad * 180 / Math.PI;
const lon = lon3Rad * 180 / Math.PI;
return [lat, lon];
}
function calcLatLon(coord, radius) {
var x = coord[0];
var y = coord[1];
var z = coord[2];
var lat = Math.asin(z / radius) * (180 / Math.PI);
var lon = Math.atan2(y, x) * (180 / Math.PI);
return [lat, lon];
}
/*
Break file into chunks and emit 'data' to oboe instance
*/
function parseJSONFile(file, oboeInstance) {
var fileSize = file.size;
var prettyFileSize = prettySize(fileSize);
var chunkSize = 512 * 1024; // bytes
var offset = 0;
var chunkReaderBlock = null;
var readEventHandler = function (evt) {
if (evt.target.error == null) {
offset += evt.target.result.length;
var chunk = evt.target.result;
var percentLoaded = (100 * offset / fileSize).toFixed(0);
status(percentLoaded + '% of ' + prettyFileSize + ' loaded...');
oboeInstance.emit('data', chunk); // callback for handling read chunk
} else {
return;
}
if (offset >= fileSize) {
oboeInstance.emit('done');
return;
}
// of to the next chunk
chunkReaderBlock(offset, chunkSize, file);
}
chunkReaderBlock = function (_offset, length, _file) {
var r = new FileReader();
var blob = _file.slice(_offset, length + _offset);
r.onload = readEventHandler;
r.readAsText(blob);
}
// now let's start the read with the first block
chunkReaderBlock(offset, chunkSize, file);
}
/*
Default behavior for file upload (no chunking)
*/
function parseKMLFile(file) {
var fileSize = prettySize(file.size);
var reader = new FileReader();
reader.onprogress = function (e) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
status(percentLoaded + '% of ' + fileSize + ' loaded...');
};
reader.onload = function (e) {
var latlngs;
status('Generating map...');
latlngs = getLocationDataFromKml(e.target.result);
heat._latlngs = latlngs;
heat.redraw();
stageThree(latlngs.length);
}
reader.onerror = function () {
status('Something went wrong reading your JSON file. Ensure you\'re uploading a "direct-from-Google" JSON file and try again, or create an issue on GitHub if the problem persists. ( error: ' + reader.error + ' )');
}
reader.readAsText(file);
}
function getLocationDataFromKml(data) {
var KML_DATA_REGEXP = /<when>( .*? )<\/when>\s*<gx:coord>( \S* )\s( \S* )\s( \S* )<\/gx:coord>/g,
locations = [],
match = KML_DATA_REGEXP.exec(data);
// match
// [ 1 ] ISO 8601 timestamp
// [ 2 ] longitude
// [ 3 ] latitude
// [ 4 ] altitude ( not currently provided by Location History )
while (match !== null) {
locations.push([Number(match[3]), Number(match[2])]);
match = KML_DATA_REGEXP.exec(data);
}
return locations;
}
}(jQuery, L, prettySize));
const secondSelector = document.querySelector('.seconds');
const minuteSelector = document.querySelector('.minutes');
const hourSelector = document.querySelector('.hours');
function clock(now) {
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours();
const getSecondsDegrees = ((seconds / 60) * 360);
const getMinutesDegrees = ((minutes / 60) * 360);
const getHoursDegrees = ((hours / 12) * 360);
secondSelector.style.transform = `rotate(${getSecondsDegrees}deg)`;
minuteSelector.style.transform = `rotate(${getMinutesDegrees}deg)`;
hourSelector.style.transform = `rotate(${getHoursDegrees}deg)`;
}