Improved www.ttss.krakow.pl
Jacek Kowalski
2020-11-02 3a4fe8e4076083c1bf0e6c930954ec58633114a5
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',
271                 // TODO: special directions
272                 // vehicle.line = vehicle.name.substr(0, vehicle_name_space);
273                 // vehicle.direction = normalizeName(vehicle.name.substr(vehicle_name_space+1));
274                 // if(special_directions[vehicle.direction]) {
275                 //     vehicle.line = special_directions[vehicle.direction];
276                 // }
c5a5c3 277                 text: feature.get('line'),
2bc9da 278                 fill: new ol.style.Fill({color: 'white'}),
JK 279             }),
280         }));
281     },
c5a5c3 282     select: function(feature) {
2bc9da 283         if(feature instanceof ol.Feature) {
JK 284             feature = feature.getId();
285         }
286         feature = this.source.getFeatureById(feature);
287         if(!feature) {
288             this.deselect();
289             return;
290         }
291         this.style(feature, true);
292         
293         this.selectedFeatureId = feature.getId();
294     },
295     deselect: function() {
296         if(!this.selectedFeatureId) return false;
297         var feature = this.source.getFeatureById(this.selectedFeatureId);
298         this.style(feature);
299         this.selectedFeatureId = null;
300     },
301
302     typesUpdated: function() {
303         this.source.forEachFeature(function (feature) {
304             this.style(feature);
305         }.bind(this));
306     },
307
308     _newFeature: function(id, data) {
c5a5c3 309         var feature = new ol.Feature(data);
JK 310         feature.set('_', 'v' + this.prefix);
311         feature.setId(id);
312         feature.setGeometry(getGeometryFeature(feature));
2bc9da 313         this.style(feature);
JK 314         return feature;
315     },
c5a5c3 316     _updateFeature: function(feature, vehicle) {
JK 317         Object.keys(vehicle).forEach(function (key) {
318             feature.set(key, deepMerge(feature.get(key), vehicle[key]));
319             if(key === 'lon' || key === 'lat') {
320                 feature.setGeometry(getGeometryFeature(feature));
321             } else if(key === 'angle') {
322                 feature.getStyle().getImage().setRotation(Math.PI * parseFloat(vehicle.angle ? vehicle.angle : 0) / 180.0);
323             } else if(key === 'line') {
324                 // TODO: Special directions
325                 feature.getStyle().getText().setText(vehicle.line);
326             }
327         });
328     },
329     _removeFeature: function(feature) {
330         if(!feature) return;
331         this.source.removeFeature(feature);
332         if(this.selectedFeatureId === feature.getId()) {
333             this.deselect();
334         }
335     },
2bc9da 336     loadFullData: function(data) {
c5a5c3 337         var self = this;
2bc9da 338         var features = [];
JK 339         for(var id in data) {
c5a5c3 340             var feature = this.source.getFeatureById(id);
JK 341             if(feature) {
342                 this._updateFeature(feature, data[id]);
343             } else {
344                 features.push(this._newFeature(id, data[id]));
345             }
2bc9da 346         }
JK 347         this.source.addFeatures(features);
c5a5c3 348         this.source.forEachFeature(function(feature) {
JK 349             if(!data[feature.getId()]) {
350                 self._removeFeature(feature);
351             }
352         });
2bc9da 353         
JK 354         if(this.selectedFeatureId) {
355             this.select(this.selectedFeatureId);
356         }
357     },
358     loadDiffData: function(data) {
359         for(var id in data) {
c5a5c3 360             var feature = this.source.getFeatureById(id);
2bc9da 361             var vehicle = data[id];
JK 362             
363             if(vehicle === null) {
c5a5c3 364                 this._removeFeature(feature);
2bc9da 365             } else if(feature) {
c5a5c3 366                 this._updateFeature(feature, vehicle);
2bc9da 367             } else {
JK 368                 this.source.addFeature(this._newFeature(id, data[id]));
369             }
370         }
371     },
372     
373     fetch: function() {
374         var self = this;
c5a5c3 375         var result = this.fetchXhr();
2bc9da 376         
JK 377         // TODO: updates (EventSource)
c5a5c3 378         // TODO: error ahandling (reconnect)
2bc9da 379         // TODO: error handling (indicator)
JK 380         
381         return result;
382     },
c5a5c3 383     fetchXhr: function() {
2bc9da 384         var self = this;
JK 385         this.xhr = $.get(
c5a5c3 386             api_url + '/positions/?type=' + this.prefix + '&last=' + this.lastUpdate
2bc9da 387         ).done(function(data) {
JK 388             try {
c5a5c3 389                 if(data['type'] == 'full') {
JK 390                     self.loadFullData(data['pos']);
391                 } else {
392                     self.loadDiffData(data['pos']);
2bc9da 393                 }
c5a5c3 394                 self.lastUpdate = data['last'];
JK 395                 setTimeout(self.fetchXhr.bind(self), api_refresh);
2bc9da 396             } catch(e) {
JK 397                 console.log(e);
398                 throw e;
399             }
400         }).fail(this.failXhr.bind(this));
401         return this.xhr;
402     },
403     
404     failXhr: function(result) {
405         // abort() is not a failure
406         if(result.readyState === 0) return;
407         
408         if(result.status === 0) {
409             fail(lang.error_request_failed_connectivity, result);
c5a5c3 410         } else if(result.status === 304) {
2bc9da 411             fail(lang.error_request_failed_no_data, result);
c5a5c3 412         } else if(result.statusText) {
2bc9da 413             fail(lang.error_request_failed_status.replace('$status', result.statusText), result);
JK 414         } else {
415             fail(lang.error_request_failed, result);
416         }
417     },
418 };
d29c06 419
57b8d3 420 function fail(msg) {
a4d011 421     setText(fail_text, msg);
57b8d3 422     fail_element.style.top = '0.5em';
8b6250 423 }
JK 424
425 function fail_ajax_generic(data, fnc) {
57b8d3 426     // abort() is not a failure
faad2a 427     if(data.readyState === 0) return;
57b8d3 428     
faad2a 429     if(data.status === 0) {
8b6250 430         fnc(lang.error_request_failed_connectivity, data);
57b8d3 431     } else if (data.statusText) {
8b6250 432         fnc(lang.error_request_failed_status.replace('$status', data.statusText), data);
57b8d3 433     } else {
8b6250 434         fnc(lang.error_request_failed, data);
57b8d3 435     }
8b6250 436 }
JK 437
438 function fail_ajax(data) {
439     fail_ajax_generic(data, fail);
440 }
441
442 function fail_ajax_popup(data) {
d29c06 443     fail_ajax_generic(data, panel.fail.bind(panel));
57b8d3 444 }
JK 445
c5a5c3 446 function getGeometryFeature(feature) {
JK 447     return getGeometryPair([feature.get('lon'), feature.get('lat')]);
448 }
2bc9da 449 function getGeometryPair(pair) {
JK 450     return new ol.geom.Point(ol.proj.fromLonLat(pair));
57b8d3 451 }
2bc9da 452 function getGeometry(object) {
JK 453     return getGeometryPair([object.longitude / 3600000.0, object.latitude / 3600000.0]);
1d4785 454 }
JK 455
c5a5c3 456 function markStops(stops, featureSource, routeStyle) {
f4a54f 457     stop_selected_source.clear();
ba6e87 458     
c5a5c3 459     var style = stops_layer['s' + featureSource].getStyle().clone();
f4a54f 460     
JK 461     if(routeStyle) {
462         style.getImage().setRadius(5);
463     } else {
464         style.getImage().getStroke().setWidth(2);
465         style.getImage().getStroke().setColor('#F00');
466         style.getImage().setRadius(5);
ba6e87 467     }
1d4785 468     
f4a54f 469     stop_selected_layer.setStyle(style);
JK 470     
db4410 471     var feature, prefix;
f4a54f 472     for(var i = 0; i < stops.length; i++) {
JK 473         if(stops[i].getId) {
474             feature = stops[i];
475         } else {
c5a5c3 476             feature = stops_source['s' + featureSource].getFeatureById(stops[i]);
f4a54f 477         }
JK 478         if(feature) {
479             stop_selected_source.addFeature(feature);
480         }
1d4785 481     }
JK 482     
f4a54f 483     stop_selected_layer.setVisible(true);
1d4785 484 }
JK 485
486 function unstyleSelectedFeatures() {
f4a54f 487     stop_selected_source.clear();
JK 488     route_source.clear();
2bc9da 489     ttss_types.forEach(function(type) {
JK 490         vehicles[type].deselect();
491     });
57b8d3 492 }
JK 493
88a24c 494 function updateStopSource(stops, prefix) {
7e7221 495     var stop;
57b8d3 496     for(var i = 0; i < stops.length; i++) {
7e7221 497         stop = stops[i];
e61357 498         
c5a5c3 499         var feature = new ol.Feature(stop);
JK 500         feature.setId(stop.id);
501         feature.setGeometry(getGeometryFeature(feature));
e61357 502         
c5a5c3 503         if(feature.get('parent') === null) {
JK 504             feature.set('_', 's' + prefix);
505             stops_source['s' + prefix].addFeature(feature);
1b7c52 506         } else {
c5a5c3 507             feature.set('_', 'p' + prefix);
JK 508             stops_source['p' + prefix].addFeature(feature);
1b7c52 509         }
57b8d3 510     }
JK 511 }
512
c5a5c3 513 function updateStops(ttss_type) {
7ca6a1 514     return $.get(
c5a5c3 515         api_url + '/stops/?type=' + ttss_type
57b8d3 516     ).done(function(data) {
c5a5c3 517         updateStopSource(data, ttss_type);
57b8d3 518     }).fail(fail_ajax);
7ca6a1 519 }
JK 520
7e7221 521 function vehiclePath(feature) {
9dd2e1 522     if(path_xhr) path_xhr.abort();
JK 523     
524     var featureId = feature.getId();
4bfa36 525     var ttss_type = featureId.substr(0, 1);
eafc1c 526     
9dd2e1 527     path_xhr = $.get(
4bfa36 528         ttss_urls[ttss_type] + '/geoserviceDispatcher/services/pathinfo/vehicle'
JK 529             + '?id=' + encodeURIComponent(featureId.substr(1))
9dd2e1 530     ).done(function(data) {
JK 531         if(!data || !data.paths || !data.paths[0] || !data.paths[0].wayPoints) return;
532         
db4410 533         var point;
9dd2e1 534         var points = [];
JK 535         for(var i = 0; i < data.paths[0].wayPoints.length; i++) {
536             point = data.paths[0].wayPoints[i];
537             points.push(ol.proj.fromLonLat([
538                 point.lon / 3600000.0,
539                 point.lat / 3600000.0,
540             ]));
541         }
542         
543         route_source.addFeature(new ol.Feature({
544             geometry: new ol.geom.LineString(points)
545         }));
546         route_layer.setVisible(true);
547     });
2b6454 548     return path_xhr;
9dd2e1 549 }
JK 550
551 function vehicleTable(feature, table) {
552     if(feature_xhr) feature_xhr.abort();
553     if(feature_timer) clearTimeout(feature_timer);
554     
c5a5c3 555     var featureDiscriminator = feature.get('_');
JK 556     var featureType = featureDiscriminator.substr(0, 1);
557     var featureSource = featureDiscriminator.substr(1, 1);
558     var featureStatus = feature.get('status');
eafc1c 559     
8b6250 560     feature_xhr = $.get(
c5a5c3 561         api_url + '/trip/?type=' + featureSource + '&id=' + feature.get('trip')
8b6250 562     ).done(function(data) {
JK 563         deleteChildren(table);
564         
db4410 565         var tr;
f4a54f 566         var stopsToMark = [];
c5a5c3 567         for(var i = 0, il = data.length; i < il; i++) {
db4410 568             tr = document.createElement('tr');
c5a5c3 569             addCellWithText(tr, data[i].time);
JK 570             addCellWithText(tr, (i+1) + '. ' + normalizeName(data[i].name));
1d4785 571             
c5a5c3 572             stopsToMark.push(data[i].stop);
8b6250 573             
c5a5c3 574             if(data[i].seq < feature.get('seq')) {
cb5a77 575                 tr.className = 'active';
c5a5c3 576             } else if(data[i].seq == feature.get('seq') && featureStatus < 2) {
8b6250 577                 tr.className = 'success';
JK 578             }
579             table.appendChild(tr);
580         }
f4a54f 581         
c5a5c3 582         if(data.length === 0) {
b6f8e3 583             tr = document.createElement('tr');
JK 584             table.appendChild(tr);
585             tr = addCellWithText(tr, lang.no_data);
586             tr.colSpan = '2';
587             tr.className = 'active';
588         }
589         
c5a5c3 590         markStops(stopsToMark, featureSource, true);
8b6250 591         
2bc9da 592         feature_timer = setTimeout(function() { vehicleTable(feature, table); }, api_refresh);
8b6250 593     }).fail(fail_ajax_popup);
2b6454 594     return feature_xhr;
8b6250 595 }
JK 596
c5a5c3 597 function stopTable(feature, table) {
8b6250 598     if(feature_xhr) feature_xhr.abort();
JK 599     if(feature_timer) clearTimeout(feature_timer);
eafc1c 600     
c5a5c3 601     var featureDiscriminator = feature.get('_');
JK 602     var featureType = featureDiscriminator.substr(0, 1);
603     var featureSource = featureDiscriminator.substr(1, 1);
604     
8b6250 605     feature_xhr = $.get(
c5a5c3 606         api_url + '/stop/?type=' + featureSource + '&id=' + feature.getId()
8b6250 607     ).done(function(data) {
JK 608         deleteChildren(table);
609         
cb5a77 610         var all_departures = data.old.concat(data.actual);
db4410 611         var tr, dir_cell, vehicle, status, status_cell, delay, delay_cell;
cb5a77 612         for(var i = 0, il = all_departures.length; i < il; i++) {
db4410 613             tr = document.createElement('tr');
cb5a77 614             addCellWithText(tr, all_departures[i].patternText);
ca42d3 615             dir_cell = addCellWithText(tr, normalizeName(all_departures[i].direction));
c5a5c3 616             //vehicle = vehicles_info.getParsed(all_departures[i].vehicleId);
8b6250 617             dir_cell.appendChild(displayVehicle(vehicle));
cb5a77 618             status = parseStatus(all_departures[i]);
db4410 619             status_cell = addCellWithText(tr, status);
cb5a77 620             delay = parseDelay(all_departures[i]);
db4410 621             delay_cell = addCellWithText(tr, delay);
8b6250 622             
cb5a77 623             if(i < data.old.length) {
db4410 624                 tr.className = 'active';
cb5a77 625             } else if(status === lang.boarding_sign) {
8b6250 626                 tr.className = 'success';
JK 627                 status_cell.className = 'status-boarding';
628             } else if(parseInt(delay) > 9) {
629                 tr.className = 'danger';
630                 delay_cell.className = 'status-delayed';
631             } else if(parseInt(delay) > 3) {
632                 tr.className = 'warning';
633             }
634             
635             table.appendChild(tr);
636         }
637         
c5a5c3 638         feature_timer = setTimeout(function() { stopTable(feature, table); }, api_refresh);
8b6250 639     }).fail(fail_ajax_popup);
2b6454 640     return feature_xhr;
8b6250 641 }
JK 642
7ca6a1 643 function featureClicked(feature) {
c5a5c3 644     if(!feature || !feature.getId() || !feature.get('_')) {
JK 645         feature = null;
646     }
1d4785 647     
JK 648     unstyleSelectedFeatures();
649     
7ca6a1 650     if(!feature) {
d29c06 651         panel.close();
7ca6a1 652         return;
JK 653     }
654     
c5a5c3 655     var featureDiscriminator = feature.get('_');
JK 656     var featureType = featureDiscriminator.substr(0, 1);
657     var featureSource = featureDiscriminator.substr(1, 1);
658     
9f0f6a 659     var div = document.createElement('div');
8b6250 660     
c5a5c3 661     var name = normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir'));
07c714 662     var additional;
8b6250 663     var table = document.createElement('table');
JK 664     var thead = document.createElement('thead');
665     var tbody = document.createElement('tbody');
666     table.appendChild(thead);
667     table.appendChild(tbody);
07c714 668     
a4d011 669     var tabular_data = true;
JK 670     
c5a5c3 671     var typeName = lang.types[featureDiscriminator];
76f5c4 672     if(typeof typeName === 'undefined') {
JK 673         typeName = '';
674     }
675     
4bfa36 676     // Location
c5a5c3 677     if(featureType == 'l') {
4bfa36 678         tabular_data = false;
76f5c4 679         name = typeName;
4bfa36 680         typeName = '';
JK 681     }
682     // Vehicle
c5a5c3 683     else if(featureType == 'v') {
JK 684         var span = displayVehicle(feature.get('type'));
4bfa36 685         
JK 686         additional = document.createElement('p');
687         if(span.title) {
688             setText(additional, span.title);
689         } else {
690             setText(additional, feature.getId());
691         }
692         additional.insertBefore(span, additional.firstChild);
693         
694         addElementWithText(thead, 'th', lang.header_time);
695         addElementWithText(thead, 'th', lang.header_stop);
696         
697         vehicleTable(feature, tbody);
c5a5c3 698         //vehiclePath(feature);
4bfa36 699     }
JK 700     // Stop or stop point
c5a5c3 701     else if(['s', 'p'].includes(featureType)) {
JK 702         if(featureType == 's') {
1b7c52 703             var second_type = lang.departures_for_buses;
c5a5c3 704             var source = stops_source['sb'];
4bfa36 705             
c5a5c3 706             if(featureSource == 'b') {
1b7c52 707                 second_type = lang.departures_for_trams;
c5a5c3 708                 source = stops_source['st'];
1b7c52 709             }
0ba749 710             
c5a5c3 711             stopTable(feature, tbody);
1b7c52 712             
c5a5c3 713             var second = source.getFeatureById(feature.get('id'));
JK 714             if(second) {
1b7c52 715                 additional = document.createElement('p');
JK 716                 additional.className = 'small';
717                 addElementWithText(additional, 'a', second_type).addEventListener(
718                     'click',
719                     function() {
c5a5c3 720                         featureClicked(second);
1b7c52 721                     }
JK 722                 );
a83099 723             }
4bfa36 724         } else {
c5a5c3 725             stopTable(feature, tbody);
8b6250 726             
JK 727             additional = document.createElement('p');
728             additional.className = 'small';
729             addElementWithText(additional, 'a', lang.departures_for_stop).addEventListener(
730                 'click',
731                 function() {
c5a5c3 732                     featureClicked(stops_source['s' + featureSource].getFeatureById(feature.get('parent')));
8b6250 733                 }
JK 734             );
4bfa36 735         }
JK 736         
737         addElementWithText(thead, 'th', lang.header_line);
738         addElementWithText(thead, 'th', lang.header_direction);
739         addElementWithText(thead, 'th', lang.header_time);
740         addElementWithText(thead, 'th', lang.header_delay);
741     } else {
742         panel.close();
743         return;
07c714 744     }
8b6250 745     
JK 746     var loader = addElementWithText(tbody, 'td', lang.loading);
747     loader.className = 'active';
ee4e7c 748     loader.colSpan = thead.childNodes.length;
07c714 749     
4bfa36 750     addParaWithText(div, typeName).className = 'type';
ae3207 751     
JK 752     var nameElement = addParaWithText(div, name + ' ');
753     nameElement.className = 'name';
754     
755     var showOnMapElement = addElementWithText(nameElement, 'a', lang.show_on_map);
756     var showOnMapFunction = function() {
757         setTimeout(function () {map.getView().animate({
758             center: feature.getGeometry().getCoordinates(),
759         })}, 10);
760     };
761     showOnMapElement.addEventListener('click', showOnMapFunction);
20d39d 762     showOnMapElement.className = 'icon icon-pin';
ae3207 763     showOnMapElement.title = lang.show_on_map;
07c714 764     
JK 765     if(additional) {
9f0f6a 766         div.appendChild(additional);
7ca6a1 767     }
JK 768     
a4d011 769     if(tabular_data) {
JK 770         div.appendChild(table);
771     }
7ca6a1 772     
ae3207 773     showOnMapFunction();
9f0f6a 774     
d29c06 775     panel.show(div, function() {
2bc9da 776         unstyleSelectedFeatures();
JK 777         
778         if(path_xhr) path_xhr.abort();
779         if(feature_xhr) feature_xhr.abort();
780         if(feature_timer) clearTimeout(feature_timer);
c5a5c3 781     }, tabular_data ? featureDiscriminator + feature.getId() : '');
07c714 782     
c5a5c3 783     if(featureType == 'v') {
JK 784         vehicles[featureSource].select(feature);
785     } else if(['s', 'p'].includes(featureType)) {
786         markStops([feature], featureSource);
787     }
a4d011 788 }
JK 789
5be662 790 function listFeatures(features) {
JK 791     var div = document.createElement('div');
792     
d5e919 793     if(features.length === 0) {
94177c 794         addParaWithText(div, lang.no_results);
JK 795         return div;
796     }
797     
5be662 798     addParaWithText(div, lang.select_feature);
JK 799     
c5a5c3 800     var feature, p, a, featureDiscriminator, typeName;
5be662 801     for(var i = 0; i < features.length; i++) {
JK 802         feature = features[i];
803         
804         p = document.createElement('p');
805         a = document.createElement('a');
806         p.appendChild(a);
807         a.addEventListener('click', function(feature) { return function() {
808             featureClicked(feature);
809         }}(feature));
810         
c5a5c3 811         featureDiscriminator = feature.get('_');
JK 812         typeName = lang.types[featureDiscriminator];
5be662 813         if(typeof typeName === 'undefined') {
JK 814             typeName = '';
815         }
c5a5c3 816         if(feature.get('type')) {
JK 817             typeName += ' ' + feature.get('type').num;
5be662 818         }
JK 819         
820         addElementWithText(a, 'span', typeName).className = 'small';
821         a.appendChild(document.createTextNode(' '));
c5a5c3 822         addElementWithText(a, 'span', normalizeName(feature.get('name') ? feature.get('name') : feature.get('line') + ' ' + feature.get('dir')));
5be662 823         
JK 824         div.appendChild(p);
825     }
826     
827     return div;
828 }
829
a4d011 830 function mapClicked(e) {
JK 831     var point = e.coordinate;
832     var features = [];
833     map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
834         if(layer == stop_selected_layer) return;
835         if(feature.getId()) features.push(feature);
836     });
837     
7e7221 838     var feature = features[0];
JK 839     
a4d011 840     if(features.length > 1) {
5be662 841         panel.show(listFeatures(features));
a4d011 842         return;
JK 843     }
844     
845     if(!feature) {
88a24c 846         stops_type.forEach(function(type) {
JK 847             if(stops_layer[type].getVisible()) {
848                 feature = returnClosest(point, feature, stops_source[type].getClosestFeatureToCoordinate(point));
849             }
850         });
4bfa36 851         ttss_types.forEach(function(type) {
2bc9da 852             if(vehicles[type].layer.getVisible()) {
JK 853                 feature = returnClosest(point, feature, vehicles[type].source.getClosestFeatureToCoordinate(point));
4bfa36 854             }
JK 855         });
a4d011 856         
JK 857         if(getDistance(point, feature) > map.getView().getResolution() * 20) {
858             feature = null;
859         }
860     }
861     
862     featureClicked(feature);
863 }
864
865 function trackingStop() {
d29c06 866     geolocation_button.classList.remove('clicked');
a4d011 867     geolocation.setTracking(false);
JK 868     
869     geolocation_source.clear();
870 }
871 function trackingStart() {
872     geolocation_set = 0;
d29c06 873     geolocation_button.classList.add('clicked');
a4d011 874     geolocation_feature.setGeometry(new ol.geom.Point(map.getView().getCenter()));
JK 875     geolocation_accuracy.setGeometry(new ol.geom.Circle(map.getView().getCenter(), 100000));
876     
877     geolocation_source.addFeature(geolocation_feature);
878     geolocation_source.addFeature(geolocation_accuracy);
879     
880     geolocation.setTracking(true);
881 }
882 function trackingToggle() {
883     if(geolocation.getTracking()) {
884         trackingStop();
885     } else {
886         trackingStart();
887     }
7ca6a1 888 }
JK 889
2bc9da 890 function Hash() {
57b8d3 891 }
2bc9da 892 Hash.prototype = {
JK 893     _ignoreChange: false,
894     
895     _set: function(id) {
896         var value = '#!' + id;
897         if(value !== window.location.hash) {
898             window.location.hash = value;
899             return true;
900         }
901         return false;
902     },
903     _updateOld: function() {
c5a5c3 904         if(window.location.hash.match(/^#![bt][0-9]{3}$/)) {
JK 905             this.go('v' + window.location.hash.substr(2));
906         } else if(window.location.hash.match(/^#![RHrh][A-Za-z][0-9]{3}$/)) {
907             this.go('vt'+ window.location.hash.substr(4));
908         } else if(window.location.hash.match(/^#![BDPbdp][A-Za-z][0-9]{3}$/)) {
909             this.go('vb'+ window.location.hash.substr(4));
2bc9da 910         }
JK 911     },
912     ready: function() {
913         this._updateOld();
914         this.changed();
c5a5c3 915         window.addEventListener('hashchange', this.changed.bind(this), false);
2bc9da 916     },
JK 917     go: function(id) {
918         this._ignoreChange = false;
919         return this._set(id);
920     },
921     set: function(id) {
922         this._ignoreChange = true;
923         return this._set(id);
924     },
925     changed: function() {
926         if(this._ignoreChange) {
927             this._ignoreChange = false;
928             return false;
929         }
930         
931         var feature = null;
c5a5c3 932         var source = null;
2bc9da 933         var vehicleId = null;
JK 934         var stopId = null;
935         
c5a5c3 936         if(window.location.hash.match(/^#!v[tb][0-9]+$/)) {
JK 937             vehicleId = window.location.hash.substr(3);
938         } else if(window.location.hash.match(/^#![sp][tb][0-9a-z_]+$/)) {
2bc9da 939             stopId = window.location.hash.substr(2);
JK 940         } else if(window.location.hash.match(/^#!f$/)) {
941             find.open(panel);
942             return;
943         }
944         
945         if(vehicleId) {
c5a5c3 946             feature = vehicles[vehicleId.substr(0,1)].source.getFeatureById(vehicleId.substr(1));
2bc9da 947         } else if(stopId) {
c5a5c3 948             feature = stops_source[stopId.substr(0,2)].getFeatureById(stopId.substr(2));
2bc9da 949         }
JK 950         
951         featureClicked(feature);
952         
953         return true;
954     },
955 };
57b8d3 956
0e60d1 957 function getDistance(c1, c2) {
JK 958     if(c1.getGeometry) {
959         c1 = c1.getGeometry().getCoordinates();
960     }
961     if(c2.getGeometry) {
962         c2 = c2.getGeometry().getCoordinates();
963     }
964     
2bc9da 965     c1 = ol.proj.transform(c1, 'EPSG:3857', 'EPSG:4326');
JK 966     c2 = ol.proj.transform(c2, 'EPSG:3857', 'EPSG:4326');
a8a6d1 967     return ol.sphere.getDistance(c1, c2);
0e60d1 968 }
JK 969
970 function returnClosest(point, f1, f2) {
971     if(!f1) return f2;
972     if(!f2) return f1;
973     
1b7c52 974     return (getDistance(point, f1) <= getDistance(point, f2)) ? f1 : f2;
0e60d1 975 }
JK 976
57b8d3 977 function init() {
d29c06 978     panel = new Panel(document.getElementById('panel'));
5be662 979     find = new Find();
57b8d3 980     
4bfa36 981     route_source = new ol.source.Vector({
2bc9da 982         attributions: [lang.help_data_attribution],
4bfa36 983         features: [],
JK 984     });
985     route_layer = new ol.layer.Vector({
986         source: route_source,
987         style: new ol.style.Style({
988             stroke: new ol.style.Stroke({ color: [255, 153, 0, .8], width: 5 })
989         }),
990     });
991     
88a24c 992     stops_type.forEach(function(type) {
JK 993         stops_source[type] = new ol.source.Vector({
994             features: [],
995         });
996         stops_layer[type] = new ol.layer.Vector({
997             source: stops_source[type],
998             renderMode: 'image',
999             style: stops_style[type],
1000         });
1b7c52 1001         stops_mapping[type] = {};
f4a54f 1002     });
JK 1003     
1004     stop_selected_source = new ol.source.Vector({
1005         features: [],
1006     });
1007     stop_selected_layer = new ol.layer.Vector({
1008         source: stop_selected_source,
57b8d3 1009         visible: false,
JK 1010     });
1011     
4bfa36 1012     ttss_types.forEach(function(type) {
2bc9da 1013         vehicles[type] = new Vehicles(type);
1d4785 1014     });
JK 1015     
a4d011 1016     geolocation_feature = new ol.Feature({
JK 1017         name: '',
1018         style: new ol.style.Style({
1019             image: new ol.style.Circle({
1020                 fill: new ol.style.Fill({color: '#39C'}),
1021                 stroke: new ol.style.Stroke({color: '#FFF', width: 2}),
1022                 radius: 5,
1023             }),
1024         }),
1025     });
1026     geolocation_feature.setId('location_point');
1027     geolocation_accuracy = new ol.Feature();
1028     geolocation_source = new ol.source.Vector({
1029         features: [],
1030     });
1031     geolocation_layer = new ol.layer.Vector({
1032         source: geolocation_source,
1033     });
19a338 1034     geolocation_button = document.querySelector('#track');
a4d011 1035     if(!navigator.geolocation) {
19a338 1036         geolocation_button.remove();
a4d011 1037     }
JK 1038     
376c6e 1039     geolocation = new ol.Geolocation({projection: 'EPSG:3857'});
a4d011 1040     geolocation.on('change:position', function() {
JK 1041         var coordinates = geolocation.getPosition();
1042         geolocation_feature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
1043         if(geolocation_set < 1) {
1044             geolocation_set = 1;
1045             map.getView().animate({
1046                 center: coordinates,
1047             })
1048         }
1049     });
1050     geolocation.on('change:accuracyGeometry', function() {
1051         var accuracy = geolocation.getAccuracyGeometry();
1052         geolocation_accuracy.setGeometry(accuracy);
1053         if(geolocation_set < 2) {
1054             geolocation_set = 2;
1055             map.getView().fit(accuracy);
1056         }
1057     });
1058     geolocation.on('error', function(error) {
1059         fail(lang.error_location + ' ' + error.message);
1060         trackingStop();
19a338 1061         geolocation_button.remove();
a4d011 1062     });
JK 1063     geolocation_button.addEventListener('click', trackingToggle);
1064     
5be662 1065     document.getElementById('find').addEventListener('click', find.open.bind(find, panel));
2bc9da 1066
JK 1067     var pixelRatio = ol.has.DEVICE_PIXEL_RATIO > 1 ? 2 : 1;
4bfa36 1068     var layers = [
JK 1069         new ol.layer.Tile({
2bc9da 1070             source: new ol.source.XYZ({
JK 1071                 attributions: [ol.source.OSM.ATTRIBUTION],
1072                 url: 'https://tiles.ttss.pl/x' + pixelRatio + '/{z}/{x}/{y}.png',
1073                 maxZoom: 19,
1074                 tilePixelRatio: pixelRatio,
a09b8a 1075                 opaque: false,
428023 1076             }),
4bfa36 1077         }),
JK 1078         route_layer,
1079         geolocation_layer,
1080     ];
1081     stops_type.forEach(function(type) {
1082         layers.push(stops_layer[type]);
1083     });
1084     layers.push(stop_selected_layer);
1085     ttss_types.forEach(function(type) {
2bc9da 1086         layers.push(vehicles[type].layer);
4bfa36 1087     });
57b8d3 1088     map = new ol.Map({
JK 1089         target: 'map',
4bfa36 1090         layers: layers,
57b8d3 1091         view: new ol.View({
JK 1092             center: ol.proj.fromLonLat([19.94, 50.06]),
a4d011 1093             zoom: 14,
JK 1094             maxZoom: 19,
a09b8a 1095             constrainResolution: true,
57b8d3 1096         }),
JK 1097         controls: ol.control.defaults({
1098             attributionOptions: ({
1099                 collapsible: false,
1100             })
1101         }).extend([
1102             new ol.control.Control({
1103                 element: document.getElementById('title'),
1104             }),
1105             new ol.control.Control({
1106                 element: fail_element,
a4d011 1107             }),
JK 1108             new ol.control.Control({
19a338 1109                 element: document.getElementById('menu'),
a4d011 1110             }),
57b8d3 1111         ]),
f4a54f 1112         loadTilesWhileAnimating: false,
57b8d3 1113     });
JK 1114     
1115     // Display popup on click
a4d011 1116     map.on('singleclick', mapClicked);
9f0f6a 1117     
JK 1118     fail_element.addEventListener('click', function() {
1119         fail_element.style.top = '-10em';
1120     });
f0bae0 1121     
57b8d3 1122     // Change mouse cursor when over marker
JK 1123     map.on('pointermove', function(e) {
1124         var hit = map.hasFeatureAtPixel(e.pixel);
1125         var target = map.getTargetElement();
1126         target.style.cursor = hit ? 'pointer' : '';
1127     });
1128     
1129     // Change layer visibility on zoom
7e7221 1130     var change_resolution = function() {
88a24c 1131         stops_type.forEach(function(type) {
JK 1132             if(type.startsWith('p')) {
1133                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1134                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
1135             }
1136         });
1137     };
1138     map.getView().on('change:resolution', change_resolution);
1139     change_resolution();
57b8d3 1140     
c5a5c3 1141     var future_requests = [];
4bfa36 1142     ttss_types.forEach(function(type) {
2bc9da 1143         future_requests.push(vehicles[type].fetch());
c5a5c3 1144         future_requests.push(updateStops(type));
4bfa36 1145     });
7ca6a1 1146     
2bc9da 1147     hash = new Hash();
JK 1148     Deferred.all(future_requests).done(hash.ready.bind(hash));
57b8d3 1149     
JK 1150     setTimeout(function() {
ae3207 1151         ttss_types.forEach(function(type) {
JK 1152             if(vehicles_xhr[type]) {
1153                 vehicles_xhr[type].abort();
1154             }
1155             if(vehicles_timer[type]) {
1156                 clearTimeout(vehicles_timer[type]);
1157             }
1158         });
1159         
57b8d3 1160         fail(lang.error_refresh);
JK 1161     }, 1800000);
1162 }
1163
1164 init();