Projekt

Obecné

Profil

Stáhnout (10.7 KB) Statistiky
| Větev: | Revize:
1
/* global L */
2
/* global $ */
3
var mymap
4
var heatmapLayer = null
5
var marksLayer = null
6

    
7
var startX = 49.7248
8
var startY = 13.3521
9
var startZoom = 17
10

    
11
var dataSourceRoute
12
var currentTime
13
var name
14
var date
15

    
16
var timer
17
var isAnimationRunning = false
18
var data = []
19

    
20
var info = []
21
var currenInfo = 0
22

    
23
// holds all instances of markers for bind/unbind popup purpose
24
// contains: {key:[L.circle,L.pupup]}
25
// key: x and y, x + '' + y string
26
const globalMarkersHolder = {}
27

    
28
// all marker from which popup was removed
29
// contains: {key:[L.circle,L.pupup]}
30
// key: x and y, x + '' + y string
31
let globalMarkersChanged = {}
32

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

    
46
  if (!sum) {
47
    previousButton = ''
48
    nextButton = ''
49
    posInfo = ''
50
  }
51
  return `
52
  ${header}
53
  ${digitInfo}
54
  ${genPopUpControls([previousButton, posInfo, nextButton])}
55
  `
56
}
57
/**
58
 * Initialize leaflet map on start position which can be default or set based on user action
59
 */
60
// eslint-disable-next-line no-unused-vars
61
function initMap () {
62
  startX = localStorage.getItem('lat') || startX
63
  startY = localStorage.getItem('lng') || startY
64
  startZoom = localStorage.getItem('zoom') || startZoom
65

    
66
  mymap = L.map('heatmap').setView([startX, startY], startZoom)
67

    
68
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
69
    attribution: '',
70
    maxZoom: 19
71
  }).addTo(mymap)
72

    
73
  mymap.on('click', showInfo)
74
}
75

    
76

    
77
function showInfo (e) {
78
  info = []
79
  currenInfo = 0
80

    
81
  // https://wiki.openstreetmap.org/wiki/Zoom_levels
82
  // Todo change to variable - it is used in heatmap init
83
  var stile = 40075016.686 * Math.cos(startX) / Math.pow(2, mymap.getZoom())
84
  var radius = 25 * stile / 256
85

    
86
  var i = 0
87
  var lat = 0
88
  var lng = 0
89

    
90
  var total = 0
91
  data[currentTime].items.forEach(element => {
92
    if (e.latlng.distanceTo(new L.LatLng(element.x, element.y)) < radius) {
93
      lat += element.x
94
      lng += element.y
95
      info[i] = { place: element.place, number: element.number }
96
      total += parseInt(element.number)
97
      i++
98
    }
99
  })
100

    
101
  if (info.length > 0) {
102
    const { place, number } = info[currenInfo]
103
    L.popup({
104
      autoPan: false
105
    })
106
      .setLatLng([lat / i, lng / i])
107
      .setContent(genPopUp(place, number, total, currenInfo + 1, info.length))
108
      .openOn(mymap)
109

    
110
    if (info.length === 1) {
111
      $('#previous-info-btn').prop('disabled', true)
112
      $('#next-info-btn').prop('disabled', true)
113
      $('.popup-controls').hide()
114
    }
115
  }
116
}
117

    
118
// eslint-disable-next-line no-unused-vars
119
function previousInfo () {
120
  currenInfo = (currenInfo + info.length - 1) % info.length
121
  displayInfoText()
122
}
123

    
124
// eslint-disable-next-line no-unused-vars
125
function nextInfo () {
126
  currenInfo = (currenInfo + 1) % info.length
127
  displayInfoText()
128
}
129

    
130
function displayInfoText () {
131
  $('#place-info').html(info[currenInfo].place)
132
  $('#digit-info').html(info[currenInfo].number)
133
  $('#count-info').html(currenInfo + 1 + ' z ' + info.length)
134
}
135

    
136
// eslint-disable-next-line no-unused-vars
137
function setMapView (latitude, longitude, zoom) {
138
  localStorage.setItem('lat', latitude)
139
  localStorage.setItem('lng', longitude)
140
  localStorage.setItem('zoom', zoom)
141
  mymap.setView([latitude, longitude], zoom)
142
}
143

    
144
/**
145
 * Change animation start from playing to stopped or the other way round
146
 */
