-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
445 lines (385 loc) · 12.7 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>Badger Map</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" href="./favicon.ico" type="image/x-icon" />
<style type="text/css">
html,
body {
height: 100%;
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
}
#main {
height: 100%;
}
.map-info-window {
padding: 0.5em;
}
.map-info-window h1 {
font-size: 1.3em;
margin: 0.3rem 0 1rem;
}
.map-info-window p {
margin: 1rem 0 0.3rem;
}
.map-info-window dl {
width: 12rem;
margin: 1rem 0 0.3rem;
}
dt {
float: left;
clear: left;
width: 4.2rem;
text-align: left;
font-weight: bold;
}
dt::after {
content: ":";
}
dd {
margin: 0 0 0 4.4rem;
padding: 0 0 0.5em 0;
}
.map-info-window table th {
text-align: left;
}
#authorize-dialog {
width: 90%;
max-width: 30em;
background-color: white;
box-sizing: border-box;
border-radius: 15px;
box-shadow: 0px 5px 10px 2px #888888;
padding: 1.5em;
position: fixed;
top: 30%;
left: 50%;
transform: translateX(-50%);
z-index: 10;
}
#authorize-dialog h1 {
margin: 0.2em 0;
font-size: 1.5em;
font-weight: lighter;
}
#authorize-button {
margin-top: 1em;
padding: 0.3em 0.8em;
font-size: 1.3em;
color: white;
font-weight: bold;
background-color: #212121;
border: none;
cursor: pointer;
}
#add-yourself-info {
position: absolute;
background-color: white;
box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;
left: 0;
bottom: 0;
/* A bit more spacing on the right ensures the default zoom buttons are always accessible. */
margin: 10px 60px 10px 10px;
padding: 10px 17px;
}
#add-yourself-info h1 {
font-size: 1.2em;
}
</style>
<script
src="https://maps.googleapis.com/maps/api/js?key={{API_KEY}}&callback=initMap"
async
defer
></script>
<script
async
defer
src="https://apis.google.com/js/api.js"
onload="gapiLoadOkay()"
onerror="gapiLoadFail(event)"
></script>
<script
async
defer
src="https://accounts.google.com/gsi/client"
onload="gisLoadOkay()"
onerror="gisLoadFail(event)"
></script>
</head>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<div id="authorize-dialog" style="display: none">
<h1>Sign in to continue</h1>
<p>
Badger Map needs access to your Red Badger account to continue. This is
to load the location information of Badgers.
</p>
<p>
<button id="authorize-button">Show me the badgers</button>
</p>
</div>
<div id="main"></div>
<div id="add-yourself-info" style="display: none">
<h1>🗺 Not on the map yet?</h1>
<p>
Click on your home on the map to<br />see instructions for adding
yourself.
</p>
</div>
<script type="text/javascript">
// Client ID and API key from the Developer Console
const CLIENT_ID = "{{CLIENT_ID}}";
const API_KEY = "{{API_KEY}}";
// Array of API discovery doc URLs for APIs used by the quickstart
const DISCOVERY_DOC =
"https://sheets.googleapis.com/$discovery/rest?version=v4";
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPE = "https://www.googleapis.com/auth/spreadsheets.readonly";
const SPREADSHEET_ID = "{{SPREADSHEET_ID}}";
const authorizeDialog = document.getElementById("authorize-dialog");
const authorizeButton = document.getElementById("authorize-button");
const addYourselfInfo = document.getElementById("add-yourself-info");
let map, pinIcon; // initialised by initMap()
const state = {
location: null,
locationMarker: null,
infoWindow: null,
people: [],
};
/* This is not pretty, but it lets us handle the waiting
for async script loading relatively neatly with await later
*/
var gapiLoadOkay, gapiLoadFail;
const gapiLoadPromise = new Promise((resolve, reject) => {
gapiLoadOkay = resolve;
gapiLoadFail = reject;
});
var gisLoadOkay, gisLoadFail;
const gisLoadPromise = new Promise((resolve, reject) => {
gisLoadOkay = resolve;
gisLoadFail = reject;
});
let tokenClient; // initialised by the following block
(async () => {
await gapiLoadPromise;
await new Promise((callback, onerror) => {
gapi.load("client", { callback, onerror });
});
gapi.client.init({ apiKey: API_KEY });
await gapi.client.load(DISCOVERY_DOC);
await gisLoadPromise;
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPE,
prompt: "",
callback: "",
});
authorizeButton.onclick = createMarkers;
authorizeDialog.style.display = "block";
})();
/* PEOPLE DATA HANDLING */
/**
* Get the spreadsheet data
*/
async function createMarkers() {
let people;
try {
await getAuthorization();
people = await loadPeople();
} catch (err) {
console.error("Error fetching people data: ", err);
return;
}
// Got data, update the UI
authorizeDialog.style.display = "none";
setupAddYourselfWindow();
people.forEach(({ name, position, slack }, idx) => {
const marker = new google.maps.Marker({
position,
animation: google.maps.Animation.DROP,
icon: pinIcon,
map,
});
marker.addListener("click", markerClickHandler(idx, marker));
});
state.people = people;
}
async function loadPeople() {
let response = await gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: SPREADSHEET_ID,
range: "people",
});
const people = response.result.values;
return people.map(function (row, idx) {
const [name, lat, lng, slack] = row;
const position = { lat: +lat, lng: +lng };
return { name, position, slack };
});
}
async function getAuthorization(err) {
return new Promise((resolve, reject) => {
// Settle this promise in the response callback for requestAccessToken()
tokenClient.callback = (resp) => {
if (resp.error !== undefined) {
reject(resp);
}
resolve(resp);
};
tokenClient.requestAccessToken();
});
}
/* MAP SETUP */
function initMap() {
const main = document.getElementById("main");
map = new google.maps.Map(main, {
center: { lat: 51.507, lng: -0.128 },
zoom: 11,
});
pinIcon = new google.maps.MarkerImage(
"./badger-pin.png",
null /* size is determined at runtime */,
null /* origin is 0,0 */,
null /* anchor is bottom center of the scaled image */,
new google.maps.Size(30, 50)
);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
state.location = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
state.locationMarker = new google.maps.Marker({
position: state.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
strokeColor: "#f0faff",
strokeWeight: 2,
fillColor: "#1976d2",
fillOpacity: 1,
},
map,
});
map.setCenter(state.location);
map.setZoom(14);
},
function () {
console.info("Could not obtain location information");
}
);
}
}
/*
* Create and configure the marker infoWindow content
*/
function infoWindow({ name, position, slack }, location) {
const content = document.createElement("div");
content.className = "map-info-window";
content.innerHTML =
'<h1></h1><dl class="info"><dt class="slack">Slack</dt><dd class="slack"></dd><dt class="distance">Distance</dt><dd class="distance"></dd></dl><p class="directions"><a>Get directions</a></p>';
content.querySelector("h1").textContent = name;
content.querySelector("dd.slack").textContent = slack;
content
.querySelector("p.directions a")
.setAttribute(
"href",
`https://maps.google.com?daddr=${position.lat},${position.lng}`
);
if (location) {
// overestimate the distance to compensate for obstacles. This is super
// scientific, obviously
const dist = (1.22 * distance(state.location, position)).toFixed(1);
const walkingSpeed = 5.0; // km/h
const time = dist / walkingSpeed; // hrs
const hrs = Math.floor(time);
const mins = Math.round((time % 1) * 60);
const hrsText =
hrs > 0 ? (hrs < 2 ? `${hrs} hour and ` : `${hrs} hours and`) : "";
const minsText = mins < 2 ? `${mins} minute` : `${mins} minutes`;
const text = `about ${hrsText}${minsText} walk`;
content.querySelector("dd.distance").textContent = text;
} else {
content.querySelectorAll("dl .distance").forEach((el) => el.remove());
}
return new google.maps.InfoWindow({ content });
}
/*
* Create a click handler for a marker for the person at index idx
* The handler will re-create the infoWindow based on state every time
*/
function markerClickHandler(idx, marker) {
return function () {
if (state.infoWindow && state.infoWindow.close) {
state.infoWindow.close();
}
// Update the info window based on *current* state
// This is called every time a marker is clicked
state.infoWindow = infoWindow(state.people[idx], state.location);
state.infoWindow.open(map, marker);
};
}
/**
* Calculate a great circle distance between two points using the Haversine
* formula
*/
function distance(origin, destination) {
const rad = (n) => (n / 180) * Math.PI;
const sin_2 = (x) => Math.sin(x) * Math.sin(x);
const D = 2 * 6371; // Km
const [lat1, lat2] = [rad(origin.lat), rad(destination.lat)];
const [lng1, lng2] = [rad(origin.lng), rad(destination.lng)];
return (
D *
Math.asin(
Math.sqrt(
sin_2((lat1 - lat2) / 2) +
Math.cos(lat1) * Math.cos(lat2) * sin_2((lng1 - lng2) / 2)
)
)
);
}
/**
* Show a info window on click, describing how to add youself to
* the map.
*/
function setupAddYourselfWindow() {
const content = document.createElement("div");
content.className = "map-info-window";
content.innerHTML = `
<h1>Add yourself</h1>
<p>Open the <a href="https://docs.google.com/spreadsheets/d/${SPREADSHEET_ID}/edit" target="_blank" rel="noopener">spreadsheet</a> and add your name and Slack handle.<br>Copy the coordinates from here:</p>
<table>
<tr>
<th scope="row">Latitude</th>
<td class="lat"></td>
</tr>
<tr>
<th scope="row">Longitude</th>
<td class="lng"></td>
</tr>
</table>
`;
const infowindow = new google.maps.InfoWindow({ content });
map.addListener("click", function (e) {
content.querySelector(".lat").textContent = e.latLng.lat();
content.querySelector(".lng").textContent = e.latLng.lng();
infowindow.open(map, {
get(prop) {
switch (prop) {
case "position":
return e.latLng;
}
},
});
});
addYourselfInfo.style.display = "block";
}
</script>
</body>
</html>