Projekt

Obecné

Profil

Stáhnout (9.26 KB) Statistiky
| Větev: | Revize:
1
var mymap;
2
var heatmapLayer = null;
3
var marksLayer = null;
4

    
5
var startX = 49.7248;
6
var startY = 13.3521;
7
var startZoom = 17;
8

    
9
var dataSourceRoute;
10
var currentTime;
11
var name;
12
var date;
13

    
14
var timer;
15
var isAnimationRunning = false;
16
var data = [];
17

    
18
// holds all instances of markers for bind/unbind popup purpose
19
// contains: {key:[L.circle,L.pupup]}
20
// key: x and y, x + '' + y string
21
const globalMarkersHolder = {};
22

    
23
//all marker from which popup was removed 
24
// contains: {key:[L.circle,L.pupup]}
25
// key: x and y, x + '' + y string
26
let globalMarkersChanged = {};
27

    
28
const genPopUpControls = (controls) => {
29
  return `<div class="popup-controls">${controls.reduce((sum, item) => sum + item, '')}</div>`
30
}
31
const genPopUp = (place, number, sum, currentPos, maxPos) => {
32
  const header = `<strong>Zařízení a počet:</strong><div id="place-info">${place}</div>`;
33
  const currentNum = `<span id="digit-info">${number}</span>`;
34
  const sumNum = `<span id="total-info" style="font-size: large">${sum ? '/'+sum : '' }</span>`;
35
  const digitInfo = `<div id="number-info">${currentNum}${sumNum}</div>`;
36
  let previousButton = `<button id="previous-info-btn" class="circle-button" onclick="previousInfo()"></button>`;
37
  let nextButton = `<button id="next-info-btn" onclick="nextInfo()" class="circle-button next"></button>`;
38
  let posInfo = `<div id="count-info">${currentPos} z ${maxPos}</div>`;
39

    
40
  if (!sum) {
41
    previousButton = '';
42
    nextButton = '';
43
    posInfo = '';
44
  }
45
  return `
46
  ${header}
47
  ${digitInfo}
48
  ${genPopUpControls([previousButton, posInfo, nextButton])}
49
  `
50
}
51
function initMap() {
52
  mymap = L.map('heatmap').setView([startX, startY], startZoom);
53

    
54
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
55
    attribution: '',
56
    maxZoom: 19
57
  }).addTo(mymap);
58

    
59
  mymap.on('click', showInfo);
