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