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