Improved www.ttss.krakow.pl
Jacek Kowalski
2019-03-13 4bfa367f643d1c644dada6776fda660df530b92b
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
JK 154     if(data.readyState == 0 && data.statusText == 'abort') return;
155     
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();
4bfa36 250     if(feature_clicked && ttss_types.indexOf(feature_clicked.getId().substr(0, 1)) >= 0) {
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;
b1d3d6 318         if(stops_ignored.indexOf(stop.shortName) >= 0) 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     });
378 }
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) {
98ba34 392         if(!data.routeName || !data.directionText) {
8b6250 393             return;
JK 394         }
395         
396         deleteChildren(table);
397         
398         for(var i = 0, il = data.old.length; i < il; i++) {
399             var tr = document.createElement('tr');
400             addCellWithText(tr, data.old[i].actualTime || data.old[i].plannedTime);
401             addCellWithText(tr, data.old[i].stop_seq_num + '. ' + data.old[i].stop.name);
402             
403             tr.className = 'active';
404             table.appendChild(tr);
405         }
406         
f4a54f 407         var stopsToMark = [];
1d4785 408         
8b6250 409         for(var i = 0, il = data.actual.length; i < il; i++) {
JK 410             var tr = document.createElement('tr');
411             addCellWithText(tr, data.actual[i].actualTime || data.actual[i].plannedTime);
412             addCellWithText(tr, data.actual[i].stop_seq_num + '. ' + data.actual[i].stop.name);
1d4785 413             
4bfa36 414             stopsToMark.push('s' + ttss_type + data.actual[i].stop.id);
8b6250 415             
JK 416             if(data.actual[i].status == 'STOPPING') {
417                 tr.className = 'success';
418             }
419             table.appendChild(tr);
420         }
f4a54f 421         
4bfa36 422         markStops(stopsToMark, ttss_type, true);
8b6250 423         
9dd2e1 424         feature_timer = setTimeout(function() { vehicleTable(feature, table); }, ttss_refresh);
8b6250 425     }).fail(fail_ajax_popup);
JK 426 }
427
eafc1c 428 function stopTable(stopType, stopId, table, featureId) {
8b6250 429     if(feature_xhr) feature_xhr.abort();
JK 430     if(feature_timer) clearTimeout(feature_timer);
431     
4bfa36 432     var ttss_type = featureId.substr(1, 1);
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         
eafc1c 479         feature_timer = setTimeout(function() { stopTable(stopType, stopId, table, featureId); }, ttss_refresh);
8b6250 480     }).fail(fail_ajax_popup);
JK 481 }
482
7ca6a1 483 function featureClicked(feature) {
1d4785 484     if(feature && !feature.getId()) return;
JK 485     
486     unstyleSelectedFeatures();
487     
7ca6a1 488     if(!feature) {
d29c06 489         panel.close();
7ca6a1 490         return;
JK 491     }
492     
493     var coordinates = feature.getGeometry().getCoordinates();
494     
9f0f6a 495     var div = document.createElement('div');
8b6250 496     
4bfa36 497     var typeName;
07c714 498     var name = feature.get('name');
JK 499     var additional;
8b6250 500     var table = document.createElement('table');
JK 501     var thead = document.createElement('thead');
502     var tbody = document.createElement('tbody');
503     table.appendChild(thead);
504     table.appendChild(tbody);
07c714 505     
a4d011 506     var tabular_data = true;
JK 507     
4bfa36 508     var type = feature.getId().substr(0, 1);
JK 509     // Location
510     if(type == 'l') {
511         tabular_data = false;
512         typeName = '';
513         name = lang.type_location;
514     }
515     // Vehicle
516     else if(ttss_types.indexOf(type) >= 0) {
517         typeName = lang.type_bus;
518         if(type == 't') {
519             typeName = lang.type_tram;
520         }
521         
522         var span = displayVehicle(feature.get('vehicle_type'));
523         
524         additional = document.createElement('p');
525         if(span.title) {
526             setText(additional, span.title);
527         } else {
528             setText(additional, feature.getId());
529         }
530         additional.insertBefore(span, additional.firstChild);
531         
532         addElementWithText(thead, 'th', lang.header_time);
533         addElementWithText(thead, 'th', lang.header_stop);
534         
535         vehicleTable(feature, tbody);
536         vehiclePath(feature);
537         
538         styleVehicle(feature, true);
539     }
540     // Stop or stop point
541     else if(['s', 'p'].indexOf(type) >= 0) {
542         if(type == 's') {
543             typeName = lang.type_stop_tram;
1b7c52 544             var second_type = lang.departures_for_buses;
JK 545             var mapping = stops_mapping['sb'];
4bfa36 546             
a83099 547             if(feature.getId().startsWith('sb')) {
4bfa36 548                 typeName = lang.type_stop_bus;
1b7c52 549                 second_type = lang.departures_for_trams;
JK 550                 mapping = stops_mapping['st'];
551             }
552             
553             if(mapping[feature.get('shortName')]) {
554                 additional = document.createElement('p');
555                 additional.className = 'small';
556                 addElementWithText(additional, 'a', second_type).addEventListener(
557                     'click',
558                     function() {
559                         featureClicked(mapping[feature.get('shortName')]);
560                     }
561                 );
a83099 562             }
4bfa36 563         } else {
JK 564             typeName = lang.type_stoppoint_tram;
8b6250 565             
a83099 566             if(feature.getId().startsWith('pb')) {
4bfa36 567                 typeName = lang.type_stoppoint_bus;
a83099 568             }
8b6250 569             
JK 570             additional = document.createElement('p');
571             additional.className = 'small';
572             addElementWithText(additional, 'a', lang.departures_for_stop).addEventListener(
573                 'click',
574                 function() {
1b7c52 575                     var mapping = stops_mapping['s' + feature.getId().substr(1,1)];
JK 576                     featureClicked(mapping[feature.get('shortName')]);
8b6250 577                 }
JK 578             );
4bfa36 579         }
JK 580         
581         addElementWithText(thead, 'th', lang.header_line);
582         addElementWithText(thead, 'th', lang.header_direction);
583         addElementWithText(thead, 'th', lang.header_time);
584         addElementWithText(thead, 'th', lang.header_delay);
585         
586         stopTable('stop', feature.get('shortName'), tbody, feature.getId());
587         markStops([feature], feature.getId().substr(1,1));
588     } else {
589         panel.close();
590         return;
07c714 591     }
8b6250 592     
JK 593     var loader = addElementWithText(tbody, 'td', lang.loading);
594     loader.className = 'active';
ee4e7c 595     loader.colSpan = thead.childNodes.length;
07c714 596     
4bfa36 597     addParaWithText(div, typeName).className = 'type';
9f0f6a 598     addParaWithText(div, name).className = 'name';
07c714 599     
JK 600     if(additional) {
9f0f6a 601         div.appendChild(additional);
7ca6a1 602     }
JK 603     
a4d011 604     if(tabular_data) {
JK 605         div.appendChild(table);
606         ignore_hashchange = true;
607         window.location.hash = '#!' + feature.getId();
608     }
7ca6a1 609     
1d4785 610     setTimeout(function () {map.getView().animate({
07c714 611         center: feature.getGeometry().getCoordinates(),
1d4785 612     }) }, 10);
07c714 613     
9f0f6a 614     
d29c06 615     panel.show(div, function() {
9f0f6a 616         if(!ignore_hashchange) {
JK 617             ignore_hashchange = true;
618             window.location.hash = '';
619             
620             unstyleSelectedFeatures();
d29c06 621             feature_clicked = null;
9f0f6a 622             
9dd2e1 623             if(path_xhr) path_xhr.abort();
9f0f6a 624             if(feature_xhr) feature_xhr.abort();
JK 625             if(feature_timer) clearTimeout(feature_timer);
626         }
627     });
07c714 628     
1d4785 629     feature_clicked = feature;
a4d011 630 }
JK 631
632 function mapClicked(e) {
633     var point = e.coordinate;
634     var features = [];
635     map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
636         if(layer == stop_selected_layer) return;
637         if(feature.getId()) features.push(feature);
638     });
639     
640     if(features.length > 1) {
641         featureClicked();
642         
643         var div = document.createElement('div');
644         
645         addParaWithText(div, lang.select_feature);
646         
647         for(var i = 0; i < features.length; i++) {
648             var feature = features[i];
649             
650             var p = document.createElement('p');
651             var a = document.createElement('a');
652             p.appendChild(a);
653             a.addEventListener('click', function(feature) { return function() {
654                 featureClicked(feature);
655             }}(feature));
656             
4bfa36 657             var type = feature.getId().substr(0, 1);
JK 658             var typeName = '';
659             if(type == 'l') {
660                 typeName = '';
661                 name = lang.type_location;
662             } else if(ttss_types.indexOf(type) >= 0) {
663                 typeName = lang.type_bus;
664                 if(type == 't') {
665                     typeName = lang.type_tram;
666                 }
667                 if(feature.get('vehicle_type').num) {
668                     typeName += ' ' + feature.get('vehicle_type').num;
669                 }
670             } else if(type == 's') {
671                 typeName = lang.type_stop_tram;
672                 if(feature.getId().startsWith('sb')) {
673                     typeName = lang.type_stop_bus;
674                 }
675             } else if (type == 'p') {
676                 typeName = lang.type_stoppoint_tram;
677                 if(feature.getId().startsWith('pb')) {
678                     typeName = lang.type_stoppoint_bus;
679                 }
680             } else {
681                 continue;
a4d011 682             }
JK 683             
4bfa36 684             addElementWithText(a, 'span', typeName).className = 'small';
a4d011 685             a.appendChild(document.createTextNode(' '));
JK 686             addElementWithText(a, 'span', feature.get('name'));
687             
688             div.appendChild(p);
689         }
690         
d29c06 691         panel.show(div);
a4d011 692         
JK 693         return;
694     }
695     
696     var feature = features[0];
697     if(!feature) {
88a24c 698         stops_type.forEach(function(type) {
JK 699             if(stops_layer[type].getVisible()) {
700                 feature = returnClosest(point, feature, stops_source[type].getClosestFeatureToCoordinate(point));
701             }
702         });
4bfa36 703         ttss_types.forEach(function(type) {
JK 704             if(vehicles_layer[type].getVisible()) {
705                 feature = returnClosest(point, feature, vehicles_source[type].getClosestFeatureToCoordinate(point));
706             }
707         });
a4d011 708         
JK 709         if(getDistance(point, feature) > map.getView().getResolution() * 20) {
710             feature = null;
711         }
712     }
713     
714     featureClicked(feature);
715 }
716
717 function trackingStop() {
d29c06 718     geolocation_button.classList.remove('clicked');
a4d011 719     geolocation.setTracking(false);
JK 720     
721     geolocation_source.clear();
722 }
723 function trackingStart() {
724     geolocation_set = 0;
d29c06 725     geolocation_button.classList.add('clicked');
a4d011 726     geolocation_feature.setGeometry(new ol.geom.Point(map.getView().getCenter()));
JK 727     geolocation_accuracy.setGeometry(new ol.geom.Circle(map.getView().getCenter(), 100000));
728     
729     geolocation_source.addFeature(geolocation_feature);
730     geolocation_source.addFeature(geolocation_accuracy);
731     
732     geolocation.setTracking(true);
733 }
734 function trackingToggle() {
735     if(geolocation.getTracking()) {
736         trackingStop();
737     } else {
738         trackingStart();
739     }
7ca6a1 740 }
JK 741
742 function hash() {
743     if(ignore_hashchange) {
744         ignore_hashchange = false;
745         return;
746     }
747     
748     var feature = null;
f4a54f 749     var vehicleId = null;
JK 750     var stopId = null;
7ca6a1 751     
JK 752     if(window.location.hash.match(/^#!t[0-9]{3}$/)) {
f4a54f 753         vehicleId = depotIdToVehicleId(window.location.hash.substr(3), 't');
JK 754     } else if(window.location.hash.match(/^#!b[0-9]{3}$/)) {
755         vehicleId = depotIdToVehicleId(window.location.hash.substr(3), 'b');
7ca6a1 756     } else if(window.location.hash.match(/^#![A-Za-z]{2}[0-9]{3}$/)) {
f4a54f 757         vehicleId = depotIdToVehicleId(window.location.hash.substr(2));
439d60 758     } else if(window.location.hash.match(/^#!v-?[0-9]+$/)) {
f4a54f 759         vehicleId = 't' + window.location.hash.substr(3);
JK 760     } else if(window.location.hash.match(/^#![tb]-?[0-9]+$/)) {
761         vehicleId = window.location.hash.substr(2);
762     } else if(window.location.hash.match(/^#![sp]-?[0-9]+$/)) {
763         stopId = window.location.hash.substr(2,1) + 't' + window.location.hash.substr(3);
764     } else if(window.location.hash.match(/^#![sp][tb]-?[0-9]+$/)) {
765         stopId = window.location.hash.substr(2);
7ca6a1 766     }
JK 767     
f4a54f 768     if(vehicleId) {
4bfa36 769         feature = vehicles_source[vehicleId.substr(0, 1)].getFeatureById(vehicleId);
7ca6a1 770     } else if(stopId) {
88a24c 771         feature = stops_source[stopId.substr(0,2)].getFeatureById(stopId);
7ca6a1 772     }
JK 773     
774     featureClicked(feature);
57b8d3 775 }
JK 776
0e60d1 777 function getDistance(c1, c2) {
JK 778     if(c1.getGeometry) {
779         c1 = c1.getGeometry().getCoordinates();
780     }
781     if(c2.getGeometry) {
782         c2 = c2.getGeometry().getCoordinates();
783     }
784     
785     var c1 = ol.proj.transform(c1, 'EPSG:3857', 'EPSG:4326');
786     var c2 = ol.proj.transform(c2, 'EPSG:3857', 'EPSG:4326');
a8a6d1 787     return ol.sphere.getDistance(c1, c2);
0e60d1 788 }
JK 789
790 function returnClosest(point, f1, f2) {
791     if(!f1) return f2;
792     if(!f2) return f1;
793     
1b7c52 794     return (getDistance(point, f1) <= getDistance(point, f2)) ? f1 : f2;
0e60d1 795 }
JK 796
57b8d3 797 function init() {
JK 798     if(!window.jQuery) {
799         fail(lang.jquery_not_loaded);
800         return;
801     }
802     
803     $.ajaxSetup({
804         dataType: 'json',
805         timeout: 10000,
806     });
d29c06 807     
JK 808     panel = new Panel(document.getElementById('panel'));
57b8d3 809     
4bfa36 810     route_source = new ol.source.Vector({
JK 811         features: [],
812     });
813     route_layer = new ol.layer.Vector({
814         source: route_source,
815         style: new ol.style.Style({
816             stroke: new ol.style.Stroke({ color: [255, 153, 0, .8], width: 5 })
817         }),
818     });
819     
88a24c 820     stops_type.forEach(function(type) {
JK 821         stops_source[type] = new ol.source.Vector({
822             features: [],
823         });
824         stops_layer[type] = new ol.layer.Vector({
825             source: stops_source[type],
826             renderMode: 'image',
827             style: stops_style[type],
828         });
1b7c52 829         stops_mapping[type] = {};
f4a54f 830     });
JK 831     
832     stop_selected_source = new ol.source.Vector({
833         features: [],
834     });
835     stop_selected_layer = new ol.layer.Vector({
836         source: stop_selected_source,
57b8d3 837         visible: false,
JK 838     });
839     
4bfa36 840     ttss_types.forEach(function(type) {
JK 841         vehicles_source[type] = new ol.source.Vector({
842             features: [],
843         });
844         vehicles_layer[type] = new ol.layer.Vector({
845             source: vehicles_source[type],
846         });
847         vehicles_last_update[type] = 0;
1d4785 848     });
JK 849     
1c0616 850     ol.style.IconImageCache.shared.setSize(512);
JK 851     
a4d011 852     geolocation_feature = new ol.Feature({
JK 853         name: '',
854         style: new ol.style.Style({
855             image: new ol.style.Circle({
856                 fill: new ol.style.Fill({color: '#39C'}),
857                 stroke: new ol.style.Stroke({color: '#FFF', width: 2}),
858                 radius: 5,
859             }),
860         }),
861     });
862     geolocation_feature.setId('location_point');
863     geolocation_accuracy = new ol.Feature();
864     geolocation_source = new ol.source.Vector({
865         features: [],
866     });
867     geolocation_layer = new ol.layer.Vector({
868         source: geolocation_source,
869     });
870     geolocation_button = document.querySelector('#track button');
871     if(!navigator.geolocation) {
d29c06 872         geolocation_button.classList.add('hidden');
a4d011 873     }
JK 874     
376c6e 875     geolocation = new ol.Geolocation({projection: 'EPSG:3857'});
a4d011 876     geolocation.on('change:position', function() {
JK 877         var coordinates = geolocation.getPosition();
878         geolocation_feature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
879         if(geolocation_set < 1) {
880             geolocation_set = 1;
881             map.getView().animate({
882                 center: coordinates,
883             })
884         }
885     });
886     geolocation.on('change:accuracyGeometry', function() {
887         var accuracy = geolocation.getAccuracyGeometry();
888         geolocation_accuracy.setGeometry(accuracy);
889         if(geolocation_set < 2) {
890             geolocation_set = 2;
891             map.getView().fit(accuracy);
892         }
893     });
894     geolocation.on('error', function(error) {
895         fail(lang.error_location + ' ' + error.message);
896         trackingStop();
d29c06 897         geolocation_button.classList.add('hidden');
a4d011 898     });
JK 899     geolocation_button.addEventListener('click', trackingToggle);
900     
4bfa36 901     var layers = [
JK 902         new ol.layer.Tile({
903             source: new ol.source.OSM(),
904         }),
905         route_layer,
906         geolocation_layer,
907     ];
908     stops_type.forEach(function(type) {
909         layers.push(stops_layer[type]);
910     });
911     layers.push(stop_selected_layer);
912     ttss_types.forEach(function(type) {
913         layers.push(vehicles_layer[type]);
914     });
57b8d3 915     map = new ol.Map({
JK 916         target: 'map',
4bfa36 917         layers: layers,
57b8d3 918         view: new ol.View({
JK 919             center: ol.proj.fromLonLat([19.94, 50.06]),
a4d011 920             zoom: 14,
JK 921             maxZoom: 19,
57b8d3 922         }),
JK 923         controls: ol.control.defaults({
924             attributionOptions: ({
925                 collapsible: false,
926             })
927         }).extend([
928             new ol.control.Control({
929                 element: document.getElementById('title'),
930             }),
931             new ol.control.Control({
932                 element: fail_element,
a4d011 933             }),
JK 934             new ol.control.Control({
935                 element: document.getElementById('track'),
936             }),
57b8d3 937         ]),
f4a54f 938         loadTilesWhileAnimating: false,
57b8d3 939     });
JK 940     
941     // Display popup on click
a4d011 942     map.on('singleclick', mapClicked);
9f0f6a 943     
JK 944     fail_element.addEventListener('click', function() {
945         fail_element.style.top = '-10em';
946     });
f0bae0 947     
57b8d3 948     // Change mouse cursor when over marker
JK 949     map.on('pointermove', function(e) {
950         var hit = map.hasFeatureAtPixel(e.pixel);
951         var target = map.getTargetElement();
952         target.style.cursor = hit ? 'pointer' : '';
953     });
954     
955     // Change layer visibility on zoom
88a24c 956     var change_resolution = function(e) {
JK 957         stops_type.forEach(function(type) {
958             if(type.startsWith('p')) {
959                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
960                 stops_layer[type].setVisible(map.getView().getZoom() >= 16);
961             }
962         });
963     };
964     map.getView().on('change:resolution', change_resolution);
965     change_resolution();
57b8d3 966     
4bfa36 967     var future_requests = [
3d2caa 968         updateVehicleInfo(),
4bfa36 969     ];
JK 970     ttss_types.forEach(function(type) {
971         future_requests.push(updateVehicles(type));
7ca6a1 972     });
4bfa36 973     stops_type.forEach(function(type) {
JK 974         future_requests.push(updateStops(type.substr(0,1), type.substr(1,1)));
975     });
976     $.when(future_requests).done(hash);
7ca6a1 977     
JK 978     window.addEventListener('hashchange', hash);
57b8d3 979     
JK 980     setTimeout(function() {
eafc1c 981         if(trams_xhr) trams_xhr.abort();
JK 982         if(trams_timer) clearTimeout(trams_timer);
983         if(buses_xhr) buses_xhr.abort();
984         if(buses_timer) clearTimeout(buses_timer);
57b8d3 985           
JK 986         fail(lang.error_refresh);
987     }, 1800000);
988 }
989
990 init();