Improved www.ttss.krakow.pl
Jacek Kowalski
2020-11-03 dc9b4f8b92fb78c39258f7bd278deb36c7be6115
commit | author | age
7e7221 1 'use strict';
f4a54f 2
2bc9da 3 var api_refresh = 10000; // 10 seconds
c5a5c3 4 var api_url = 'https://api.ttss.pl';
57b8d3 5
a4d011 6 var geolocation = null;
JK 7 var geolocation_set = 0;
8 var geolocation_button = null;
9 var geolocation_feature = null;
10 var geolocation_accuracy = null;
11 var geolocation_source = null;
12 var geolocation_layer = null;
13
2bc9da 14 var vehicles = {};
JK 15 var hash = null;
eafc1c 16
88a24c 17 var stops_style = {
JK 18     'sb': new ol.style.Style({
19         image: new ol.style.Circle({
20             fill: new ol.style.Fill({color: '#07F'}),
21             stroke: new ol.style.Stroke({color: '#05B', width: 2}),
22             radius: 3,
23         }),
24     }),
25     'st': new ol.style.Style({
26         image: new ol.style.Circle({
27             fill: new ol.style.Fill({color: '#FA0'}),
28             stroke: new ol.style.Stroke({color: '#B70', width: 2}),
29             radius: 3,
30         }),
31     }),
32     'pb': new ol.style.Style({
33         image: new ol.style.Circle({
34             fill: new ol.style.Fill({color: '#07F'}),
35             stroke: new ol.style.Stroke({color: '#05B', width: 1}),
36             radius: 3,
37         }),
38     }),
39     'pt': new ol.style.Style({
40         image: new ol.style.Circle({
41             fill: new ol.style.Fill({color: '#FA0'}),
42             stroke: new ol.style.Stroke({color: '#B70', width: 1}),
43             radius: 3,
44         }),
45     }),
46 };
47 var stops_type = ['st', 'sb', 'pt', 'pb'];
1b7c52 48 var stops_mapping = {};
88a24c 49 var stops_source = {};
JK 50 var stops_layer = {};
f4a54f 51
JK 52 var stop_selected_source = null;
53 var stop_selected_layer = null;
57b8d3 54
8b6250 55 var feature_xhr = null;
JK 56 var feature_timer = null;
9dd2e1 57 var path_xhr = null;
1d4785 58
JK 59 var route_source = null;
60 var route_layer = null;
07c714 61
57b8d3 62 var map = null;
d29c06 63
JK 64 var panel = null;
5be662 65 var find = null;
d29c06 66
57b8d3 67 var fail_element = document.getElementById('fail');
a4d011 68 var fail_text = document.querySelector('#fail span');
7ca6a1 69
d29c06 70
JK 71 function Panel(element) {
72     this._element = element;
73     this._element.classList.add('panel');
74     
ae5170 75     this._hide = addElementWithText(this._element, 'a', '▶');
d29c06 76     this._hide.title = lang.action_collapse;
JK 77     this._hide.className = 'hide';
78     this._hide.addEventListener('click', this.toggleExpanded.bind(this));
79     
ae5170 80     this._close = addElementWithText(this._element, 'a', '×');
d29c06 81     this._close.title = lang.action_close;
JK 82     this._close.className = 'close';
83     this._close.addEventListener('click', this.close.bind(this));
84     
85     this._content = document.createElement('div');
86     this._element.appendChild(this._content);
d5e919 87 }
d29c06 88 Panel.prototype = {
JK 89     _element: null,
90     _hide: null,
91     _close: null,
92     _content: null,
93     
94     _closeCallback: null,
95     _runCallback: function() {
96         var callback = this.closeCallback;
97         this.closeCallback = null;
98         if(callback) callback();
99     },
100     
101     expand: function() {
102         this._element.classList.add('expanded');
103         setText(this._hide, '▶');
104         this._hide.title = lang.action_collapse;
105     },
106     collapse: function() {
107         this._element.classList.remove('expanded');
108         setText(this._hide, '◀');
109         this._hide.title = lang.action_expand;
110     },
111     toggleExpanded: function() {
112         if(this._element.classList.contains('expanded')) {
113             this.collapse();
114         } else {
115             this.expand();
116         }
117     },
118     fail: function(message) {
119         addParaWithText(this._content, message).className = 'error';
120     },
c5a5c3 121     show: function(contents, closeCallback, hashValue) {
JK 122         hash.set(hashValue ? hashValue : '');
123         
d29c06 124         this._runCallback();
JK 125         this.closeCallback = closeCallback;
126         
127         deleteChildren(this._content);
128         
129         this._content.appendChild(contents);
130         this._element.classList.add('enabled');
131         setTimeout(this.expand.bind(this), 1);
132     },
133     close: function() {
134         this._runCallback();
135         this._element.classList.remove('expanded');
136         this._element.classList.remove('enabled');
137     },
138 };
5be662 139
JK 140
141 function Find() {
142     this.div = document.createElement('div');
143     
144     this.form = document.createElement('form');
145     this.div.appendChild(this.form);
146     
147     var para = addParaWithText(this.form, lang.enter_query);
148     para.appendChild(document.createElement('br'));
149     this.input = document.createElement('input');
150     this.input.type = 'text';
151     this.input.style.width = '80%';
152     para.appendChild(this.input);
153     para.appendChild(document.createElement('hr'));
154     
155     this.results = document.createElement('div');
156     this.div.appendChild(this.results);
157     
158     this.input.addEventListener('keyup', this.findDelay.bind(this));
159     this.form.addEventListener('submit', this.findDelay.bind(this));
160 }
161 Find.prototype = {
162     query: '',
163     timeout: null,
164     
165     div: null,
166     form: null,
167     input: null,
168     results: null,
169     
170     find: function() {
171         var query = this.input.value.toUpperCase();
172         if(query === this.query) return;
173         this.query = query;
174         
94177c 175         if(query === '') {
JK 176             deleteChildren(this.results);
177             return;
178         }
179         
5be662 180         var features = [];
JK 181         stops_type.forEach(function(stop_type) {
182             if(stop_type.substr(0,1) === 'p') return;
183             stops_source[stop_type].forEachFeature(function(feature) {
184                 if(feature.get('name').toUpperCase().indexOf(query) > -1) {
185                     features.push(feature);
186                 }
187             });
188         });
189         
190         ttss_types.forEach(function(ttss_type) {
3a4fe8 191             vehicles[ttss_type].source.forEachFeature(function(feature) {
5be662 192                 if(feature.get('vehicle_type') && feature.get('vehicle_type').num.indexOf(query) > -1) {
JK 193                     features.push(feature);
194                 }
195             });
196         });
197         
198         deleteChildren(this.results);
199         this.results.appendChild(listFeatures(features));
200     },
201     findDelay: function(e) {
202         e.preventDefault();
203         if(this.timeout) clearTimeout(this.timeout);
204         this.timeout = setTimeout(this.find.bind(this), 100);
205     },
206     open: function(panel) {
c5a5c3 207         panel.show(this.div, this.close.bind(this), 'f');
5be662 208         this.input.focus();
JK 209     },
210     close: function() {
211         if(this.timeout) clearTimeout(this.timeout);
212     },
213 };
214
2bc9da 215 function Vehicles(prefix) {
JK 216     this.prefix = prefix;
217     this.source = new ol.source.Vector({
218         features: [],
219     });
220     this.layer = new ol.layer.Vector({
221         source: this.source,
222     });
223 }
224 Vehicles.prototype = {
225     prefix: '',
226     
227     layer: null,
228     source: null,
229     
230     lastUpdate: 0,
231     xhr: null,
232     es: null,
233     
234     selectedFeatureId: null,
235     deselectCallback: null,
236     
237     style: function(feature, clicked) {
238         var color_type = 'black';
239         
c5a5c3 240         var vehicleType = feature.get('type');
2bc9da 241         if(vehicleType) {
JK 242             switch(vehicleType.low) {
243                 case 0:
244                     color_type = 'orange';
245                 break;
246                 case 1:
247                 case 2:
248                     color_type = 'green';
249                 break;
250             }
251         }
252         
253         var fill = '#B70';
254         if(this.prefix === 'b') {
255             fill = '#05B';
256         }
257         if(clicked) {
258             fill = '#922';
259         }
260         
261         var image = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="30"><polygon points="10,0 20,23 0,23" style="fill:'+fill+';stroke:'+color_type+';stroke-width:3"/></svg>';
262         
263         feature.setStyle(new ol.style.Style({
264             image: new ol.style.Icon({
265                 src: 'data:image/svg+xml;base64,' + btoa(image),
266                 imgSize: [20,30],
267                 rotation: Math.PI * feature.get('angle') / 180.0,
268             }),
269             text: new ol.style.Text({
270                 font: 'bold 10px sans-serif',
c5a5c3 271                 text: feature.get('line'),
2bc9da 272                 fill: new ol.style.Fill({color: 'white'}),
JK 273             }),
274         }));
275     },
c5a5c3 276     select: function(feature) {
2bc9da 277         if(feature instanceof ol.Feature) {
JK 278             feature = feature.getId();
279         }
280         feature = this.source.getFeatureById(feature);
281         if(!feature) {
282             this.deselect();
283             return;
284         }
285         this.style(feature, true);
286         
287         this.selectedFeatureId = feature.getId();
288     },
289     deselect: function() {
290         if(!this.selectedFeatureId) return false;
291         var feature = this.source.getFeatureById(this.selectedFeatureId);
292         this.style(feature);
293         this.selectedFeatureId = null;
294     },
295
296     typesUpdated: function() {
297         this.source.forEachFeature(function (feature) {
298             this.style(feature);
299         }.bind(this));
300     },
301
302     _newFeature: function(id, data) {
c5a5c3 303         var feature = new ol.Feature(data);
JK 304         feature.set('_', 'v' + this.prefix);
305         feature.setId(id);
306         feature.setGeometry(getGeometryFeature(feature));
2bc9da 307         this.style(feature);
JK 308         return feature;
309     },
c5a5c3 310     _updateFeature: function(feature, vehicle) {
JK 311         Object.keys(vehicle).forEach(function (key) {
312             feature.set(key, deepMerge(feature.get(key), vehicle[key]));
313             if(key === 'lon' || key === 'lat') {
314                 feature.setGeometry(getGeometryFeature(feature));
315             } else if(key === 'angle') {
316                 feature.getStyle().getImage().setRotation(Math.PI * parseFloat(vehicle.angle ? vehicle.angle : 0) / 180.0);
317             } else if(key === 'line') {
318                 // TODO: Special directions
319                 feature.getStyle().getText().setText(vehicle.line);
320             }
321         });
322     },
323     _removeFeature: function(feature) {
324         if(!feature) return;
325         if(this.selectedFeatureId === feature.getId()) {
326             this.deselect();
327         }
01853e 328         this.source.removeFeature(feature);
c5a5c3 329     },
2bc9da 330     loadFullData: function(data) {
c5a5c3 331         var self = this;
2bc9da 332         var features = [];
JK 333         for(var id in data) {
c5a5c3 334             var feature = this.source.getFeatureById(id);
JK 335             if(feature) {
336                 this._updateFeature(feature, data[id]);
337             } else {
338                 features.push(this._newFeature(id, data[id]));
339             }
2bc9da 340         }
JK 341         this.source.addFeatures(features);
c5a5c3 342         this.source.forEachFeature(function(feature) {
JK 343             if(!data[feature.getId()]) {
344                 self._removeFeature(feature);
345             }
346         });
2bc9da 347         
JK 348         if(this.selectedFeatureId) {
349             this.select(this.selectedFeatureId);
350         }
351     },
352     loadDiffData: function(data) {
353         for(var id in data) {
c5a5c3 354             var feature = this.source.getFeatureById(id);
2bc9da 355             var vehicle = data[id];
JK 356             
357             if(vehicle === null) {
c5a5c3 358                 this._removeFeature(feature);
2bc9da 359             } else if(feature) {
c5a5c3 360                 this._updateFeature(feature, vehicle);
2bc9da 361             } else {
JK 362                 this.source.addFeature(this._newFeature(id, data[id]));
363             }
364         }
365     },
366     
367     fetch: function() {
368         var self = this;
c5a5c3 369         var result = this.fetchXhr();
2bc9da 370         
JK 371         // TODO: updates (EventSource)
c5a5c3 372         // TODO: error ahandling (reconnect)
2bc9da 373         // TODO: error handling (indicator)
JK 374         
375         return result;
376     },
c5a5c3 377     fetchXhr: function() {
2bc9da 378         var self = this;
JK 379         this.xhr = $.get(
c5a5c3 380             api_url + '/positions/?type=' + this.prefix + '&last=' + this.lastUpdate
2bc9da 381         ).done(function(data) {
JK 382             try {
42c5bf 383                 if(data['date'] < self.lastUpdate) {
JK 384                     console.log('Data older than lastUpdate!');
385                 }
c5a5c3 386                 if(data['type'] == 'full') {
JK 387                     self.loadFullData(data['pos']);
388                 } else {
389                     self.loadDiffData(data['pos']);
2bc9da 390                 }
42c5bf 391                 self.lastUpdate = data['date'];
c5a5c3 392                 setTimeout(self.fetchXhr.bind(self), api_refresh);
2bc9da 393             } catch(e) {
JK 394                 console.log(e);
395                 throw e;
396             }
397         }).fail(this.failXhr.bind(this));
398         return this.xhr;
399     },
400     
401     failXhr: function(result) {
402         // abort() is not a failure
403         if(result.readyState === 0) return;
404         
405         if(result.status === 0) {
406             fail(lang.error_request_failed_connectivity, result);
c5a5c3 407         } else if(result.status === 304) {
2bc9da 408             fail(lang.error_request_failed_no_data, result);
c5a5c3 409         } else if(result.statusText) {
2bc9da 410             fail(lang.error_request_failed_status.replace('$status', result.statusText), result);
JK 411         } else {
412             fail(lang.error_request_failed, result);
413         }
414     },
415 };
d29c06 416
57b8d3 417 function fail(msg) {
a4d011 418     setText(fail_text, msg);
57b8d3 419     fail_element.style.top = '0.5em';
8b6250 420 }
JK 421
422 function fail_ajax_generic(data, fnc) {
57b8d3 423     // abort() is not a failure
faad2a 424     if(data.readyState === 0) return;
57b8d3 425     
faad2a 426     if(data.status === 0) {
8b6250 427         fnc(lang.error_request_failed_connectivity, data);
57b8d3 428     } else if (data.statusText) {
8b6250 429         fnc(lang.error_request_failed_status.replace('$status', data.statusText), data);
57b8d3 430     } else {
8b6250 431         fnc(lang.error_request_failed, data);
57b8d3 432     }
8b6250 433 }
JK 434
435 function fail_ajax(data) {
436     fail_ajax_generic(data, fail);
437 }
438
439 function fail_ajax_popup(data) {
d29c06 440     fail_ajax_generic(data, panel.fail.bind(panel));
57b8d3 441 }
JK 442
c5a5c3 443 function getGeometryFeature(feature) {
JK 444     return getGeometryPair([feature.get('lon'), feature.get('lat')]);
445 }
2bc9da 446 function getGeometryPair(pair) {
JK 447     return new ol.geom.Point(ol.proj.fromLonLat(pair));
57b8d3 448 }
2bc9da 449 function getGeometry(object) {
JK 450     return getGeometryPair([object.longitude / 3600000.0, object.latitude / 3600000.0]);
1d4785 451 }
JK 452
c5a5c3 453 function markStops(stops, featureSource, routeStyle) {
f4a54f 454     stop_selected_source.clear();
ba6e87 455     
c5a5c3 456     var style = stops_layer['s' + featureSource].getStyle().clone();
f4a54f 457     
JK 458     if(routeStyle) {
459         style.getImage().setRadius(5);
460     } else {
461         style.getImage().getStroke().setWidth(2);
462         style.getImage().getStroke().setColor('#F00');
463         style.getImage().setRadius(5);
ba6e87 464     }
1d4785 465     
f4a54f 466     stop_selected_layer.setStyle(style);
JK 467     
db4410 468     var feature, prefix;
f4a54f 469     for(var i = 0; i < stops.length; i++) {
JK 470         if(stops[i].getId) {
471             feature = stops[i];
472         } else {
c5a5c3 473             feature = stops_source['s' + featureSource].getFeatureById(stops[i]);
f4a54f 474         }
JK 475         if(feature) {
476             stop_selected_source.addFeature(feature);
477         }
1d4785 478     }
JK 479     
f4a54f 480     stop_selected_layer.setVisible(true);
1d4785 481 }
JK 482
483 function unstyleSelectedFeatures() {
f4a54f 484     stop_selected_source.clear();
JK 485     route_source.clear();
2bc9da 486     ttss_types.forEach(function(type) {
JK 487         vehicles[type].deselect();
488     });
57b8d3 489 }
JK 490
88a24c 491 function updateStopSource(stops, prefix) {
7e7221 492     var stop;
57b8d3 493     for(var i = 0; i < stops.length; i++) {
7e7221 494         stop = stops[i];
e61357 495         
c5a5c3 496         var feature = new ol.Feature(stop);
JK 497         feature.setId(stop.id);
498         feature.setGeometry(getGeometryFeature(feature));
e61357 499         
c5a5c3 500         if(feature.get('parent') === null) {
JK 501             feature.set('_', 's' + prefix);
502             stops_source['s' + prefix].addFeature(feature);
1b7c52 503         } else {
c5a5c3 504             feature.set('_', 'p' + prefix);
JK 505             stops_source['p' + prefix].addFeature(feature);
1b7c52 506         }
57b8d3 507     }
JK 508 }
509
c5a5c3 510 function updateStops(ttss_type) {
7ca6a1 511     return $.get(
c5a5c3 512         api_url + '/stops/?type=' + ttss_type
57b8d3 513     ).done(function(data) {
c5a5c3 514         updateStopSource(data, ttss_type);
57b8d3 515     }).fail(fail_ajax);
7ca6a1 516 }
JK 517
7e7221 518 function vehiclePath(feature) {
9dd2e1 519     if(path_xhr) path_xhr.abort();
JK 520     
521     var featureId = feature.getId();
4bfa36 522     var ttss_type = featureId.substr(0, 1);
eafc1c 523     
9dd2e1 524     path_xhr = $.get(
4bfa36 525         ttss_urls[ttss_type] + '/geoserviceDispatcher/services/pathinfo/vehicle'
JK 526             + '?id=' + encodeURIComponent(featureId.substr(1))
9dd2e1 527     ).done(function(data) {
JK 528         if(!data || !data.paths || !data.paths[0] || !data.paths[0].wayPoints) return;
529         
db4410 530         var point;
9dd2e1 531         var points = [];
JK 532         for(var i = 0; i < data.paths[0].wayPoints.length; i++) {
533             point = data.paths[0].wayPoints[i];
534             points.push(ol.proj.fromLonLat([
535                 point.lon / 3600000.0,
536                 point.lat / 3600000.0,
537             ]));
538         }
539         
540         route_source.addFeature(new ol.Feature({
541             geometry: new ol.geom.LineString(points)
542         }));
543         route_layer.setVisible(true);
544     });
2b6454 545     return path_xhr;
9dd2e1 546 }
JK 547
548 function vehicleTable(feature, table) {
549     if(feature_xhr) feature_xhr.abort();
550     if(feature_timer) clearTimeout(feature_timer);
551     
c5a5c3 552     var featureDiscriminator = feature.get('_');
JK 553     var featureType = featureDiscriminator.substr(0, 1);
554     var featureSource = featureDiscriminator.substr(1, 1);
555     var featureStatus = feature.get('status');
eafc1c 556     
8b6250 557     feature_xhr = $.get(
c5a5c3 558         api_url + '/trip/?type=' + featureSource + '&id=' + feature.get('trip')
8b6250 559     ).done(function(data) {
JK 560         deleteChildren(table);
561         
db4410 562         var tr;
f4a54f 563         var stopsToMark = [];
c5a5c3 564         for(var i = 0, il = data.length; i < il; i++) {
db4410 565             tr = document.createElement('tr');
c5a5c3 566             addCellWithText(tr, data[i].time);
JK 567             addCellWithText(tr, (i+1) + '. ' + normalizeName(data[i].name));
1d4785 568             
c5a5c3 569             stopsToMark.push(data[i].stop);
8b6250 570             
c5a5c3 571             if(data[i].seq < feature.get('seq')) {
cb5a77 572                 tr.className = 'active';
c5a5c3 573             } else if(data[i].seq == feature.get('seq') && featureStatus < 2) {
8b6250 574                 tr.className = 'success';
JK 575             }
576             table.appendChild(tr);
577         }
f4a54f 578         
c5a5c3 579         if(data.length === 0) {
b6f8e3 580             tr = document.createElement('tr');
JK 581             table.appendChild(tr);
582             tr = addCellWithText(tr, lang.no_data);
583             tr.colSpan = '2';
584             tr.className = 'active';
585         }
586         
c5a5c3 587         markStops(stopsToMark, featureSource, true);
8b6250 588         
2bc9da 589         feature_timer = setTimeout(function() { vehicleTable(feature, table); }, api_refresh);
8b6250 590     }).fail(fail_ajax_popup);
2b6454 591     return feature_xhr;
8b6250 592 }
JK 593
c5a5c3 594 function stopTable(feature, table) {
8b6250 595     if(feature_xhr) feature_xhr.abort();
JK 596     if(feature_timer) clearTimeout(feature_timer);
eafc1c 597     
c5a5c3 598     var featureDiscriminator = feature.get('_');
JK 599     var featureType = featureDiscriminator.substr(0, 1);
600     var featureSource = featureDiscriminator.substr(1, 1);
601     
8b6250 602     feature_xhr = $.get(
dc9b4f 603         api_url + '/schedule/?type=' + featureSource + '&id=' + feature.getId()
8b6250 604     ).done(function(data) {
JK 605         deleteChildren(table);
606         
db4410 607         var tr, dir_cell, vehicle, status, status_cell, delay, delay_cell;
dc9b4f 608         for(var i = 0, il = data.length; i < il; i++) {
db4410 609             tr = document.createElement('tr');
dc9b4f 610             addCellWithText(tr, data[i].line);
JK 611             dir_cell = addCellWithText(tr, data[i].direction);
c5a5c3 612             //vehicle = vehicles_info.getParsed(all_departures[i].vehicleId);
dc9b4f 613             //dir_cell.appendChild(displayVehicle(vehicle));
JK 614             //status = parseStatus(all_departures[i]);
615             status_cell = addCellWithText(tr, data[i].time);
616             //delay = parseDelay(all_departures[i]);
617             delay_cell = addCellWithText(tr, '');
618             /*
cb5a77 619             if(i < data.old.length) {
db4410 620                 tr.className = 'active';
cb5a77 621             } else if(status === lang.boarding_sign) {
8b6250 622                 tr.className = 'success';
JK 623                 status_cell.className = 'status-boarding';
624             } else if(parseInt(delay) > 9) {
625                 tr.className = 'danger';
626                 delay_cell.className = 'status-delayed';
627             } else if(parseInt(delay) > 3) {
628                 tr.className = 'warning';
629             }
dc9b4f 630             */
8b6250 631             table.appendChild(tr);
JK 632         }
633         
c5a5c3 634         feature_timer = setTimeout(function() { stopTable(feature, table); }, api_refresh);
8b6250 635     }).fail(fail_ajax_popup);
2b6454 636     return feature_xhr;
8b6250 637 }
JK 638
7ca6a1 639 function featureClicked(feature) {
c5a5c3 640     if(!feature || !feature.getId() || !feature.get('_')) {
JK 641         feature = null;
642     }
1d4785 643     
JK 644     unstyleSelectedFeatures();
645     
7ca6a1 646     if(!feature) {
d29c06 647         panel.close();
7ca6a1 648         return;
JK 649     }
650     
c5a5c3 651     var featureDiscriminator = feature.get('_');
JK 652     var featureType = featureDiscriminator.substr(0, 1);
653     var featureSource = featureDiscriminator.substr(1, 1);
654     
9f0f6a 655     var div = document.createElement('div');
8b6250 656     
c5a5c3 657     var name = normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir'));
07c714 658     var additional;
8b6250 659     var table = document.createElement('table');
JK 660     var thead = document.createElement('thead');
661     var tbody = document.createElement('tbody');
662     table.appendChild(thead);
663     table.appendChild(tbody);
07c714 664     
a4d011 665     var tabular_data = true;
JK 666     
c5a5c3 667     var typeName = lang.types[featureDiscriminator];
76f5c4 668     if(typeof typeName === 'undefined') {
JK 669         typeName = '';
670     }
671     
4bfa36 672     // Location
c5a5c3 673     if(featureType == 'l') {
4bfa36 674         tabular_data = false;
76f5c4 675         name = typeName;
4bfa36 676         typeName = '';
JK 677     }
678     // Vehicle
c5a5c3 679     else if(featureType == 'v') {
JK 680         var span = displayVehicle(feature.get('type'));
4bfa36 681         
JK 682         additional = document.createElement('p');
683         if(span.title) {
684             setText(additional, span.title);
685         } else {
686             setText(additional, feature.getId());
687         }
688         additional.insertBefore(span, additional.firstChild);
689         
690         addElementWithText(thead, 'th', lang.header_time);
691         addElementWithText(thead, 'th', lang.header_stop);
692         
693         vehicleTable(feature, tbody);
c5a5c3 694         //vehiclePath(feature);
4bfa36 695     }
JK 696     // Stop or stop point
c5a5c3 697     else if(['s', 'p'].includes(featureType)) {
JK 698         if(featureType == 's') {
1b7c52 699             var second_type = lang.departures_for_buses;
c5a5c3 700             var source = stops_source['sb'];
4bfa36 701             
c5a5c3 702             if(featureSource == 'b') {
1b7c52 703                 second_type = lang.departures_for_trams;
c5a5c3 704                 source = stops_source['st'];
1b7c52 705             }
0ba749 706             
c5a5c3 707             stopTable(feature, tbody);
1b7c52 708             
c5a5c3 709             var second = source.getFeatureById(feature.get('id'));
JK 710             if(second) {
1b7c52 711                 additional = document.createElement('p');
JK 712                 additional.className = 'small';
713                 addElementWithText(additional, 'a', second_type).addEventListener(
714                     'click',
715                     function() {
c5a5c3 716                         featureClicked(second);
1b7c52 717                     }
JK 718                 );
a83099 719             }
4bfa36 720         } else {
c5a5c3 721             stopTable(feature, tbody);
8b6250 722             
JK 723             additional = document.createElement('p');
724             additional.className = 'small';
725             addElementWithText(additional, 'a', lang.departures_for_stop).addEventListener(
726                 'click',
727                 function() {
c5a5c3 728                     featureClicked(stops_source['s' + featureSource].getFeatureById(feature.get('parent')));
8b6250 729                 }
JK 730             );
4bfa36 731         }
JK 732         
733         addElementWithText(thead, 'th', lang.header_line);
734         addElementWithText(thead, 'th', lang.header_direction);
735         addElementWithText(thead, 'th', lang.header_time);
736         addElementWithText(thead, 'th', lang.header_delay);
737     } else {
738         panel.close();
739         return;
07c714 740     }
8b6250 741     
JK 742     var loader = addElementWithText(tbody, 'td', lang.loading);
743     loader.className = 'active';
ee4e7c 744     loader.colSpan = thead.childNodes.length;
07c714 745     
4bfa36 746     addParaWithText(div, typeName).className = 'type';
ae3207 747     
JK 748     var nameElement = addParaWithText(div, name + ' ');
749     nameElement.className = 'name';
750     
751     var showOnMapElement = addElementWithText(nameElement, 'a', lang.show_on_map);
752     var showOnMapFunction = function() {
753         setTimeout(function () {map.getView().animate({
754             center: feature.getGeometry().getCoordinates(),
755         })}, 10);
756     };
757     showOnMapElement.addEventListener('click', showOnMapFunction);
20d39d 758     showOnMapElement.className = 'icon icon-pin';
ae3207 759     showOnMapElement.title = lang.show_on_map;
07c714 760     
JK 761     if(additional) {
9f0f6a 762         div.appendChild(additional);
7ca6a1 763     }
JK 764     
a4d011 765     if(tabular_data) {
JK 766         div.appendChild(table);
767     }
7ca6a1 768     
ae3207 769     showOnMapFunction();
9f0f6a 770     
d29c06 771     panel.show(div, function() {
2bc9da 772         unstyleSelectedFeatures();
JK 773         
774         if(path_xhr) path_xhr.abort();
775         if(feature_xhr) feature_xhr.abort();
776         if(feature_timer) clearTimeout(feature_timer);
c5a5c3 777     }, tabular_data ? featureDiscriminator + feature.getId() : '');
07c714 778     
c5a5c3 779     if(featureType == 'v') {
JK 780         vehicles[featureSource].select(feature);
781     } else if(['s', 'p'].includes(featureType)) {
782         markStops([feature], featureSource);
783     }
a4d011 784 }
JK 785
5be662 786 function listFeatures(features) {
JK 787     var div = document.createElement('div');
788     
d5e919 789     if(features.length === 0) {
94177c 790         addParaWithText(div, lang.no_results);
JK 791         return div;
792     }
793     
5be662 794     addParaWithText(div, lang.select_feature);
JK 795     
c5a5c3 796     var feature, p, a, featureDiscriminator, typeName;
5be662 797     for(var i = 0; i < features.length; i++) {
JK 798         feature = features[i];
799         
800         p = document.createElement('p');
801         a = document.createElement('a');
802         p.appendChild(a);
803         a.addEventListener('click', function(feature) { return function() {
804             featureClicked(feature);
805         }}(feature));
806         
c5a5c3 807         featureDiscriminator = feature.get('_');
JK 808         typeName = lang.types[featureDiscriminator];
5be662 809         if(typeof typeName === 'undefined') {
JK 810             typeName = '';
811         }
c5a5c3 812         if(feature.get('type')) {
JK 813             typeName += ' ' + feature.get('type').num;
5be662 814         }
JK 815         
816         addElementWithText(a, 'span', typeName).className = 'small';
817         a.appendChild(document.createTextNode(' '));
c5a5c3 818         addElementWithText(a, 'span', normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir')));
5be662 819         
JK 820         div.appendChild(p);
821     }
822     
823     return div;
824 }
825
a4d011 826 function mapClicked(e) {
JK 827     var point = e.coordinate;
828     var features = [];
829     map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
830         if(layer == stop_selected_layer) return;
831         if(feature.getId()) features.push(feature);
832     });
833     
7e7221 834     var feature = features[0];
JK 835     
a4d011 836     if(features.length > 1) {
5be662 837         panel.show(listFeatures(features));
a4d011 838         return;
JK 839     }
840     
841     if(!feature) {
88a24c 842         stops_type.forEach(function(type) {
JK 843             if(stops_layer[type].getVisible()) {
844                 feature = returnClosest(point, feature, stops_source[type].getClosestFeatureToCoordinate(point));
845             }
846         });
4bfa36 847         ttss_types.forEach(function(type) {
2bc9da 848             if(vehicles[type].layer.getVisible()) {
JK 849                 feature = returnClosest(point, feature, vehicles[type].source.getClosestFeatureToCoordinate(point));
4bfa36 850             }
JK 851         });
a4d011 852         
JK 853         if(getDistance(point, feature) > map.getView().getResolution() * 20) {
854             feature = null;
855         }
856     }
857     
858     featureClicked(feature);
859 }
860
861 function trackingStop() {
d29c06 862     geolocation_button.classList.remove('clicked');
a4d011 863     geolocation.setTracking(false);
JK 864     
865     geolocation_source.clear();
866 }
867 function trackingStart() {
868     geolocation_set = 0;
d29c06 869     geolocation_button.classList.add('clicked');
a4d011 870     geolocation_feature.setGeometry(new ol.geom.Point(map.getView().getCenter()));
JK 871     geolocation_accuracy.setGeometry(new ol.geom.Circle(map.getView().getCenter(), 100000));
872     
873     geolocation_source.addFeature(geolocation_feature);
874     geolocation_source.addFeature(geolocation_accuracy);
875     
876     geolocation.setTracking(true);
877 }
878 function trackingToggle() {
879     if(geolocation.getTracking()) {
880         trackingStop();
881     } else {
882         trackingStart();
883     }
7ca6a1 884 }
JK 885
2bc9da 886 function Hash() {
57b8d3 887 }
2bc9da 888 Hash.prototype = {
JK 889     _ignoreChange: false,
890     
891     _set: function(id) {
892         var value = '#!' + id;
893         if(value !== window.location.hash) {
894             window.location.hash = value;
895             return true;
896         }
897         return false;
898     },
899     _updateOld: function() {
c5a5c3 900         if(window.location.hash.match(/^#![bt][0-9]{3}$/)) {
JK 901             this.go('v' + window.location.hash.substr(2));
902         } else if(window.location.hash.match(/^#![RHrh][A-Za-z][0-9]{3}$/)) {
903             this.go('vt'+ window.location.hash.substr(4));
904         } else if(window.location.hash.match(/^#![BDPbdp][A-Za-z][0-9]{3}$/)) {
905             this.go('vb'+ window.location.hash.substr(4));
2bc9da 906         }
JK 907     },
908     ready: function() {
909         this._updateOld();
910         this.changed();
c5a5c3 911         window.addEventListener('hashchange', this.changed.bind(this), false);
2bc9da 912     },
JK 913     go: function(id) {
914         this._ignoreChange = false;
915         return this._set(id);
916     },
917     set: function(id) {
918         this._ignoreChange = true;
919         return this._set(id);
920     },
921     changed: function() {
922         if(this._ignoreChange) {
923             this._ignoreChange = false;
924             return false;
925         }
926         
927         var feature = null;
c5a5c3 928         var source = null;
2bc9da 929         var vehicleId = null;
JK 930         var stopId = null;
931         
c5a5c3 932         if(window.location.hash.match(/^#!v[tb][0-9]+$/)) {
JK 933             vehicleId = window.location.hash.substr(3);
934         } else if(window.location.hash.match(/^#![sp][tb][0-9a-z_]+$/)) {
2bc9da 935             stopId = window.location.hash.substr(2);
JK 936         } else if(window.location.hash.match(/^#!f$/)) {
937             find.open(panel);
938             return;
939         }
940         
941         if(vehicleId) {
c5a5c3 942             feature = vehicles[vehicleId.substr(0,1)].source.getFeatureById(vehicleId.substr(1));
2bc9da 943         } else if(stopId) {
c5a5c3 944             feature = stops_source[stopId.substr(0,2)].getFeatureById(stopId.substr(2));
2bc9da 945         }
JK 946         
947         featureClicked(feature);
948         
949         return true;
950     },
951 };
57b8d3 952
0e60d1 953 function getDistance(c1, c2) {
JK 954     if(c1.getGeometry) {
955         c1 = c1.getGeometry().getCoordinates();
956     }
957     if(c2.getGeometry) {
958         c2 = c2.getGeometry().getCoordinates();
959     }
960     
2bc9da 961     c1 = ol.proj.transform(c1, 'EPSG:3857', 'EPSG:4326');
JK 962     c2 = ol.proj.transform(c2, 'EPSG:3857', 'EPSG:4326');
a8a6d1 963     return ol.sphere.getDistance(c1, c2);
0e60d1 964 }
JK 965
966 function returnClosest(point, f1, f2) {
967     if(!f1) return f2;
968     if(!f2) return f1;
969     
1b7c52 970     return (getDistance(point, f1) <= getDistance(point, f2)) ? f1 : f2;
0e60d1 971 }
JK 972
57b8d3 973 function init() {
d29c06 974     panel = new Panel(document.getElementById('panel'));
5be662 975     find = new Find();
57b8d3 976     
4bfa36 977     route_source = new ol.source.Vector({
2bc9da 978         attributions: [lang.help_data_attribution],
4bfa36 979         features: [],
JK 980     });
981     route_layer = new ol.layer.Vector({
982         source: route_source,
983         style: new ol.style.Style({
984             stroke: new ol.style.Stroke({ color: [255, 153, 0, .8], width: 5 })
985         }),
986     });
987     
88a24c 988     stops_type.forEach(function(type) {
JK 989         stops_source[type] = new ol.source.Vector({
990             features: [],
991         });
992         stops_layer[type] = new ol.layer.Vector({
993             source: stops_source[type],
994             renderMode: 'image',
995             style: stops_style[type],
996         });
1b7c52 997         stops_mapping[type] = {};
f4a54f 998     });
JK 999     
1000     stop_selected_source = new ol.source.Vector({
1001         features: [],
1002     });
1003     stop_selected_layer = new ol.layer.Vector({
1004         source: stop_selected_source,
57b8d3 1005         visible: false,
JK 1006     });
1007     
4bfa36 1008     ttss_types.forEach(function(type) {
2bc9da 1009         vehicles[type] = new Vehicles(type);
1d4785 1010     });
JK 1011     
a4d011 1012     geolocation_feature = new ol.Feature({
JK 1013         name: '',
1014         style: new ol.style.Style({
1015             image: new ol.style.Circle({
1016                 fill: new ol.style.Fill({color: '#39C'}),
1017                 stroke: new ol.style.Stroke({color: '#FFF', width: 2}),
1018                 radius: 5,
1019             }),
1020         }),
1021     });
1022     geolocation_feature.setId('location_point');
1023     geolocation_accuracy = new ol.Feature();
1024     geolocation_source = new ol.source.Vector({
1025         features: [],
1026     });
1027     geolocation_layer = new ol.layer.Vector({
1028         source: geolocation_source,
1029     });
19a338 1030     geolocation_button = document.querySelector('#track');
a4d011 1031     if(!navigator.geolocation) {
19a338 1032         geolocation_button.remove();
a4d011 1033     }
JK 1034     
376c6e 1035     geolocation = new ol.Geolocation({projection: 'EPSG:3857'});
a4d011 1036     geolocation.on('change:position', function() {
JK 1037         var coordinates = geolocation.getPosition();
1038         geolocation_feature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
1039         if(geolocation_set < 1) {
1040             geolocation_set = 1;
1041             map.getView().animate({
1042                 center: coordinates,
1043             })
1044         }
1045     });
1046     geolocation.on('change:accuracyGeometry', function() {
1047         var accuracy = geolocation.getAccuracyGeometry();
1048         geolocation_accuracy.setGeometry(accuracy);
1049         if(geolocation_set < 2) {
1050             geolocation_set = 2;
1051             map.getView().fit(accuracy);
1052         }
1053     });
1054     geolocation.on('error', function(error) {
1055         fail(lang.error_location + ' ' + error.message);
1056         trackingStop();
19a338 1057         geolocation_button.remove();
a4d011 1058     });
JK 1059     geolocation_button.addEventListener('click', trackingToggle);
1060     
5be662 1061     document.getElementById('find').addEventListener('click', find.open.bind(find, panel));
2bc9da 1062
JK 1063     var pixelRatio = ol.has.DEVICE_PIXEL_RATIO > 1 ? 2 : 1;
4bfa36 1064     var layers = [
JK 1065         new ol.layer.Tile({
2bc9da 1066             source: new ol.source.XYZ({
JK 1067                 attributions: [ol.source.OSM.ATTRIBUTION],
1068                 url: 'https://tiles.ttss.pl/x' + pixelRatio + '/{z}/{x}/{y}.png',
1069                 maxZoom: 19,
1070                 tilePixelRatio: pixelRatio,
a09b8a 1071                 opaque: false,
428023 1072             }),
4bfa36 1073         }),
JK 1074         route_layer,
1075         geolocation_layer,
1076     ];
1077     stops_type.forEach(function(type) {
1078         layers.push(stops_layer[type]);
1079     });
1080     layers.push(stop_selected_layer);
1081     ttss_types.forEach(function(type) {
2bc9da 1082         layers.push(vehicles[type].layer);
4bfa36 1083     });
57b8d3 1084     map = new ol.Map({
JK 1085         target: 'map',
4bfa36 1086         layers: layers,
57b8d3 1087         view: new ol.View({
JK 1088             center: ol.proj.fromLonLat([19.94, 50.06]),
a4d011 1089             zoom: 14,
JK 1090             maxZoom: 19,
a09b8a 1091             constrainResolution: true,
57b8d3 1092         }),
JK 1093         controls: ol.control.defaults({
1094             attributionOptions: ({
1095                 collapsible: false,
1096             })
1097         }).extend([
1098             new ol.control.Control({
1099                 element: document.getElementById('title'),
1100             }),
1101             new ol.control.Control({
1102                 element: fail_element,
a4d011 1103             }),
JK 1104             new ol.control.Control({
19a338 1105                 element: document.getElementById('menu'),
a4d011 1106             }),
57b8d3 1107         ]),
f4a54f 1108         loadTilesWhileAnimating: false,
57b8d3 1109     });
JK 1110     
1111     // Display popup on click
a4d011 1112     map.on('singleclick', mapClicked);
9f0f6a 1113     
JK 1114     fail_element.addEventListener('click', function() {
1115         fail_element.style.top = '-10em';
1116     });
f0bae0 1117     
57b8d3 1118     // Change mouse cursor when over marker
JK 1119     map.on('pointermove', function(e) {
1120         var hit = map.hasFeatureAtPixel(e.pixel);
1121         var target = map.getTargetElement();
1122         target.style.cursor = hit ? 'pointer' : '';
1123     });
1124     
1125     // Change layer visibility on zoom
7e7221 1126     var change_resolution = function() {
88a24c 1127         stops_type.forEach(function(type) {
JK 1128             if(type.startsWith('p')) {
1129                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1130                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1131             }
1132         });
1133     };
1134     map.getView().on('change:resolution', change_resolution);
1135     change_resolution();
57b8d3 1136     
c5a5c3 1137     var future_requests = [];
4bfa36 1138     ttss_types.forEach(function(type) {
2bc9da 1139         future_requests.push(vehicles[type].fetch());
c5a5c3 1140         future_requests.push(updateStops(type));
4bfa36 1141     });
7ca6a1 1142     
2bc9da 1143     hash = new Hash();
JK 1144     Deferred.all(future_requests).done(hash.ready.bind(hash));
57b8d3 1145 }
JK 1146
1147 init();