Improved www.ttss.krakow.pl
Jacek Kowalski
2020-11-02 01853e8919f80dd24d7864b2f5a4232cf475b5dc
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(
c5a5c3 603         api_url + '/stop/?type=' + featureSource + '&id=' + feature.getId()
8b6250 604     ).done(function(data) {
JK 605         deleteChildren(table);
606         
cb5a77 607         var all_departures = data.old.concat(data.actual);
db4410 608         var tr, dir_cell, vehicle, status, status_cell, delay, delay_cell;
cb5a77 609         for(var i = 0, il = all_departures.length; i < il; i++) {
db4410 610             tr = document.createElement('tr');
cb5a77 611             addCellWithText(tr, all_departures[i].patternText);
ca42d3 612             dir_cell = addCellWithText(tr, normalizeName(all_departures[i].direction));
c5a5c3 613             //vehicle = vehicles_info.getParsed(all_departures[i].vehicleId);
8b6250 614             dir_cell.appendChild(displayVehicle(vehicle));
cb5a77 615             status = parseStatus(all_departures[i]);
db4410 616             status_cell = addCellWithText(tr, status);
cb5a77 617             delay = parseDelay(all_departures[i]);
db4410 618             delay_cell = addCellWithText(tr, delay);
8b6250 619             
cb5a77 620             if(i < data.old.length) {
db4410 621                 tr.className = 'active';
cb5a77 622             } else if(status === lang.boarding_sign) {
8b6250 623                 tr.className = 'success';
JK 624                 status_cell.className = 'status-boarding';
625             } else if(parseInt(delay) > 9) {
626                 tr.className = 'danger';
627                 delay_cell.className = 'status-delayed';
628             } else if(parseInt(delay) > 3) {
629                 tr.className = 'warning';
630             }
631             
632             table.appendChild(tr);
633         }
634         
c5a5c3 635         feature_timer = setTimeout(function() { stopTable(feature, table); }, api_refresh);
8b6250 636     }).fail(fail_ajax_popup);
2b6454 637     return feature_xhr;
8b6250 638 }
JK 639
7ca6a1 640 function featureClicked(feature) {
c5a5c3 641     if(!feature || !feature.getId() || !feature.get('_')) {
JK 642         feature = null;
643     }
1d4785 644     
JK 645     unstyleSelectedFeatures();
646     
7ca6a1 647     if(!feature) {
d29c06 648         panel.close();
7ca6a1 649         return;
JK 650     }
651     
c5a5c3 652     var featureDiscriminator = feature.get('_');
JK 653     var featureType = featureDiscriminator.substr(0, 1);
654     var featureSource = featureDiscriminator.substr(1, 1);
655     
9f0f6a 656     var div = document.createElement('div');
8b6250 657     
c5a5c3 658     var name = normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir'));
07c714 659     var additional;
8b6250 660     var table = document.createElement('table');
JK 661     var thead = document.createElement('thead');
662     var tbody = document.createElement('tbody');
663     table.appendChild(thead);
664     table.appendChild(tbody);
07c714 665     
a4d011 666     var tabular_data = true;
JK 667     
c5a5c3 668     var typeName = lang.types[featureDiscriminator];
76f5c4 669     if(typeof typeName === 'undefined') {
JK 670         typeName = '';
671     }
672     
4bfa36 673     // Location
c5a5c3 674     if(featureType == 'l') {
4bfa36 675         tabular_data = false;
76f5c4 676         name = typeName;
4bfa36 677         typeName = '';
JK 678     }
679     // Vehicle
c5a5c3 680     else if(featureType == 'v') {
JK 681         var span = displayVehicle(feature.get('type'));
4bfa36 682         
JK 683         additional = document.createElement('p');
684         if(span.title) {
685             setText(additional, span.title);
686         } else {
687             setText(additional, feature.getId());
688         }
689         additional.insertBefore(span, additional.firstChild);
690         
691         addElementWithText(thead, 'th', lang.header_time);
692         addElementWithText(thead, 'th', lang.header_stop);
693         
694         vehicleTable(feature, tbody);
c5a5c3 695         //vehiclePath(feature);
4bfa36 696     }
JK 697     // Stop or stop point
c5a5c3 698     else if(['s', 'p'].includes(featureType)) {
JK 699         if(featureType == 's') {
1b7c52 700             var second_type = lang.departures_for_buses;
c5a5c3 701             var source = stops_source['sb'];
4bfa36 702             
c5a5c3 703             if(featureSource == 'b') {
1b7c52 704                 second_type = lang.departures_for_trams;
c5a5c3 705                 source = stops_source['st'];
1b7c52 706             }
0ba749 707             
c5a5c3 708             stopTable(feature, tbody);
1b7c52 709             
c5a5c3 710             var second = source.getFeatureById(feature.get('id'));
JK 711             if(second) {
1b7c52 712                 additional = document.createElement('p');
JK 713                 additional.className = 'small';
714                 addElementWithText(additional, 'a', second_type).addEventListener(
715                     'click',
716                     function() {
c5a5c3 717                         featureClicked(second);
1b7c52 718                     }
JK 719                 );
a83099 720             }
4bfa36 721         } else {
c5a5c3 722             stopTable(feature, tbody);
8b6250 723             
JK 724             additional = document.createElement('p');
725             additional.className = 'small';
726             addElementWithText(additional, 'a', lang.departures_for_stop).addEventListener(
727                 'click',
728                 function() {
c5a5c3 729                     featureClicked(stops_source['s' + featureSource].getFeatureById(feature.get('parent')));
8b6250 730                 }
JK 731             );
4bfa36 732         }
JK 733         
734         addElementWithText(thead, 'th', lang.header_line);
735         addElementWithText(thead, 'th', lang.header_direction);
736         addElementWithText(thead, 'th', lang.header_time);
737         addElementWithText(thead, 'th', lang.header_delay);
738     } else {
739         panel.close();
740         return;
07c714 741     }
8b6250 742     
JK 743     var loader = addElementWithText(tbody, 'td', lang.loading);
744     loader.className = 'active';
ee4e7c 745     loader.colSpan = thead.childNodes.length;
07c714 746     
4bfa36 747     addParaWithText(div, typeName).className = 'type';
ae3207 748     
JK 749     var nameElement = addParaWithText(div, name + ' ');
750     nameElement.className = 'name';
751     
752     var showOnMapElement = addElementWithText(nameElement, 'a', lang.show_on_map);
753     var showOnMapFunction = function() {
754         setTimeout(function () {map.getView().animate({
755             center: feature.getGeometry().getCoordinates(),
756         })}, 10);
757     };
758     showOnMapElement.addEventListener('click', showOnMapFunction);
20d39d 759     showOnMapElement.className = 'icon icon-pin';
ae3207 760     showOnMapElement.title = lang.show_on_map;
07c714 761     
JK 762     if(additional) {
9f0f6a 763         div.appendChild(additional);
7ca6a1 764     }
JK 765     
a4d011 766     if(tabular_data) {
JK 767         div.appendChild(table);
768     }
7ca6a1 769     
ae3207 770     showOnMapFunction();
9f0f6a 771     
d29c06 772     panel.show(div, function() {
2bc9da 773         unstyleSelectedFeatures();
JK 774         
775         if(path_xhr) path_xhr.abort();
776         if(feature_xhr) feature_xhr.abort();
777         if(feature_timer) clearTimeout(feature_timer);
c5a5c3 778     }, tabular_data ? featureDiscriminator + feature.getId() : '');
07c714 779     
c5a5c3 780     if(featureType == 'v') {
JK 781         vehicles[featureSource].select(feature);
782     } else if(['s', 'p'].includes(featureType)) {
783         markStops([feature], featureSource);
784     }
a4d011 785 }
JK 786
5be662 787 function listFeatures(features) {
JK 788     var div = document.createElement('div');
789     
d5e919 790     if(features.length === 0) {
94177c 791         addParaWithText(div, lang.no_results);
JK 792         return div;
793     }
794     
5be662 795     addParaWithText(div, lang.select_feature);
JK 796     
c5a5c3 797     var feature, p, a, featureDiscriminator, typeName;
5be662 798     for(var i = 0; i < features.length; i++) {
JK 799         feature = features[i];
800         
801         p = document.createElement('p');
802         a = document.createElement('a');
803         p.appendChild(a);
804         a.addEventListener('click', function(feature) { return function() {
805             featureClicked(feature);
806         }}(feature));
807         
c5a5c3 808         featureDiscriminator = feature.get('_');
JK 809         typeName = lang.types[featureDiscriminator];
5be662 810         if(typeof typeName === 'undefined') {
JK 811             typeName = '';
812         }
c5a5c3 813         if(feature.get('type')) {
JK 814             typeName += ' ' + feature.get('type').num;
5be662 815         }
JK 816         
817         addElementWithText(a, 'span', typeName).className = 'small';
818         a.appendChild(document.createTextNode(' '));
c5a5c3 819         addElementWithText(a, 'span', normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir')));
5be662 820         
JK 821         div.appendChild(p);
822     }
823     
824     return div;
825 }
826
a4d011 827 function mapClicked(e) {
JK 828     var point = e.coordinate;
829     var features = [];
830     map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
831         if(layer == stop_selected_layer) return;
832         if(feature.getId()) features.push(feature);
833     });
834     
7e7221 835     var feature = features[0];
JK 836     
a4d011 837     if(features.length > 1) {
5be662 838         panel.show(listFeatures(features));
a4d011 839         return;
JK 840     }
841     
842     if(!feature) {
88a24c 843         stops_type.forEach(function(type) {
JK 844             if(stops_layer[type].getVisible()) {
845                 feature = returnClosest(point, feature, stops_source[type].getClosestFeatureToCoordinate(point));
846             }
847         });
4bfa36 848         ttss_types.forEach(function(type) {
2bc9da 849             if(vehicles[type].layer.getVisible()) {
JK 850                 feature = returnClosest(point, feature, vehicles[type].source.getClosestFeatureToCoordinate(point));
4bfa36 851             }
JK 852         });
a4d011 853         
JK 854         if(getDistance(point, feature) > map.getView().getResolution() * 20) {
855             feature = null;
856         }
857     }
858     
859     featureClicked(feature);
860 }
861
862 function trackingStop() {
d29c06 863     geolocation_button.classList.remove('clicked');
a4d011 864     geolocation.setTracking(false);
JK 865     
866     geolocation_source.clear();
867 }
868 function trackingStart() {
869     geolocation_set = 0;
d29c06 870     geolocation_button.classList.add('clicked');
a4d011 871     geolocation_feature.setGeometry(new ol.geom.Point(map.getView().getCenter()));
JK 872     geolocation_accuracy.setGeometry(new ol.geom.Circle(map.getView().getCenter(), 100000));
873     
874     geolocation_source.addFeature(geolocation_feature);
875     geolocation_source.addFeature(geolocation_accuracy);
876     
877     geolocation.setTracking(true);
878 }
879 function trackingToggle() {
880     if(geolocation.getTracking()) {
881         trackingStop();
882     } else {
883         trackingStart();
884     }
7ca6a1 885 }
JK 886
2bc9da 887 function Hash() {
57b8d3 888 }
2bc9da 889 Hash.prototype = {
JK 890     _ignoreChange: false,
891     
892     _set: function(id) {
893         var value = '#!' + id;
894         if(value !== window.location.hash) {
895             window.location.hash = value;
896             return true;
897         }
898         return false;
899     },
900     _updateOld: function() {
c5a5c3 901         if(window.location.hash.match(/^#![bt][0-9]{3}$/)) {
JK 902             this.go('v' + window.location.hash.substr(2));
903         } else if(window.location.hash.match(/^#![RHrh][A-Za-z][0-9]{3}$/)) {
904             this.go('vt'+ window.location.hash.substr(4));
905         } else if(window.location.hash.match(/^#![BDPbdp][A-Za-z][0-9]{3}$/)) {
906             this.go('vb'+ window.location.hash.substr(4));
2bc9da 907         }
JK 908     },
909     ready: function() {
910         this._updateOld();
911         this.changed();
c5a5c3 912         window.addEventListener('hashchange', this.changed.bind(this), false);
2bc9da 913     },
JK 914     go: function(id) {
915         this._ignoreChange = false;
916         return this._set(id);
917     },
918     set: function(id) {
919         this._ignoreChange = true;
920         return this._set(id);
921     },
922     changed: function() {
923         if(this._ignoreChange) {
924             this._ignoreChange = false;
925             return false;
926         }
927         
928         var feature = null;
c5a5c3 929         var source = null;
2bc9da 930         var vehicleId = null;
JK 931         var stopId = null;
932         
c5a5c3 933         if(window.location.hash.match(/^#!v[tb][0-9]+$/)) {
JK 934             vehicleId = window.location.hash.substr(3);
935         } else if(window.location.hash.match(/^#![sp][tb][0-9a-z_]+$/)) {
2bc9da 936             stopId = window.location.hash.substr(2);
JK 937         } else if(window.location.hash.match(/^#!f$/)) {
938             find.open(panel);
939             return;
940         }
941         
942         if(vehicleId) {
c5a5c3 943             feature = vehicles[vehicleId.substr(0,1)].source.getFeatureById(vehicleId.substr(1));
2bc9da 944         } else if(stopId) {
c5a5c3 945             feature = stops_source[stopId.substr(0,2)].getFeatureById(stopId.substr(2));
2bc9da 946         }
JK 947         
948         featureClicked(feature);
949         
950         return true;
951     },
952 };
57b8d3 953
0e60d1 954 function getDistance(c1, c2) {
JK 955     if(c1.getGeometry) {
956         c1 = c1.getGeometry().getCoordinates();
957     }
958     if(c2.getGeometry) {
959         c2 = c2.getGeometry().getCoordinates();
960     }
961     
2bc9da 962     c1 = ol.proj.transform(c1, 'EPSG:3857', 'EPSG:4326');
JK 963     c2 = ol.proj.transform(c2, 'EPSG:3857', 'EPSG:4326');
a8a6d1 964     return ol.sphere.getDistance(c1, c2);
0e60d1 965 }
JK 966
967 function returnClosest(point, f1, f2) {
968     if(!f1) return f2;
969     if(!f2) return f1;
970     
1b7c52 971     return (getDistance(point, f1) <= getDistance(point, f2)) ? f1 : f2;
0e60d1 972 }
JK 973
57b8d3 974 function init() {
d29c06 975     panel = new Panel(document.getElementById('panel'));
5be662 976     find = new Find();
57b8d3 977     
4bfa36 978     route_source = new ol.source.Vector({
2bc9da 979         attributions: [lang.help_data_attribution],
4bfa36 980         features: [],
JK 981     });
982     route_layer = new ol.layer.Vector({
983         source: route_source,
984         style: new ol.style.Style({
985             stroke: new ol.style.Stroke({ color: [255, 153, 0, .8], width: 5 })
986         }),
987     });
988     
88a24c 989     stops_type.forEach(function(type) {
JK 990         stops_source[type] = new ol.source.Vector({
991             features: [],
992         });
993         stops_layer[type] = new ol.layer.Vector({
994             source: stops_source[type],
995             renderMode: 'image',
996             style: stops_style[type],
997         });
1b7c52 998         stops_mapping[type] = {};
f4a54f 999     });
JK 1000     
1001     stop_selected_source = new ol.source.Vector({
1002         features: [],
1003     });
1004     stop_selected_layer = new ol.layer.Vector({
1005         source: stop_selected_source,
57b8d3 1006         visible: false,
JK 1007     });
1008     
4bfa36 1009     ttss_types.forEach(function(type) {
2bc9da 1010         vehicles[type] = new Vehicles(type);
1d4785 1011     });
JK 1012     
a4d011 1013     geolocation_feature = new ol.Feature({
JK 1014         name: '',
1015         style: new ol.style.Style({
1016             image: new ol.style.Circle({
1017                 fill: new ol.style.Fill({color: '#39C'}),
1018                 stroke: new ol.style.Stroke({color: '#FFF', width: 2}),
1019                 radius: 5,
1020             }),
1021         }),
1022     });
1023     geolocation_feature.setId('location_point');
1024     geolocation_accuracy = new ol.Feature();
1025     geolocation_source = new ol.source.Vector({
1026         features: [],
1027     });
1028     geolocation_layer = new ol.layer.Vector({
1029         source: geolocation_source,
1030     });
19a338 1031     geolocation_button = document.querySelector('#track');
a4d011 1032     if(!navigator.geolocation) {
19a338 1033         geolocation_button.remove();
a4d011 1034     }
JK 1035     
376c6e 1036     geolocation = new ol.Geolocation({projection: 'EPSG:3857'});
a4d011 1037     geolocation.on('change:position', function() {
JK 1038         var coordinates = geolocation.getPosition();
1039         geolocation_feature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
1040         if(geolocation_set < 1) {
1041             geolocation_set = 1;
1042             map.getView().animate({
1043                 center: coordinates,
1044             })
1045         }
1046     });
1047     geolocation.on('change:accuracyGeometry', function() {
1048         var accuracy = geolocation.getAccuracyGeometry();
1049         geolocation_accuracy.setGeometry(accuracy);
1050         if(geolocation_set < 2) {
1051             geolocation_set = 2;
1052             map.getView().fit(accuracy);
1053         }
1054     });
1055     geolocation.on('error', function(error) {
1056         fail(lang.error_location + ' ' + error.message);
1057         trackingStop();
19a338 1058         geolocation_button.remove();
a4d011 1059     });
JK 1060     geolocation_button.addEventListener('click', trackingToggle);
1061     
5be662 1062     document.getElementById('find').addEventListener('click', find.open.bind(find, panel));
2bc9da 1063
JK 1064     var pixelRatio = ol.has.DEVICE_PIXEL_RATIO > 1 ? 2 : 1;
4bfa36 1065     var layers = [
JK 1066         new ol.layer.Tile({
2bc9da 1067             source: new ol.source.XYZ({
JK 1068                 attributions: [ol.source.OSM.ATTRIBUTION],
1069                 url: 'https://tiles.ttss.pl/x' + pixelRatio + '/{z}/{x}/{y}.png',
1070                 maxZoom: 19,
1071                 tilePixelRatio: pixelRatio,
a09b8a 1072                 opaque: false,
428023 1073             }),
4bfa36 1074         }),
JK 1075         route_layer,
1076         geolocation_layer,
1077     ];
1078     stops_type.forEach(function(type) {
1079         layers.push(stops_layer[type]);
1080     });
1081     layers.push(stop_selected_layer);
1082     ttss_types.forEach(function(type) {
2bc9da 1083         layers.push(vehicles[type].layer);
4bfa36 1084     });
57b8d3 1085     map = new ol.Map({
JK 1086         target: 'map',
4bfa36 1087         layers: layers,
57b8d3 1088         view: new ol.View({
JK 1089             center: ol.proj.fromLonLat([19.94, 50.06]),
a4d011 1090             zoom: 14,
JK 1091             maxZoom: 19,
a09b8a 1092             constrainResolution: true,
57b8d3 1093         }),
JK 1094         controls: ol.control.defaults({
1095             attributionOptions: ({
1096                 collapsible: false,
1097             })
1098         }).extend([
1099             new ol.control.Control({
1100                 element: document.getElementById('title'),
1101             }),
1102             new ol.control.Control({
1103                 element: fail_element,
a4d011 1104             }),
JK 1105             new ol.control.Control({
19a338 1106                 element: document.getElementById('menu'),
a4d011 1107             }),
57b8d3 1108         ]),
f4a54f 1109         loadTilesWhileAnimating: false,
57b8d3 1110     });
JK 1111     
1112     // Display popup on click
a4d011 1113     map.on('singleclick', mapClicked);
9f0f6a 1114     
JK 1115     fail_element.addEventListener('click', function() {
1116         fail_element.style.top = '-10em';
1117     });
f0bae0 1118     
57b8d3 1119     // Change mouse cursor when over marker
JK 1120     map.on('pointermove', function(e) {
1121         var hit = map.hasFeatureAtPixel(e.pixel);
1122         var target = map.getTargetElement();
1123         target.style.cursor = hit ? 'pointer' : '';
1124     });
1125     
1126     // Change layer visibility on zoom
7e7221 1127     var change_resolution = function() {
88a24c 1128         stops_type.forEach(function(type) {
JK 1129             if(type.startsWith('p')) {
1130                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1131                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1132             }
1133         });
1134     };
1135     map.getView().on('change:resolution', change_resolution);
1136     change_resolution();
57b8d3 1137     
c5a5c3 1138     var future_requests = [];
4bfa36 1139     ttss_types.forEach(function(type) {
2bc9da 1140         future_requests.push(vehicles[type].fetch());
c5a5c3 1141         future_requests.push(updateStops(type));
4bfa36 1142     });
7ca6a1 1143     
2bc9da 1144     hash = new Hash();
JK 1145     Deferred.all(future_requests).done(hash.ready.bind(hash));
57b8d3 1146     
JK 1147     setTimeout(function() {
ae3207 1148         ttss_types.forEach(function(type) {
JK 1149             if(vehicles_xhr[type]) {
1150                 vehicles_xhr[type].abort();
1151             }
1152             if(vehicles_timer[type]) {
1153                 clearTimeout(vehicles_timer[type]);
1154             }
1155         });
1156         
57b8d3 1157         fail(lang.error_refresh);
JK 1158     }, 1800000);
1159 }
1160
1161 init();