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