-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
408 lines (328 loc) · 12.4 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Define an array of GeoJSON file URLs in the desired order
const jsonUrls = [
'./static/meta.json'
]
// Define an array of GeoJSON file URLs in the desired order
const geoJsonUrls = [
'./static/flensburg_stadtteile.geojson',
'./static/flensburg_details.geojson'
]
const queryform = document.querySelector('#form')
let currentClickedLayer = null
let currentClickedMarker = null
let metaDataArray = null
let geojsonLayer = null
const circleMarkers = []
const geoJsonLayers = []
const style1 = {
fillColor: '#fff',
fillOpacity: .6,
color: '#989898',
weight: 2,
}
const style2 = {
}
const style3 = {
}
// Define different pointToLayer functions with an index parameter
const pointToLayerFunctions = [
(feature, latlng, index) => {
latlng.on('click', function (e) {
console.debug('0')
})
},
(feature, latlng, index) => {
// Calculate the radius based on the current zoom level
const zoom = map.getZoom()
const radius = calculateRadius(zoom)
// Custom pointToLayer logic for the third GeoJSON layer
const circleMarker = L.circleMarker(latlng, {
weight: 0,
radius: radius,
color: '#f95016',
fillOpacity: 1
})
const year = feature.properties.ujahr
const utyp1 = getMetaValue(metaDataArray.utyp1, feature.properties.utyp1)
// Add a tooltip to the CircleMarker
const label = `${utyp1.name}, ${year}`
circleMarker.bindTooltip(label)
// Add an onClick event handler to each CircleMarker
circleMarker.on('click', function (e) {
const currentZoom = map.getZoom()
// Set minimum zoom level
let zoomView = 18
if (zoomView < currentZoom) {
zoomView = currentZoom
}
// Center the map on the CircleMarker's location
map.setView(latlng, zoomView)
const detail = {
ukategorie: getMetaValue(metaDataArray.ukategorie, e.target.feature.properties.ukategorie),
uwochentag: getMetaValue(metaDataArray.uwochentag, e.target.feature.properties.uwochentag),
umonat: getMetaValue(metaDataArray.umonat, e.target.feature.properties.umonat),
ujahr: feature.properties.ujahr,
ustunde: removeLeadingZero(feature.properties.ustunde),
uland: getMetaValue(metaDataArray.uland, e.target.feature.properties.uland),
utyp1: getMetaValue(metaDataArray.utyp1, e.target.feature.properties.utyp1),
uart: getMetaValue(metaDataArray.uart, e.target.feature.properties.uart),
ulichtverh: getMetaValue(metaDataArray.ulichtverh, e.target.feature.properties.ulichtverh),
istrad: getMetaValue(metaDataArray.istrad, e.target.feature.properties.istrad),
istpkw: getMetaValue(metaDataArray.istpkw, e.target.feature.properties.istpkw),
istfuss: getMetaValue(metaDataArray.istfuss, e.target.feature.properties.istfuss),
istgkfz: getMetaValue(metaDataArray.istgkfz, e.target.feature.properties.istgkfz),
istkrad: getMetaValue(metaDataArray.istkrad, e.target.feature.properties.istkrad),
istsonstig: getMetaValue(metaDataArray.istsonstig, e.target.feature.properties.istsonstig)
}
let detailOutput = ''
for (const key of Object.keys(detail)) {
const value = detail[key]
if (value !== undefined) {
if (key === 'umonat') {
detailOutput += `<li><strong>Monat</strong> ${value.name}</li>`
}
if (key === 'uland') {
detailOutput += `<li><strong>Bundesland</strong> ${value.name}</li>`
}
if (key === 'ujahr') {
detailOutput += `<li><strong>Jahr</strong> ${value}</li>`
}
if (key === 'ustunde') {
detailOutput += `<li><strong>Ungefähr</strong> ${value} Uhr</li>`
}
if (key === 'uwochentag') {
detailOutput += `<li><strong>Tag</strong> ${value.name}</li>`
}
if (key === 'istrad') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'istpkw') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'istfuss') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'istgkfz') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'istkrad') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'istsonstig') {
detailOutput += `<li><strong>-</strong> ${value.name}</li>`
}
if (key === 'ukategorie') {
detailOutput += `<li class="text-xl"><strong>${value.name}</strong></li>`
}
if (key === 'ulichtverh') {
detailOutput += `<li><strong>Lichtverhältnisse</strong> ${value.name}</li>`
}
if (key === 'utyp1') {
detailOutput += `<li><strong>Unfalltyp</strong> ${value.name}</li>`
}
if (key === 'uart') {
detailOutput += `<li><strong>Unfallart</strong> ${value.name}</li>`
}
}
}
const element = document.querySelector('#details')
element.innerHTML = `<ul class="p-3 space-y-2 bg-gray-700 text-white mb-4 md:mb-8"> ${detailOutput}</ul>`
// Trigger click events on CircleMarkers in previous GeoJSON layers
geoJsonLayers[index - 1].fire('click')
})
return circleMarker
},
]
// Define different onEachFeature functions with an index parameter
const onEachFeatureFunctions = [
(feature, layer, index) => {
// Add a click event handler for each layer
layer.on('click', function () {
// Check if there was a previously clicked layer
if (currentClickedLayer) {
// Reset the fill color of the previously clicked layer
currentClickedLayer.setStyle({ fillColor: '#fff' })
}
// Set the fill color of the clicked layer
layer.setStyle({ fillColor: '#d1e4fd' })
// Update the currently clicked layer
currentClickedLayer = layer
})
},
(feature, layer, index) => {
// Add a click event handler for each layer
layer.on('click', function () {
// Check if there was a previously clicked marker
if (currentClickedMarker) {
// Reset the color of the previously clicked marker
currentClickedMarker.setStyle({ fillColor: '#f95016' })
}
// Set the fill color of the clicked marker
layer.setStyle({ fillColor: '#00f' });
// Update the currently clicked layer
currentClickedMarker = layer
})
},
(feature, layer, index) => {
// Custom logic for the third GeoJSON layer with index = 2
},
]
const styles = [style1, style2, style3]
// Initialize map
const map = L.map('map', {
maxZoom: 19
}).setView([54.7836, 9.4121], 2)
L.tileLayer.wms('https://sgx.geodatenzentrum.de/wms_basemapde?SERVICE=WMS&Request=GetCapabilities', {
layers: 'de_basemapde_web_raster_grau',
maxZoom: 20,
attribution: '<a href="https://www.bkg.bund.de">© GeoBasis-DE / BKG 2024</a> | <a href="https://creativecommons.org/licenses/by/4.0">CC BY 4.0</a>'
}).addTo(map)
// Create an array of jsonPromises for fetching JSON data
const jsonPromises = jsonUrls.map((url, index) =>
fetch(url)
.then((response) => response.json())
.then((data) => {
return data
})
)
// Create an array of geoJsonPromises for fetching GeoJSON data
const geoJsonPromises = geoJsonUrls.map((url, index) =>
fetch(url)
.then((response) => response.json())
.then((data) => {
// let geojsonLayer
if (index === geoJsonUrls.length - 1) {
geojsonLayer = L.geoJSON(data, {
pointToLayer: (feature, latlng) => {
// Call the corresponding pointToLayer function with the index parameter
return pointToLayerFunctions[index](feature, latlng, index)
},
onEachFeature: (feature, layer) => {
// Call the corresponding onEachFeature function with the index parameter
onEachFeatureFunctions[index](feature, layer, index)
},
})
} else {
// For other layers, use the default onEachFeature function
geojsonLayer = L.geoJSON(data, {
style: styles[index],
onEachFeature: (feature, layer) => {
// Call the corresponding onEachFeature function with the index parameter
onEachFeatureFunctions[index](feature, layer, index)
},
})
}
// Store the GeoJSON layer in the geoJsonLayers array
geoJsonLayers.push(geojsonLayer)
return geojsonLayer
})
)
// Define a click event handler
function handleLayerClick(event) {
// Perform your custom action here, using event properties
console.log('Click event:', event)
// Example: Change the style of the clicked layer
event.target.setStyle({ fillColor: 'red' })
}
// Use Promise.all to wait for all geoJsonPromises to resolve
Promise.all(jsonPromises)
.then((data) => {
let tmpData = data
while (Array.isArray(tmpData) && tmpData.length === 1) {
tmpData = tmpData[0]
}
metaDataArray = tmpData
createSelectElement('utyp1', 'utyp1Wrapper', metaDataArray['utyp1'], 'Unfall Typ auswählen')
createSelectElement('uart', 'uartWrapper', metaDataArray['uart'], 'Unfall Hergang auswählen')
})
.catch((error) => {
console.error('Error fetching GeoJSON data:', error)
})
// Use Promise.all to wait for all geoJsonPromises to resolve
Promise.all(geoJsonPromises)
.then((layers) => {
layers[0].addTo(map)
layers[1].addTo(map)
// Calculate the bounds based on all GeoJSON layers
const bounds = L.featureGroup(layers).getBounds()
const center = bounds.getCenter()
const newLatitude = center.lat + 0.01
const newCenter = L.latLng(newLatitude, center.lng)
map.setView(newCenter, 13)
// Event listener to update circle marker radius when zoom changes
map.on('zoomend', function () {
const zoom = map.getZoom()
layers[1].eachLayer(function (layer) {
const radius = calculateRadius(zoom)
layer.setStyle({ radius: radius });
});
})
// Create a LayerGroup and add your layers to it
const layerGroup = L.layerGroup(...layers)
// Add a click event listener to the LayerGroup
layerGroup.on('click', handleLayerClick)
})
.catch((error) => {
console.error('Error fetching GeoJSON data:', error)
})
function getMetaValue(array, property) {
return array.find((item) => item.id === removeLeadingZero(property))
}
function removeLeadingZero(inputString) {
if (inputString !== null && inputString.startsWith('0')) {
return parseInt(inputString.substring(1))
}
return parseInt(inputString)
}
// Create label element and select element with options
function createSelectElement(id, target, options, label) {
const labelElement = document.createElement('label')
labelElement.classList = 'block text-gray-700 text-sm font-bold mb-2'
labelElement.setAttribute('for', id)
labelElement.textContent = label
const selectElement = document.createElement('select')
selectElement.classList = 'shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline cursor-pointer'
selectElement.setAttribute('name', id)
selectElement.setAttribute('id', id)
// Add an extra option element to unselect all
const optionElement = document.createElement('option')
optionElement.value = 0
optionElement.textContent = 'Keine Auswahl'
selectElement.appendChild(optionElement)
// Loop through the options array and create option elements
options.forEach(option => {
const optionElement = document.createElement('option')
optionElement.value = option['id']
optionElement.textContent = option['name']
selectElement.appendChild(optionElement)
})
// Append the select element to the DOM
document.querySelector(`#${target}`).append(labelElement)
document.querySelector(`#${target}`).append(selectElement)
}
function calculateRadius(zoom) {
let value
if (zoom >= 16) {
value = 6
}
else if (zoom >= 13 && zoom < 16) {
value = 4
}
else if (zoom < 13) {
value = 2
}
return value
}
if (queryform.length) {
queryform.addEventListener('change', (e) => {
e.preventDefault()
const data = new FormData(queryform)
const districtId = parseInt(data.get('district'))
const year = data.getAll('year')
const utyp1 = data.get('utyp1')
const uart = data.get('uart')
console.log(geojsonLayer)
geojsonLayer
// renderPromise(dataObject, districtId, onlyFellings)
})
}