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