147
// eslint-disable-next-line no-unused-vars
148
function changeAnimationState () {
149
  isAnimationRunning = !isAnimationRunning
150
  if (isAnimationRunning) {
151
    $('#play-pause').attr('class', 'pause')
152
    timer = setInterval(
153
      function () {
154
        next()
155
      },
156
      800
157
    )
158
  } else {
159
    clearTimeout(timer)
160
    $('#play-pause').attr('class', 'play')
161
  }
162
}
163

    
164
// eslint-disable-next-line no-unused-vars
165
function previous () {
166
  currentTime = (currentTime + 23) % 24
167
  drawHeatmap(data[currentTime])
168
  setTimeline()
169
  mymap.closePopup()
170
  updateHeaderControls()
171
  changeUrl()
172
}
173

    
174
function next () {
175
  currentTime = (currentTime + 1) % 24
176
  drawHeatmap(data[currentTime])
177
  setTimeline()
178
  mymap.closePopup()
179
  updateHeaderControls()
180
  changeUrl()
181
}
182

    
183
/**
184
 * Change browser url based on animation step
185
 */
186
function changeUrl () {
187
  window.history.pushState(
188
    '',
189
    document.title,
190
    window.location.origin + window.location.pathname + `?data_set[date]=${$('#date').val()}&data_set[time]=${currentTime}&data_set[type]=${$('#type').children('option:selected').val()}`
191
  )
192
}
193

    
194
function updateHeaderControls () {
195
  document.getElementById('time').value = currentTime
196
}
197

    
198
function setTimeline () {
199
  $('#timeline').text(currentTime + ':00')
200
  $('#timeline').attr('class', 'time hour-' + currentTime)
201
}
202

    
203
/**
204
 * Load and display heatmap layer for current data
205
 * @param {string} opendataRoute route to dataset source
206
 * @param {string} positionsRoute  route to dataset postitions source
207
 */
208
// eslint-disable-next-line no-unused-vars
209
function loadCurrentTimeHeatmap (opendataRoute, positionsRoute) {
210
  dataSourceRoute = opendataRoute
211
  data = []
212

    
213
  name = $('#type').children('option:selected').val()
214
  date = $('#date').val()
215
  currentTime = parseInt($('#time').children('option:selected').val())
216
  setTimeline()
217
  $.ajax({
218
    type: 'POST',
219
    url: positionsRoute + '/' + name,
220
    success: function (result) {
221
      drawDataSourceMarks(result)
222
      $.ajax({
223
        type: 'POST',
224
        url: dataSourceRoute + '/' + name + '/' + date + '/' + currentTime,
225
        success: function (result) {
226
          data[currentTime] = result
227
          drawHeatmap(data[currentTime])
228
        }
229
      })
230
    }
231
  })
232

    
233
  preload(currentTime, 1)
234
  preload(currentTime, -1)
235
}
236

    
237
function drawDataSourceMarks (data) {
238
  if (marksLayer != null) {
239
    L.removeLayer(marksLayer)
240
  }
241
  marksLayer = L.layerGroup()
242
  for (var key in data) {
243
    const { x, y, name } = data[key]
244
    const pop =
245
      L.popup({ autoPan: false })
246
        .setLatLng([x, y])
247
        .setContent(genPopUp(name, 0, 0, 1, 1))
248
    const newCircle =
249
      L.circle([x, y], { radius: 2, fillOpacity: 0.8, color: '#004fb3', fillColor: '#004fb3', bubblingMouseEvents: true })
250
        .bindPopup(pop)
251
    globalMarkersHolder[x + '' + y] = [newCircle, pop] // add new marker to global holders
252
    marksLayer.addLayer(
253
      newCircle
254
    )
255
  }
256

    
257
  marksLayer.setZIndex(-1).addTo(mymap)
258
}
259

    
260
function preload (time, change) {
261
  var ntime = time + change
262
  if (ntime >= 0 && ntime <= 23) {
263
    $.ajax({
264
      type: 'POST',
265
      url: dataSourceRoute + '/' + name + '/' + date + '/' + ntime,
266
      success: function (result) {
267
        data[ntime] = result
268
        preload(ntime, change)
269
      }
270
    })
271
  }
272
}
273

    
274
function drawHeatmap (data) {
275
  // Todo still switched
276
  if (data.items != null) {
277
    // Bind back popups for markers (we dont know if there is any data for this marker or not)
278
    if (Object.keys(globalMarkersChanged).length) {
279
      Object.keys(globalMarkersChanged).forEach(function (key) {
280
        globalMarkersChanged[key][0].bindPopup(globalMarkersChanged[key][1])
281
      })
282
      globalMarkersChanged = {}
283
    }
284
    const points = data.items.map((point) => {
285
      const { x, y, number } = point
286
      const key = x + '' + y
287
      const holder = globalMarkersHolder[key]
288
      if (!globalMarkersChanged[key] && number) {
289
        // There is data for this marker => unbind popup with zero value
290
        holder[0] = holder[0].unbindPopup()
291
        globalMarkersChanged[key] = holder
292
      }
293
      return [x, y, number]
294
    })
295
    if (heatmapLayer != null) {
296
      mymap.removeLayer(heatmapLayer)
297
    }
298
    heatmapLayer = L.heatLayer(points, { max: data.max, minOpacity: 0.5, radius: 35, blur: 30 }).addTo(mymap)
299
  } else {
300
    if (heatmapLayer != null) {
301
      mymap.removeLayer(heatmapLayer)
302
    }
303
  }
304

    
305
  // var heat_01 = ...
306
  // on background map.addLayer(heat_01) -> map.removeLayer(heat_01);
307
  // $(.leaflet-heatmap-layer).css('opacity', 'value');
308
}
309

    
310
/**
311
 * Checks dataset availibility
312
 * @param {string} route authority for datasets availibility checks 
313
 */
