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