Projekt

Obecné

Profil

Stáhnout (9.44 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
// holds all instances of markers for bind/unbind popup purpose
21
// contains: {key:[L.circle,L.pupup]}
22
// key: x and y, x + '' + y string
23
const globalMarkersHolder = {}
24

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

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

    
42
  if (!sum) {
43
    previousButton = ''
44
    nextButton = ''
45
    posInfo = ''
46
  }
47
  return `
48
  ${header}
49
  ${digitInfo}
50
  ${genPopUpControls([previousButton, posInfo, nextButton])}
51
  `
52
}
53
// eslint-disable-next-line no-unused-vars
54
function initMap () {
55
  mymap = L.map('heatmap').setView([startX, startY], startZoom)
56

    
57
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
58
    attribution: '',
59
    maxZoom: 19
60
  }).addTo(mymap)
61

    
62
  mymap.on('click', showInfo)
63
}
64

    
65
var info = []
66
var currenInfo = 0
67

    
68
function showInfo (e) {
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
  if (info.length > 0) {
93
    const { place, number } = info[currenInfo]
94
    L.popup({
95
      autoPan: false
96
    })
97
      .setLatLng([lat / i, lng / i])
98
      .setContent(genPopUp(place, number, total, currenInfo + 1, info.length))
99
      .openOn(mymap)
100

    
101
    if (info.length === 1) {
102
      $('#previous-info-btn').prop('disabled', true)
103
      $('#next-info-btn').prop('disabled', true)
104
      $('.popup-controls').hide()
105
    }
106
  }
107
}
108

    
109
// eslint-disable-next-line no-unused-vars
110
function previousInfo () {
111
  currenInfo = (currenInfo + info.length - 1) % info.length
112
  displayInfoText()
113
}
114

    
115
// eslint-disable-next-line no-unused-vars
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
// eslint-disable-next-line no-unused-vars
128
function setMapView (latitude = startX, longitude = startY, zoom = startZoom) {
129
  mymap.setView([latitude, longitude], zoom)
130
}
131

    
132
// eslint-disable-next-line no-unused-vars
133
function changeAnimationState () {
134
  isAnimationRunning = !isAnimationRunning
135
  if (isAnimationRunning) {
136
    $('#play-pause').attr('class', 'pause')
137
    timer = setInterval(
138
      function () {
139
        next()
140
      },
141
      800
142
    )
143
  } else {
144
    clearTimeout(timer)
145
    $('#play-pause').attr('class', 'play')
146
  }
147
}
148

    
149
// eslint-disable-next-line no-unused-vars
150
function previous () {
151
  currentTime = (currentTime + 23) % 24
152
  drawHeatmap(data[currentTime])
153
  setTimeline()
154
  mymap.closePopup()
155
  updateHeaderControls()
156
  changeUrl()
157
}
158

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

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

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

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

    
185
// eslint-disable-next-line no-unused-vars
186
function loadCurrentTimeHeatmap (opendataRoute, positionsRoute) {
187
  dataSourceRoute = opendataRoute
188
  data = []
189

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

    
210
  preload(currentTime, 1)
211
  preload(currentTime, -1)
212
}
213

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

    
234
  marksLayer.setZIndex(-1).addTo(mymap)
235
}
236

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

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

    
282
  // var heat_01 = ...
283
  // on background map.addLayer(heat_01) -> map.removeLayer(heat_01);
284
  // $(.leaflet-heatmap-layer).css('opacity', 'value');
285
}
286

    
287
// eslint-disable-next-line no-unused-vars
288
function checkDataSetsAvailability (route) {
289
  $.ajax({
290
    type: 'POST',
291
    // Todo it might be good idea to change db collections format
292
    url: route + '/' + $('#date').val(),
293
    success: function (result) {
294
      updateAvailableDataSets(result)
295
    }
296
  })
297
}
298

    
299
var allOptionsDisabled = false
300

    
301
function updateAvailableDataSets (available) {
302
  var isOptionEnabled = true
303
  $('#type > option').each(function () {
304
    if ((this.value in available) === false) {
305
      $(this).prop('disabled', true)
306
      $(this).prop('selected', false)
307
    } else {
308
      $(this).prop('disabled', false)
309
      if (allOptionsDisabled) {
310
        $(this).prop('selected', true)
311
        allOptionsDisabled = false
312
      }
313
      isOptionEnabled = false
314
    }
315
  })
316
  allOptionsDisabled = isOptionEnabled
317

    
318
  $('#submit-btn').prop('disabled', isOptionEnabled)
319
}
320

    
321
function formatDate (date) {
322
  var day = String(date.getDate())
323
  var month = String(date.getMonth() + 1)
324

    
325
  if (day.length === 1) {
326
    day = '0' + day
327
  }
328

    
329
  if (month.length === 1) {
330
    month = '0' + month
331
  }
332

    
333
  return date.getFullYear() + '-' + month + '-' + day
334
}
335

    
336
// eslint-disable-next-line no-unused-vars
337
function initDatepicker (availableDatesSource) {
338
  var availableDates = ''
339

    
340
  $.ajax({
341
    type: 'GET',
342
    url: availableDatesSource,
343
    success: function (result) {
344
      availableDates = String(result).split(',')
345
    }
346
  }).then(function () {
347
    $('#date').datepicker({
348
      format: 'yyyy-mm-dd',
349
      language: 'cs',
350
      beforeShowDay: function (date) {
351
        if (availableDates.indexOf(formatDate(date)) < 0) {
352
          return { enabled: false, tooltip: 'Žádná data' }
353
        } else {
354
          return { enabled: true }
355
        }
356
      },
357
      autoclose: true
358
    })
359
  })
360
}
    (1-1/1)