60

    
61
}
62

    
63
var info = [];
64
var currenInfo = 0;
65
var infoLength = 0;
66

    
67
function showInfo(e) {
68

    
69
  info = []
70
  currenInfo = 0;
71

    
72
  // https://wiki.openstreetmap.org/wiki/Zoom_levels
73
  // Todo change to variable - it is used in heatmap init
74
  var stile =  40075016.686 * Math.cos(startX) / Math.pow(2, mymap.getZoom()) ;
75
  var radius = 25 * stile / 256;
76

    
77
  var i = 0;
78
  var lat = 0;
79
  var lng = 0;
80

    
81
  var total = 0;
82
  data[currentTime]['items'].forEach(element => {
83
    if (e.latlng.distanceTo(new L.LatLng(element.x, element.y)) < radius) {
84
      lat += element.x
85
      lng += element.y;
86
      info[i] = {'place' : element.place, 'number' : element.number};
87
      total += parseInt(element.number);
88
      i++;
89
    }
90
  });
91

    
92
  
93
  if (info.length > 0) {
94
    const { place, number } = info[currenInfo];
95
    var popup = L.popup({
96
      autoPan: false
97
                  })
98
                  .setLatLng([lat / i, lng / i])
99
                  .setContent(genPopUp(place, number, total, currenInfo+1,info.length))
100
                  .openOn(mymap);
101
    
102
    if (info.length == 1) {
103
      $('#previous-info-btn').prop('disabled', true);
104
      $('#next-info-btn').prop('disabled', true);
105
      $('.popup-controls').hide();
106
    }
107
  }
108

    
109
}
110

    
111
function previousInfo() {
112
  currenInfo = (currenInfo + info.length - 1) % info.length;
113
  displayInfoText();
114
}
115

    
116
function nextInfo() {
117
  currenInfo = (currenInfo + 1) % info.length
118
  displayInfoText();
119
}
120

    
121
function displayInfoText() {
122
  $('#place-info').html(info[currenInfo].place)
123
  $('#digit-info').html(info[currenInfo].number)
124
  $('#count-info').html(currenInfo + 1 + ' z ' + info.length);
125
}
126

    
127
function setMapView(latitude = startX, longitude = startY, zoom = startZoom) {
128
  mymap.setView([latitude, longitude], zoom);
129
}
130

    
131
function changeAnimationState() {
132

    
133
  isAnimationRunning = !isAnimationRunning
134
  if (isAnimationRunning) {
135
    $('#play-pause').attr('class', 'pause');
136
    timer = setInterval(
137
      function() {
138
        next();
139
      },
140
      800
141
    );
142
  }
143
  else {
144
    clearTimeout(timer);
145
    $('#play-pause').attr('class', 'play');
146
  }
147

    
148

    
149
}
150

    
151
function previous() {
152
  currentTime = (currentTime + 23) % 24;
153
  drawHeatmap(data[currentTime]);
154
  setTimeline();
155
  mymap.closePopup();
156
  updateHeaderControls();
157
  changeUrl();
158
}
159

    
160
function next() {
161
  currentTime = (currentTime + 1) % 24;
162
  drawHeatmap(data[currentTime]);
163
  setTimeline();
164
  mymap.closePopup();
165
  updateHeaderControls();
166
  changeUrl();
167
}
168

    
169
function changeUrl() {
170
  window.history.pushState(
171
    "",
172
    document.title,
173
    window.location.origin + window.location.pathname + `?data_set[date]=${$('#date').val()}&data_set[time]=${currentTime}&data_set[type]=${$('#type').children("option:selected").val()}`
174
  );
175
}
176

    
177
function updateHeaderControls() {
178
  document.getElementById('time').value = currentTime;
179
}
180

    
181
function setTimeline() {
182
  $('#timeline').text(currentTime + ":00");
183
  $('#timeline').attr('class', 'time hour-' + currentTime);
184
}
185

    
186
function loadCurrentTimeHeatmap(opendataRoute, positionsRoute) {
187

    
188
  dataSourceRoute = opendataRoute;
189
  data = [];
190

    
191
  name = $('#type').children("option:selected").val();
192
  date = $('#date').val()
193
  currentTime = parseInt($('#time').children("option:selected").val());
194
  setTimeline();
195
  $.ajax({
196
    type: 'POST',
197
    url: positionsRoute + '/' + name,
198
    success: function(result) {
199
      drawDataSourceMarks(result);
200
      $.ajax({
201
        type: "POST",
202
        url: dataSourceRoute + '/' +  name + '/' + date + '/' + currentTime,
203
        success: function(result) {
204
          data[currentTime] = result;
205
          drawHeatmap(data[currentTime]);
206
        }
207
      })
208
    }
209
  });
210

    
211
  preload(currentTime, 1);
212
  preload(currentTime, -1);
213

    
214
}
215

    
216
function drawDataSourceMarks(data) {
217
  if (marksLayer != null) {
218
    L.removeLayer(marksLayer);
219
  }
220
  marksLayer = L.layerGroup();
221
  for (var key in data) {
222
    const {x,y,name} = data[key];
223
    const pop = 
224
      L.popup({autoPan: false})
225
        .setLatLng([x, y])
226
        .setContent(genPopUp(name, 0, 0, 1,1));
227
    const newCircle = 
228
      L.circle([x, y], {radius: 2,fillOpacity: 0.8, color: '#004fb3',fillColor: '#004fb3', bubblingMouseEvents: true})
229
        .bindPopup(pop);
230
    globalMarkersHolder[x+''+y] = [newCircle, pop]; //add new marker to global holders
231
    marksLayer.addLayer(
232
      newCircle
233
    );
234
  }
235

    
236
  marksLayer.setZIndex(-1).addTo(mymap);
237

    
238
}
239

    
240
function preload(time, change) {
241

    
242
  var ntime = time + change; 
243
  if (0 <=  ntime && ntime <= 23) {
244
      $.ajax({
245
        type: "POST",
246
        url: dataSourceRoute + '/' +  name + '/' + date + '/' + ntime,
247
        success: function(result) {
248
          data[ntime] = result;
249
          preload(ntime, change);
250
        }
251
      });
252
  }
253

    
254
}
255

    
256

    
257
function drawHeatmap(data) {
258

    
259
  // Todo still switched
260
  if (data['items'] != null) {
261
    //Bind back popups for markers (we dont know if there is any data for this marker or not)
262
    if (Object.keys(globalMarkersChanged).length){
263
      Object.keys(globalMarkersChanged).forEach(function(key) {
264
        globalMarkersChanged[key][0].bindPopup(globalMarkersChanged[key][1]);
265
    });
266
      globalMarkersChanged = {};
267
    }
268
    points = data['items'].map((point) => { 
269
      const {x,y,number} = point;
270
      const key = x+''+y;
271
      const holder = globalMarkersHolder[key];
272
      if (!globalMarkersChanged[key] && number){
273
        //There is data for this marker => unbind popup with zero value
274
        holder[0] = holder[0].unbindPopup();
275
        globalMarkersChanged[key] = holder;
276
      }
277
      return [x, y, number]; 
278
    });
279
    if (heatmapLayer != null) {
280
      mymap.removeLayer(heatmapLayer);
281
    }
282
    heatmapLayer = L.heatLayer(points, {'max' : data['max'], 'minOpacity' : 0.5, 'radius' : 35, 'blur' : 30}).addTo(mymap);
283
  }
284
  else {
285
    if (heatmapLayer != null) {
286
      mymap.removeLayer(heatmapLayer);
287
    }
288
  }
289

    
290
  // var heat_01 = ...
291
  // on background map.addLayer(heat_01) -> map.removeLayer(heat_01);
292
  // $(.leaflet-heatmap-layer).css('opacity', 'value');
293
}
294

    
295
function checkDataSetsAvailability(route) {
296

    
297
  $.ajax({
298
    type: "POST",
299
    // Todo it might be good idea to change db collections format
300
    url: route + '/' + $('#date').val(),
301
    success: function(result) {
302
      updateAvailableDataSets(result);
303
    }
304
  });
305
}
306

    
307
var allOptionsDisabled = false;
308

    
309
function updateAvailableDataSets(available) {
310
  
311
  var isOptionEnabled = true;
312
  $("#type > option").each(function() {
313
    if((this.value in available) == false) {
314
      $(this).prop('disabled', true);
315
      $(this).prop('selected', false);  
316
    }
317
    else {
318
      $(this).prop('disabled', false)
319
      if (allOptionsDisabled) {
320
        $(this).prop('selected', true);
321
        allOptionsDisabled = false;
322
      }
323
      isOptionEnabled = false;
324
    }
325
  });
326
  allOptionsDisabled = isOptionEnabled;
327

    
328
  $('#submit-btn').prop('disabled', isOptionEnabled);
329

    
330
}
331

    
332

    
333
function formatDate(date) {
334
  var day = String(date.getDate());
335
  var month = String(date.getMonth() + 1);
336

    
337
  if (day.length === 1) {
338
    day = '0' + day;
339
  }
340

    
341
  if (month.length === 1) {
342
    month = '0' + month;
343
  }
344

    
345
  return date.getFullYear() + '-' + month + '-' + day;
346
}
347

    
348
function initDatepicker(availableDatesSource) {
349
  var availableDates = '';
350

    
351
  $.ajax({
352
    type: 'GET',
353
    url: availableDatesSource,
354
    success: function(result) {
355
      availableDates = String(result).split(',');
356
    }
357
  }).then(function () {
358
    $('#date').datepicker({
359
      format: 'yyyy-mm-dd',
360
      language: 'cs',
361
      beforeShowDay: function(date) {
362
        if (availableDates.indexOf(formatDate(date)) < 0) {
363
          return {enabled: false, tooltip: 'Žádná data'}
364
        }
365
        else {
366
          return {enabled: true}
367
        }
368
      },
369
      autoclose: true
370
    });
371
  });
372
}
(8-8/8)