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