-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapanimation.js
90 lines (79 loc) · 2 KB
/
mapanimation.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
const busStops = [
[-71.093729, 42.359244],
[-71.094915, 42.360175],
[-71.0958, 42.360698],
[-71.099558, 42.362953],
[-71.103476, 42.365248],
[-71.106067, 42.366806],
[-71.108717, 42.368355],
[-71.110799, 42.369192],
[-71.113095, 42.370218],
[-71.115476, 42.372085],
[-71.117585, 42.373016],
[-71.118625, 42.374863],
];
mapboxgl.accessToken = 'pk.eyJ1IjoiYm9ib3BvcDc4NyIsImEiOiJja3MwbGNtcGQwbzUzMnVyd3FtaHpiZHQ3In0.rvj4UKXunmwCCHLsVH-2ag';
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-71.0873216701205, 42.354642574314255],
zoom: 12.8,
});
let counter = 0;
let isRunning = false;
let marker = new mapboxgl.Marker({
"color": "#3bc22d"
})
.setLngLat([-71.093729, 42.359244])
.addTo(map);
let interval;
function restart() {
if(isRunning) {
return;
}
counter = 0;
move();
}
function move() {
isRunning = true;
interval = setInterval(() => {
if(counter >= busStops.length) {
isRunning = false;
return;
}
marker.setLngLat(busStops[counter]);
counter++;
}, 1000);
}
let liveMarkers = [];
async function run() {
const locations = await getBusLocations();
console.log("Updated at", new Date());
console.log(locations);
for(let i = 0; i < liveMarkers.length; i++) {
liveMarkers[i].remove();
}
liveMarkers = new Array(locations.length);
for(let i = 0; i < locations.length; i++) {
let location = [];
location.push(locations[i].attributes.longitude, locations[i].attributes.latitude);
let popup = new mapboxgl.Popup()
.setText("")
liveMarkers[i] = new mapboxgl.Marker({
"color": "#c92a02"
})
.setLngLat(location)
.addTo(map);
}
setTimeout(run, 20000);
}
async function getBusLocations() {
const url = 'https://api-v3.mbta.com/vehicles?filter[route]=1&include=trip'
const response = await fetch(url);
const json = await response.json();
return json.data;
}
run();
if (typeof module !== 'undefined') {
module.exports = { move };
}