-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
409 lines (375 loc) · 14.6 KB
/
main.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
'use strict'
const LRT_NAMES = {
/* needed because source data has hebrew names but RTL text often confuses vscode, so defining English consts helps */
GREEN: "ירוק",
RED: "אדום",
PURPLE: "סגול",
BROWN: "חום",
};
const BASE_LAYERS = {
metro: {
name_EN: "Metro",
name_HE: "מטרו",
sources: [
{
url: "data/tlv_metro_isochrones_unmerged.geojson",
type: "unmerged_isochrones"
},
{
url: "data/tlv_metro_lines.geojson",
type: "lines",
color_rules: {
property_name: "NAME",
M1: "#c48d55",
M2: "#14a6f1",
M3: "#fea2bb"
}
},
{
url: "data/tlv_metro_stations.geojson",
type: "stations",
color_rules: {
property_name: "LINE",
"M1-south": "#c48d55",
"M1-north": "#c48d55",
M2: "#14a6f1",
M3: "#fea2bb"
}
},
]
},
lrt: {
// brown line is also part of the LRT layer
name_EN: "LRT",
name_HE: 'רק"ל',
sources: [
{
url: "data/tlv_lrt_isochrones_unmerged.geojson",
type: "unmerged_isochrones"
},
{
url: "data/tlv_lrt_lines.geojson",
type: "lines",
color_rules: {
property_name: "NAME",
[LRT_NAMES.RED]: "#d63229",
[LRT_NAMES.GREEN]: "#35a56a",
[LRT_NAMES.PURPLE]: "#9f307d",
[LRT_NAMES.BROWN]: "#ae6322",
}
},
{
url: "data/tlv_lrt_stations.geojson",
type: "stations",
color_rules: {
property_name: "LINE",
[LRT_NAMES.RED]: "#d63229",
[LRT_NAMES.GREEN]: "#35a56a",
[LRT_NAMES.PURPLE]: "#9f307d",
[LRT_NAMES.BROWN]: "#ae6322",
}
},
]
}
};
const MERGED_ISOCHRONE_LAYERS = {
lrt: 'data/tlv_lrt_isochrones_merged.geojson',
metro: 'data/tlv_metro_isochrones_merged.geojson',
lrt_metro: 'data/tlv_metro_lrt_isochrones_merged.geojson',
brown: 'data/tlv_brown_isochrones_merged.geojson',
brown_lrt: 'data/tlv_lrt_brown_isochrones_merged.geojson',
brown_lrt_metro: 'data/tlv_metro_lrt_brown_isochrones_merged.geojson',
brown_metro: 'data/tlv_brown_metro_isochrones_merged.geojson'
};
const MAPBOX_TYPES = {
unmerged_isochrones: "fill",
stations: "circle",
lines: "line",
};
class LayerManager {
constructor(map) {
this.map = map;
this.enabledLayers = new Set(['lrt']);
this.enabledTimes = new Set(['5', '10', '15']);
this._syncCheckboxState();
this._loadLayers();
this._registerEventHandlers();
}
_loadLayers() {
Object.entries(MERGED_ISOCHRONE_LAYERS).forEach(([key, url]) => {
const id = `${key}_merged_isochrones`;
this.map.addSource(id, {
type: 'geojson',
data: url,
});
this.map.addLayer({
id,
type: 'fill',
source: id,
layout: {
visibility: this._getCurrentIsochroneLayer() === key ? 'visible' : 'none',
},
paint: {
'fill-color': ['get', 'color'],
'fill-opacity': 0.4,
},
});
});
Object.entries(BASE_LAYERS).forEach(([key, layer]) => {
layer.sources.forEach((source) => {
const id = `${key}_${source.type}`;
const sourceDef = {
type: 'geojson',
data: source.url,
}
if (source.type === 'stations') {
sourceDef.promoteId = 'OBJECTID';
}
this.map.addSource(id, sourceDef);
const colorProp = source.type === 'lines' ? 'line-color' : 'circle-color';
const colorMap = [];
const paint = {}
if (source.color_rules) {
Object.entries(source.color_rules).forEach(([key, value]) => { if (key != 'property_name') { colorMap.push(key, value); }})
paint[colorProp] = ['match', ['string', ['get', source.color_rules.property_name]], ...colorMap, 'black'];
}
const layout = {
visibility: this.enabledLayers.has(key) ? 'visible' : 'none',
};
switch (source.type) {
case 'unmerged_isochrones':
paint['fill-opacity'] = 0;
break;
case 'lines':
paint['line-width'] = 2;
paint['line-opacity'] = 0.9;
break;
case 'stations':
paint['circle-stroke-width'] = [
'case',
['boolean', ['feature-state', 'hover'], false],
3,
0
];
break;
}
const layerProps = {
id,
type: MAPBOX_TYPES[source.type],
source: id,
minzoom: source.type === 'stations' ? 12 : 0,
layout,
paint,
};
if (key === 'lrt') {
layerProps.filter = this._getBrownLineFilter(source.type);
}
this.map.addLayer(layerProps);
});
});
}
_getCurrentIsochroneLayer() {
return Array.from(this.enabledLayers).sort().join('_');
}
_registerEventHandlers() {
document.querySelectorAll('#layer_selection input, #time_selection input').forEach((node) => {
node.addEventListener('change', (event) => {
const layerKey = event.target.dataset.layer;
const layerSet = ['5', '10', '15'].includes(layerKey) ? this.enabledTimes : this.enabledLayers;
if (layerSet.has(layerKey)){
layerSet.delete(layerKey);
} else {
layerSet.add(layerKey);
}
this.syncLayerVisibility();
});
});
}
_getBrownLineFilter(sourceType) {
if (this.enabledLayers.has('brown') && this.enabledLayers.has('lrt')) {
// both lrt and brown line enabled? no need for filter
return null;
}
let filterField;
switch (sourceType) {
case 'lines':
filterField = 'NAME'
break;
case 'stations':
case 'unmerged_isochrones':
filterField = 'LINE'
break;
}
const filterOp = this.enabledLayers.has('brown') ? '==' : '!=';
return [filterOp, ['get', filterField], 'חום']
}
enableLayer(layer) {
this.enabledLayers.add(layer);
this.syncLayerVisibility();
}
disableLayer(layer) {
this.enabledLayers.remove(layer);
this.syncLayerVisibility();
}
_syncCheckboxState() {
document.querySelectorAll('#layer_selection input').forEach((node) => {
const layerKey = node.dataset.layer;
node.checked = this.enabledLayers.has(layerKey);
});
document.querySelectorAll('#time_selection input').forEach((node) => {
const layerKey = node.dataset.layer;
node.checked = this.enabledTimes.has(layerKey);
});
}
_getLayerVisibility(key) {
let visibility = this.enabledLayers.has(key) ? 'visible' : 'none';
if (key === 'lrt' && this.enabledLayers.has('brown')) {
// brown line is included in the LRT layer, even though it's BRT
visibility = 'visible';
}
return visibility;
}
syncLayerVisibility() {
Object.entries(BASE_LAYERS).forEach(([key, layer]) => {
layer.sources.forEach((source) => {
const layerId = `${key}_${source.type}`;
this.map.setLayoutProperty(layerId, 'visibility', this._getLayerVisibility(key));
if (key === 'lrt') {
this.map.setFilter(layerId, this._getBrownLineFilter(source.type), { validate: false });
}
});
});
Object.keys(MERGED_ISOCHRONE_LAYERS).forEach((key) => {
const layerId = `${key}_merged_isochrones`;
const visibility = this._getCurrentIsochroneLayer() === key ? 'visible' : 'none';
this.map.setLayoutProperty(layerId, 'visibility', visibility);
// filter isochrones according to selected times
this.map.setFilter(layerId, ['in', ['get', 'time'], ['literal', Array.from(this.enabledTimes).map(time => parseInt(time))]]);
});
}
}
class InfoPopup {
constructor(map) {
this.popup = new mapboxgl.Popup({
closeButton: true,
closeOnClick: false,
maxWidth: '300px',
});
this.isShown = false;
this.map = map;
this.showPopup = this.showPopup.bind(this);
this.hidePopup = this.hidePopup.bind(this);
this.movePopup = this.movePopup.bind(this);
Object.keys(MERGED_ISOCHRONE_LAYERS).forEach((layer) => {
map.on('mouseenter', `${layer}_merged_isochrones`, this.showPopup);
map.on('mouseleave', `${layer}_merged_isochrones`, this.hidePopup);
map.on('mousemove', `${layer}_merged_isochrones`, this.movePopup);
});
this.hoverFeatures = [];
}
getPopupContents(point) {
const features = this.map.queryRenderedFeatures(point);
const stations = []
// collect station features, to be sorted by time
features.forEach((feature) => {
if (!feature.source.includes('unmerged_isochrones')) {
return; // skip irrelvant layers
}
const properties = { ...feature.properties, source: feature.source };
stations.push(properties)
});
stations.sort((a, b) => a.time - b.time);
// build contents
const seenStations = [];
const seenTimes = new Set([]);
const newHoverFeatures = [];
const container = document.createElement('div');
let ul;
stations.forEach((station) => {
const stationKey = `${station.LINE}-${station.NAME}`;
if (!seenStations.includes(stationKey)) {
if (!seenTimes.has(station.time)) {
if (ul) {
container.appendChild(ul);
}
ul = document.createElement('ul');
const h2 = document.createElement('h2');
h2.textContent = `${station.time} דקות`;
container.appendChild(h2);
seenTimes.add(station.time);
}
seenStations.push(stationKey);
const li = document.createElement('li');
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const colorRules = BASE_LAYERS[station.source.split('_')[0]].sources.find((item) => item.type === 'stations').color_rules;
svg.setAttribute('width', "16px");
svg.setAttribute('height', "16px");
svg.setAttribute('aria-hidden', 'true');
svg.innerHTML = `<circle r="45%" cx="50%" cy="50%" fill="${ colorRules[station.LINE]}">`;
li.appendChild(svg);
const cleanLine = station.LINE.split('-')[0];
const span = document.createElement('span');
span.textContent = `${cleanLine} - ${station.NAME}`;
li.appendChild(span);
ul.appendChild(li);
newHoverFeatures.push({ id: station.OBJECTID, source: `${station.source.split('_')[0]}_stations` });
}
});
container.appendChild(ul);
this.hoverFeatures.forEach((feature) => {
if (!newHoverFeatures.find((newFeature) => feature.id === newFeature.id && feature.source === newFeature.source)) {
this.map.setFeatureState(feature, { hover: false })
}
});
newHoverFeatures.forEach((feature) => {
if (!this.hoverFeatures.find((oldFeature) => feature.id === oldFeature.id && feature.source === oldFeature.source)) {
this.map.setFeatureState(feature, { hover: true });
}
});
this.hoverFeatures = newHoverFeatures;
return container.outerHTML;
}
movePopup(e) {
if (this.isShown) {
this.popup.setLngLat(e.lngLat).setHTML(this.getPopupContents(e.point));
}
}
showPopup(e) {
this.map.getCanvas().style.cursor = 'pointer';
this.popup.setLngLat(e.lngLat).setHTML(this.getPopupContents(e.point)).addTo(this.map);
this.isShown = true;
}
hidePopup() {
this.map.getCanvas().style.cursor = '';
this.popup.remove();
this.isShown = false;
this.hoverFeatures.forEach((feature) => this.map.setFeatureState(feature, { hover: false }));
this.hoverFeatures = [];
}
}
function init() {
mapboxgl.accessToken = 'pk.eyJ1IjoiZWxhZGFsZmFzc2EiLCJhIjoiY2psOGF4eHY0MGQ2NjNrbXQyOXFmamlkbCJ9.j2ECgxf01pIEQvcreLeFWQ';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v10',
center: [34.775113, 32.075341],
zoom: 11,
});
map.addControl(new mapboxgl.NavigationControl());
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js');
mapboxgl.prewarm();
map.on('load', () => {
window.layerManager = new LayerManager(map);
window.InfoPopup = new InfoPopup(map);
});
window.myMap = map;
document.querySelector('#desclaimer button').addEventListener('click', () => {
document.getElementById('desclaimer_bg').remove();
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init());
} else {
// in the case DOMContentLoaded might fire before this script could run
init();
}