forked from mnhrc/mnhrc.github.io
-
Notifications
You must be signed in to change notification settings - Fork 3
/
map_controller.js
517 lines (458 loc) · 19.4 KB
/
map_controller.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
// Data =======================================================================
var haveData = false;
var courses = [];
// Map ========================================================================
google.maps.visualRefresh = true;
var map, geocoder;
var markers = [];
// define center point of initial map render
var centerLat = 36.16;
var centerLng = 273.215;
// Sheets API =================================================================
var discoveryDocs = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
var apiKey = 'AIzaSyC8YkrMM7NEO59ERQ2OBkE6I3QfLyVmN64';
// sheet shared with me (nick), seemingly controlled by MNHRC
var spreadsheetId = '1aI16jUKAHFLmjKXtjI2nCYltDWa1awCFZ2Kt1IhhbZ4';
// function manyLanguages(english, spanish, french, arabic) {
// return { en: english, es: spanish, fr: french, ar: arabic };
// }
// Multi-lingual support of local text.
// Should be simple enough to extend to even more languages,
// just copy the `translated.en` object, replace the values, and
// rename the language. Please use ISO639-2 abbreviations.
// Every object key here maps directly to a tag that has the
// attribute id="ml-foobar". Leaving keys unsupplied or empty string
// will result in a fallback to 'en' (defaultLanguageFallback)
// TODO: Still needs translation work.
var translated = {
en: {
aboutp1: 'wESL (We ESL) is a platform for easily finding ESL (English as a Second Language) classes in Nashville, TN. All organizations that offer ESL classes are listed on the map. You can click on the map location for more information about the organizations and the classes they offer. If you would like your organization\'s classes to be added to the platform, click on the link the in the left column titled "Submission Form."',
aboutp2: 'The wESL platform is offered and maintained by the Metro Human Relations Commission. If you have any questions, please email us at <a href="mailto:[email protected]?subject=wESL" target="_blank">[email protected]</a> and follow <a href="https://www.twitter.com/eslmap" target="_blank">@ESLmap</a> on Twitter for updates about the platform.',
aboutp3: 'For more info about the Metro Human Relations Commission, please visit <a href="http://www.1City4AllPeople.com" target="_blank">www.1City4AllPeople.com</a>, <a href="http://www.Facebook.com/NashMHRC" target="_blank">www.Facebook.com/NashMHRC</a>, or <a href="http://www.twitter.com/1City4AllPeople" target="_blank">www.twitter.com/1City4AllPeople</a>.',
navTitle: 'Davidson County English Language Courses',
daySelect1: 'Next 30 Days',
daySelect2: '30 - 60 Days',
daySelect3: '60 - 90 Days',
scheduleSelect1: 'Any',
scheduleSelect2: 'Semester',
scheduleSelect3: 'Trimester',
scheduleSelect4: 'Quarterly',
scheduleSelect5: 'Ongoing',
levelSelect1: 'Any',
levelSelect2: 'Pre-Literate',
levelSelect3: 'Intro',
levelSelect4: 'Level 1',
levelSelect5: 'Level 2',
levelSelect6: 'Level 3',
levelSelect7: 'Level 4',
levelSelect8: 'Level 5',
levelSelect9: 'Conversation',
levelSelect10: 'GED',
levelSelect11: 'Citizenship',
costSelect1: 'Any',
costSelect2: 'Free',
costSelect3: '$10',
costSelect4: '$20',
costSelect5: '$30',
costSelect6: '$40',
costSelect7: '$50',
costSelect8: '$60+',
classSubmit: 'To submit a class click <a href="https://docs.google.com/a/jasonamyers.com/forms/d/1yQP_1ph3Rx3VNEIiHvYny9QtoDClMXNa7F1ro0srFjA/viewform">here.</a>',
aboutLink: 'About this App',
popupBack: '< Back to Locations',
popupTitleClasses: 'Classes held at:',
popupTitleClass: 'Class',
popupTitleDate: 'Date',
popupTitleSchedule: 'Schedule',
popupTitleCurriculum: 'Curriculum',
popupTitleFee: 'Fee',
searchBack: '< Back to Search',
locations: 'Locations'
},
es: {
aboutp1: 'wESL (We ESL) is a platform for easily finding ESL (English as a Second Language) classes in Nashville, TN. All organizations that offer ESL classes are listed on the map. You can click on the map location for more information about the organizations and the classes they offer. If you would like your organization\'s classes to be added to the platform, click on the link the in the left column titled "Submission Form."',
aboutp2: 'The wESL platform is offered and maintained by the Metro Human Relations Commission. If you have any questions, please email us at <a href="mailto:[email protected]?subject=wESL" target="_blank">[email protected]</a> and follow <a href="https://www.twitter.com/eslmap" target="_blank">@ESLmap</a> on Twitter for updates about the platform.',
aboutp3: 'For more info about the Metro Human Relations Commission, please visit <a href="http://www.1City4AllPeople.com" target="_blank">www.1City4AllPeople.com</a>, <a href="http://www.Facebook.com/NashMHRC" target="_blank">www.Facebook.com/NashMHRC</a>, or <a href="http://www.twitter.com/1City4AllPeople" target="_blank">www.twitter.com/1City4AllPeople</a>.',
navTitle: 'Davidson County English Language Courses',
daySelect1: 'Next 30 Days',
daySelect2: '30 - 60 Days',
daySelect3: '60 - 90 Days',
scheduleSelect1: 'Any',
scheduleSelect2: 'Semester',
scheduleSelect3: 'Trimester',
scheduleSelect4: 'Quarterly',
scheduleSelect5: 'Ongoing',
levelSelect1: 'Any',
levelSelect2: 'Pre-Literate',
levelSelect3: 'Intro',
levelSelect4: 'Level 1',
levelSelect5: 'Level 2',
levelSelect6: 'Level 3',
levelSelect7: 'Level 4',
levelSelect8: 'Level 5',
levelSelect9: 'Conversation',
levelSelect10: 'GED',
levelSelect11: 'Citizenship',
costSelect1: 'Any',
costSelect2: 'Free',
costSelect3: '$10',
costSelect4: '$20',
costSelect5: '$30',
costSelect6: '$40',
costSelect7: '$50',
costSelect8: '$60+',
classSubmit: 'To submit a class click <a href="https://docs.google.com/a/jasonamyers.com/forms/d/1yQP_1ph3Rx3VNEIiHvYny9QtoDClMXNa7F1ro0srFjA/viewform">here.</a>',
aboutLink: 'About this App',
popupBack: '< Back to Locations',
popupTitleClasses: 'Classes held at:',
popupTitleClass: 'Class',
popupTitleDate: 'Date',
popupTitleSchedule: 'Schedule',
popupTitleCurriculum: 'Curriculum',
popupTitleFee: 'Fee',
searchBack: '< Back to Search',
locations: 'Locations'
},
ar: {
aboutp1: 'wESL (We ESL) is a platform for easily finding ESL (English as a Second Language) classes in Nashville, TN. All organizations that offer ESL classes are listed on the map. You can click on the map location for more information about the organizations and the classes they offer. If you would like your organization\'s classes to be added to the platform, click on the link the in the left column titled "Submission Form."',
aboutp2: 'The wESL platform is offered and maintained by the Metro Human Relations Commission. If you have any questions, please email us at <a href="mailto:[email protected]?subject=wESL" target="_blank">[email protected]</a> and follow <a href="https://www.twitter.com/eslmap" target="_blank">@ESLmap</a> on Twitter for updates about the platform.',
aboutp3: 'For more info about the Metro Human Relations Commission, please visit <a href="http://www.1City4AllPeople.com" target="_blank">www.1City4AllPeople.com</a>, <a href="http://www.Facebook.com/NashMHRC" target="_blank">www.Facebook.com/NashMHRC</a>, or <a href="http://www.twitter.com/1City4AllPeople" target="_blank">www.twitter.com/1City4AllPeople</a>.',
navTitle: 'Davidson County English Language Courses',
daySelect1: 'Next 30 Days',
daySelect2: '30 - 60 Days',
daySelect3: '60 - 90 Days',
scheduleSelect1: 'Any',
scheduleSelect2: 'Semester',
scheduleSelect3: 'Trimester',
scheduleSelect4: 'Quarterly',
scheduleSelect5: 'Ongoing',
levelSelect1: 'Any',
levelSelect2: 'Pre-Literate',
levelSelect3: 'Intro',
levelSelect4: 'Level 1',
levelSelect5: 'Level 2',
levelSelect6: 'Level 3',
levelSelect7: 'Level 4',
levelSelect8: 'Level 5',
levelSelect9: 'Conversation',
levelSelect10: 'GED',
levelSelect11: 'Citizenship',
costSelect1: 'Any',
costSelect2: 'Free',
costSelect3: '$10',
costSelect4: '$20',
costSelect5: '$30',
costSelect6: '$40',
costSelect7: '$50',
costSelect8: '$60+',
classSubmit: 'To submit a class click <a href="https://docs.google.com/a/jasonamyers.com/forms/d/1yQP_1ph3Rx3VNEIiHvYny9QtoDClMXNa7F1ro0srFjA/viewform">here.</a>',
aboutLink: 'About this App',
popupBack: '< Back to Locations',
popupTitleClasses: 'Classes held at:',
popupTitleClass: 'Class',
popupTitleDate: 'Date',
popupTitleSchedule: 'Schedule',
popupTitleCurriculum: 'Curriculum',
popupTitleFee: 'Fee',
searchBack: '< Back to Search',
locations: 'Locations'
}
};
// Do not even overwrite from headers.
// English is the only language that is fully filled out.
var defaultLanguageFallback = 'en';
// This can be replaced by header values.
// It is the value that is used when populating the text.
var currentLanguage = 'en';
// personal copy of sheet ([email protected])
//var spreadsheetId = '1fnAs8ZrPcNGP6LTDyV9ajiP2grdpNCiPQlSdCVFM7ug';
// lifecycle start
google.maps.event.addDomListener(window, 'load', initialize);
// connect to spreadsheet and pull data from it
function initGAPI (callback) {
return new Promise(function (res, rej) {
gapi.load('client', function () {
gapi.client.init({
apiKey: apiKey,
discoveryDocs: discoveryDocs,
})
.then(loadSheetData)
.then(function (locations) {
res(locations);
});
// no catch on this thing?
//.catch(rej);
});
});
}
function loadSheetData () {
console.info('gapi::loadSheetData');
// send out a promise
return gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: spreadsheetId,
range: 'Sheet1'
}).then(function onSheet (resp) {
var values = resp.result.values;
var fields = {
"Organization" : "organization",
"address" : "address",
"Latitude/Longitude" : "latitudeLongitude",
"classAddress" : "classAddress",
"Courses Offered" : "coursesOffered",
"Start Date" : "startDate",
"Fee" : "fee",
"Description" : "description",
"Phone Number" : "phoneNumber",
"Email Address" : "emailAddress",
"websiteURL" : "websiteUrl",
"Days Classes Offered" : "daysClassesOffered",
"Class Times" : "classTimes",
"Faith Based" : "faithBased",
"Class Schedule" : "classSchedule",
"Status" : "status",
"Site2Address" : "site2Address",
"Curriculum Used" : "curriculumUsed"
};
var headers = values[0].map(function mapHeader (header) {
return fields[header];
});
var locations = values.slice(1).map(function makeLocations (row) {
var location = {};
return headers.reduce(function mapToCells (acc, header, i) {
acc[header] = row[i];
return acc;
}, location);
}).map(function extractLatLon (location) {
// TODO a little checking would probably be good
// look here if map errors?
var latLon = location.latitudeLongitude.split(',');
location.$lat = latLon[0];
location.$lon = latLon[1];
return location;
});
locations
.filter(function (loc) { return loc.status === 'Approved'; })
.forEach(function (loc) { courses.push(loc); });
console.info('gapi::loadSheetData::ETL doneskies');
haveData = true;
return locations;
}).then(function cleanVals (locations) {
// big ugly data cleansing map
return locations.map(function (loc) {
if (loc.classSchedule === undefined)
loc.classSchedule = "";
return loc;
});
});
}
function listLocation(organization, classAddress) {
var output = '<tr class="locations"><td class="location-list">'
+ '<div class="location-button" onclick="selectAddressFromList(\'' + classAddress + '\');">'
+ organization + '</div></td></tr>';
$('#location_table tr:last').after(output);
}
// This is the function that figures out which courses to show on the map.
function getFilteredCourses() {
// For each course, execute the function to determine whether we should
// show it or not.
return courses.filter(function (course) {
// Filter by start date.
var courseDate = course.startDate;
if (courseDate !== "" && courseDate.indexOf('/') !== -1) {
var filterInput = parseInt($("#start_date_menu").val());
var filterEnd = moment().day(filterInput);
var filterStart = moment();
if (filterInput === 60) {
filterStart = moment().add('d', 30);
}
if (filterInput === 90) {
filterStart = moment().add('d', 60);
}
var courseCompare = moment(courseDate);
if (courseCompare.valueOf() > filterEnd.valueOf() ||
courseCompare.valueOf() < filterStart.valueOf()) {
return false;
}
}
// Filter by level.
var level = $("#level_menu").val();
if (level !== "" && course.coursesOffered.toLowerCase().indexOf(level.toLowerCase()) === -1) {
return false;
}
// Filter by schedule.
var schedule = $("#schedule_menu").val();
if (schedule !== "" && course.classSchedule.toLowerCase().indexOf(schedule.toLowerCase()) === -1) {
return false;
}
// Filter by cost.
var fee = $("#cost_menu").val();
var courseFee = course.fee.toLowerCase();
if (fee !== courseFee.toLowerCase() && fee !== "") {
if (courseFee !== "" && courseFee !== "free") {
if (fee == "free") {
return false;
}
var testFee = parseInt(courseFee);
var filterFee = parseInt(fee);
if (testFee >= filterFee) {
return false;
}
}
}
// If we passed all those, this course is selected. Hooray!
return true;
});
}
// Knockout bindings :( =======================================================
function ViewModel() {
var self = this;
self.organization = ko.observable();
self.address = ko.observable();
self.classAddress = ko.observable();
self.phoneNumber = ko.observable();
self.emailAddress = ko.observable();
self.websiteUrl = ko.observable();
self.coursesAtLocation = ko.observableArray();
self.anySelected = ko.observable(false);
self.description = ko.observable();
self.faithBased = ko.observable();
self.update = function (data) {
self.organization(data.organization);
self.address(data.address);
self.classAddress(data.classAddress);
self.emailAddress("<a href=mailto:" + data.emailAddress + ">" + data.emailAddress + "</a>");
self.phoneNumber(data.phoneNumber);
self.websiteUrl("<a href=" + data.websiteUrl + ">" + data.websiteUrl + "</a>");
self.description(data.description);
self.faithBased(data.faithBased);
self.coursesAtLocation.removeAll();
data.coursesAtLocation.forEach(function (course) {
self.coursesAtLocation.push(course);
});
};
}
var model = new ViewModel;
var selectedAddress = null;
function selectAddress(classAddress) {
selectedAddress = classAddress;
updatePopup();
}
function selectAddressFromList(classAddress) {
selectedAddress = classAddress;
toggleDetails();
updatePopup();
}
function toggleDetails() {
$("#location-popup").toggle();
$("#location-list").toggle();
}
function updatePopup() {
var matches = getFilteredCourses().filter(function (course) {
return course.classAddress == selectedAddress;
});
if (matches.length !== 0) {
model.update({
organization: matches[0].organization,
address: matches[0].address,
classAddress: selectedAddress,
phoneNumber: matches[0].phoneNumber,
emailAddress: matches[0].emailAddress,
websiteUrl: matches[0].websiteUrl,
description: matches[0].description,
faithBased: matches[0].faithBased,
coursesAtLocation: matches
});
document.getElementById("location-popup").style.display = "block";
}
}
function hidePopup() {
document.getElementById("location-popup").style.display = "none";
}
function insertPin(course) {
var address = course.classAddress;
var organization = course.organization;
$("#location_table tbody").html("");
listLocation(organization, address); // here
if (course.latitudeLongitude === "") {
geocoder.geocode(
{"address": address},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
makeMarker(results[0].geometry.location);
} else {
console.error("Geocoding failed: " + status);
}
});
} else {
var parts = course.latitudeLongitude.split(",");
makeMarker(new google.maps.LatLng(Number(parts[0]), Number(parts[1])));
}
function makeMarker(location) {
var marker = new google.maps.Marker({
map: map,
position: location,
title: organization
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function() {
selectAddress(address);
});
}
}
function initialize() {
// Create the map.
map = new google.maps.Map(document.getElementById("map-canvas"), {
center: new google.maps.LatLng(centerLat, centerLng),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
ko.applyBindings(model);
// declare jquery listeners
$("select.filter_menu").change(updateMap);
$("#aboutLink").click(function() {
$("#about_window").toggle();
});
initGAPI()
.then(updateMap);
}
function showHideLocations() {
$("#location-list").toggle();
$("#location-top").toggle();
$("#navigation").toggle();
}
function hideAbout() {
$("#about_window").toggle();
}
function updateMap() {
// Remove any old pins from the map.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// Insert new pins.
var pinAddresses = [];
getFilteredCourses().forEach(function (course) {
if (pinAddresses.indexOf(course.classAddress) === -1) {
pinAddresses.push(course.classAddress);
insertPin(course);
}
});
// If the popup is visible, we'll want to update that too.
updatePopup();
hidePopup();
}
// Programatically populate all text on the page with the new language.
// All tags with id="ml-foobar" will be populated with text from
// translated['foobar'], falling back on translated['en']['foobar']
// (defaultLanguageFallback) if the language is not implemented yet for
// that tag.
function populateText(lang) {
if (lang) { currentLanguage = lang; }
var defaultTable = translated[defaultLanguageFallback];
var table = translated[currentLanguage] || defaultTable;
Object.keys(defaultTable).forEach(function(key) {
var text = table[key] || defaultTable[key];
$('#ml-' + key).html(text);
});
}