-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.js
330 lines (294 loc) · 9.72 KB
/
map.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
/* global google */
// const intersectionObserver = new IntersectionObserver((entries) => {
// for (const entry of entries) {
// if (entry.isIntersecting) {
// entry.target.classList.add("drop");
// intersectionObserver.unobserve(entry.target);
// }
// }
// });
// Initialize the map
window.addEventListener('load', initialize)
async function initialize() {
// Request needed libraries.
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
// Create the map
window.map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: new google.maps.LatLng(37.76173100956567, -122.4386811010743),
disableDefaultUI: true,
zoomControl: true,
mapId: 'c46bf4bc0e87c92b'
});
// Create the datastore
window.events = new Events();
// Bind infoWindow.close() shortcuts
window.addEventListener('keyup', event => {
switch (event.keyCode) {
case 27: // esc
Events.infoWindow().close();
break;
}
});
google.maps.event.addListener(window.map, 'click', function(event) {
Events.infoWindow().close();
});
console.log('Loading Events...');
window.events.load()
.then(events => {
events.forEach(event => {
if (!event.title) return; // skip empty events just in case
if (!event.geometry) console.error('Event Geometry Missing', { event });
event.marker = new google.maps.marker.AdvancedMarkerElement({
map: window.map,
position: event.geometry,
title: event.title,
});
event.marker.addListener('click', function () {
Events.infoWindow(event).open(window.map, event.marker);
});
// Add drop animation
// const content = event.marker.content
// content.style.opacity = "0";
// content.addEventListener("animationend", (event) => {
// content.classList.remove("drop");
// content.style.opacity = "1";
// });
// const time = 2 + Math.random(); // 2s delay for easy to see the animation
// content.style.setProperty("--delay-time", time + "s");
// intersectionObserver.observe(content);
});
// Apply URL filters
let filters = {};
if (document.location.search) {
document.location.search.substr(1).split('&').forEach(param => {
param = param.split('=');
filters[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
});
}
// Default to today's date
if (!filters.date) {
let date = new Date();
var mm = date.getMonth() + 1;
var dd = date.getDate();
filters.date = `${date.getFullYear()}-${(mm>9 ? '' : '0') + mm}-${(dd>9 ? '' : '0') + dd}`;
}
window.filter(filters);
});
}
let options = {};
/**
* Callback for datepicker, filters all visible events to specified date and category
* @param {object} filters
* @param {string} [filters.date]
* @param {string} [filters.category]
*/
window.filter = function (filters = {}) {
Object.assign(options, filters);
let date;
if (options.date) {
date = options.date.replace(/-/gi, '/');
date = new Date(date);
}
let categories = [];
if (options.category) {
categories = options.category.split(',')
}
// Filter events
let count = window.events.get().filter(event => {
if (!event.title) return; // skip empty events
event.visible = true;
// check date
if (date) {
let eventDate = new Date(event.date);
if (date.getFullYear() !== eventDate.getFullYear() ||
date.getMonth() !== eventDate.getMonth() ||
date.getDate() !== eventDate.getDate()
)
event.visible = false;
}
// check category
if (categories.length && !event.categories.some(category => categories.includes(category))) {
event.visible = false;
}
// if (event.visible) {
// event.marker.content.classList.add('drop')
// } else {
// event.marker.content.style.opacity = '0';
// }
event.marker.content.style.display = event.visible ? 'block' : 'none';
return event.visible;
}).length;
// Apply filters to DOM and URL
let query = [];
for (let option in options) {
let element = document.getElementById(option);
if (element) {
if (element.type === 'select-multiple') {
const selected = options[option].split(',');
for (const option of element.options) {
option.selected = selected.includes(option.value)
}
query.push(encodeURIComponent(option) + '=' + categories.map(category => encodeURIComponent(category)).join(','));
} else {
element.value = options[option];
query.push(encodeURIComponent(option) + '=' + encodeURIComponent(options[option]));
}
}
}
window.history.replaceState({}, '', '?' + query.join('&'));
document.getElementById('count').innerText = count;
};
/**
* Utility class for managing event data
*/
class Events {
/**
* Generates and returns a google maps info window
*
* @param {object} [event] - If passed, sets the content
* @returns {google.maps.InfoWindow}
*/
static infoWindow(event) {
if (!this.cachedInfoWindow)
this.cachedInfoWindow = new google.maps.InfoWindow({});
if (event) {
const time = event.time.split(' to ')
const start = new Date(`${event.date_text} ${time[0]}`)
const startDate = start.toLocaleDateString('sv-SE') // outputs yyyy-mm-dd
let endToken
if (time[1]) {
// Is event overnight?
if (time[1].substr(-2) == 'am' && time[0].substr(-2) == 'pm') {
let endDate = new Date(start)
endDate.setDate(endDate.getDate() + 1)
endToken = `${endDate.toLocaleDateString('sv-SE').replace(/-/gi, '/')} ${time[1]}`
} else { // same day
endToken = `${startDate.replace(/-/gi, '/')} ${time[1]}`
}
} else { // default 1 hour duration
endToken = start.getTime() + 60*60*1000
}
const end = new Date(endToken)
const headerContent = document.createElement('div')
headerContent.innerHTML = `
<h2><a target="_blank" href="${event.url}" title="FunCheapSF Page">${event.title}</a></h2>
<add-to-calendar-button
name="${event.title.replaceAll('"',"'")}"
description="${event.eventUrl}"
startDate="${startDate}"
options="'Apple','Google','iCal','Outlook.com'"
startTime="${start.toTimeString().substr(0,5)}"
endDate="${end.toLocaleDateString('sv-SE')}"
endTime="${end.toTimeString().substr(0,5)}"
location="${event.venue}"
listStyle="modal"
buttonStyle="default"
timeZone="America/Los_Angeles"
size="4"
hideTextLabelButton
hideCheckmark
debug
></add-to-calendar-button>
<h3>
<a target="_blank" href="https://maps.google.com/?q=${encodeURIComponent(event.venue)}&ll=${event.geometry.lat},${event.geometry.lng}" title="Venue Details on Google Maps">${event.venue}</a>
|
<a target="_blank" href="${event.eventUrl}" title="Event Page">${event.cost}</a>
<br>
<span>${event.date_text}</span>
|
<span>${event.time}</span>
</h3>
`
this.cachedInfoWindow.setHeaderContent(headerContent)
this.cachedInfoWindow.setContent(`
<div class="info-header">
<p>
${event.cost_details}
</p>
<p class="categories">Categories: ${event.categories.map(category => `<a onclick="filter({category:'${category}'})">${category}</a>`).join('')}</p>
</div>
<div class="info-body">
<input id="moreInfo" type="checkbox">
<label for="moreInfo">+ Expand Details +</label>
<div id="details">
${event.details}
</div>
</div>
`);
}
return this.cachedInfoWindow;
}
/**
* Loads event data from cache
*
* @returns {object[]} events
*/
get() {
if (this.cache)
return this.cache;
this.cache = window.localStorage.getItem('events');
if (this.cache)
this.cache = JSON.parse(this.cache);
return this.cache;
}
/**
* Stores the event data to cache and adds a timestamp
*
* @param {object[]} events
* @returns {object[]} events
*/
set(events) {
try {
// Known to throw QuotaExceededException on Safari
window.localStorage.setItem('events', JSON.stringify(events));
window.localStorage.setItem('events_age', Date.now());
} catch (e) {
console.error(e)
}
this.cache = events;
return this.cache;
}
/**
* Returns the age of the cache
*
* @returns {number} events_age - Timestamp
*/
age() {
return window.localStorage.getItem('events_age');
}
/**
* Specifies if the age of the cache is old. Defaults to 24 hours
*
* @param {number} [old=86400] - How long ago is considered old. Default: 24 hours
* @returns {boolean}
*/
isFresh(old = 86400) {
let age = this.age();
return age && age > (Date.now() - old);
}
/**
* Checks if the cache is old and updates it
*
* @returns {Promise}
*/
load() {
if (this.isFresh()) {
return Promise.resolve(this.get());
} else {
return this.query()
.then(this.set.bind(this));
}
}
/**
* Queries the crawler API
*
* @returns {Promise}
*/
query() {
return fetch(new Request(Events.API))
.then(response => response.json());
}
}
Events.API = 'https://api.apify.com/v2/acts/apify~cheerio-scraper/runs/last/dataset/items?token=apify_api_1U4gg8GRgTkFBjyfEkxKNtS9n4gUUw3wUjUV';