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