314
// eslint-disable-next-line no-unused-vars
315
function checkDataSetsAvailability (route) {
316
  $.ajax({
317
    type: 'POST',
318
    // Todo it might be good idea to change db collections format
319
    url: route + '/' + $('#date').val(),
320
    success: function (result) {
321
      updateAvailableDataSets(result)
322
    }
323
  })
324
}
325

    
326
var allOptionsDisabled = false
327

    
328
function updateAvailableDataSets (available) {
329
  var isOptionEnabled = true
330
  $('#type > option').each(function () {
331
    if ((this.value in available) === false) {
332
      $(this).prop('disabled', true)
333
      $(this).prop('selected', false)
334
    } else {
335
      $(this).prop('disabled', false)
336
      if (allOptionsDisabled) {
337
        $(this).prop('selected', true)
338
        allOptionsDisabled = false
339
      }
340
      isOptionEnabled = false
341
    }
342
  })
343
  allOptionsDisabled = isOptionEnabled
344

    
345
  $('#submit-btn').prop('disabled', isOptionEnabled)
346
}
347

    
348
function formatDate (date) {
349
  var day = String(date.getDate())
350
  var month = String(date.getMonth() + 1)
351

    
352
  if (day.length === 1) {
353
    day = '0' + day
354
  }
355

    
356
  if (month.length === 1) {
357
    month = '0' + month
358
  }
359

    
360
  return date.getFullYear() + '-' + month + '-' + day
361
}
362

    
363
// eslint-disable-next-line no-unused-vars
364
function initDatepicker (availableDatesSource) {
365
  var availableDates = ''
366

    
367
  $.ajax({
368
    type: 'GET',
369
    url: availableDatesSource,
370
    success: function (result) {
371
      availableDates = String(result).split(',')
372
    }
373
  }).then(function () {
374
    $('#date').datepicker({
375
      format: 'yyyy-mm-dd',
376
      language: 'cs',
377
      beforeShowDay: function (date) {
378
        if (availableDates.indexOf(formatDate(date)) < 0) {
379
          return { enabled: false, tooltip: 'Žádná data' }
380
        } else {
381
          return { enabled: true }
382
        }
383
      },
384
      autoclose: true
385
    })
386
  })
387
}
388

    
389
function initLocationsMenu() {
390
  var locationsWrapper = '.locations';
391
  var locationsDisplayClass = 'show';
392

    
393
  if ($(window).width() <= 480) {  
394
    $(locationsWrapper).removeClass(locationsDisplayClass);
395
  }
396
  else {
397
    $(locationsWrapper).addClass(locationsDisplayClass);
398
  }
399
}
400

    
401
function openDatepicker() {
402
  if ($(window).width() <= 990) {
403
    $('.navbar-collapse').collapse();
404
  }
405

    
406
  $('#date').datepicker('show')
407
}
    (1-1/1)