-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
432 lines (380 loc) · 16 KB
/
index.html
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-time Noise Map</title>
<script src='https://api.mapbox.com/mapbox-gl-js/v3.6.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v3.6.0/mapbox-gl.css' rel='stylesheet' />
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 80px;
bottom: 0;
width: 100%;
}
#map-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
}
#info-panel {
position: relative;
top: 0;
left: 0;
right: 0;
height: 80px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
font-family: Arial, sans-serif;
font-size: 14px;
z-index: 1;
padding: 5px 0;
}
#control-panel {
position: relative;
left: 0;
right: 0;
height: 40px;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1;
}
#control-panel button {
margin: 0 5px;
padding: 5px 10px;
}
.mapboxgl-user-location-dot {
width: 15px;
height: 15px;
border-radius: 50%;
background-color: #007cbf;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.25);
}
.mapboxgl-user-location-dot::before {
content: '';
width: 15px;
height: 15px;
border-radius: 50%;
position: absolute;
background-color: #007cbf;
opacity: 0.1;
animation: pulse 2s infinite;
}
.mapboxgl-user-location-dot::after {
content: '';
display: block;
width: 0;
height: 0;
border-radius: 50%;
border-top: 5px solid #fff;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@keyframes pulse {
0% {
transform: scale(1);
opacity: 1;
}
70% {
transform: scale(3);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 0;
}
}
#sound-meter {
width: 300px;
height: 30px;
background-color: #333;
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
border-radius: 15px;
overflow: hidden;
display: flex;
}
.meter-bar {
flex: 1;
height: 100%;
margin: 0 1px;
background-color: #ddd;
transition: height 0.1s ease-out;
}
</style>
</head>
<body>
<div id="map-overlay">
<div id="info-panel">
<span>Current: <span id="current-level">0</span> dB</span>
<span>10s Avg: <span id="avg-level">0</span> dB</span>
<span>Min: <span id="min-level">0</span> dB</span>
<span>Max: <span id="max-level">0</span> dB</span>
</div>
<div id="control-panel">
<button id="pauseBtn">Pause</button>
<button id="resumeBtn" disabled>Resume</button>
<button id="resetBtn">Reset</button>
</div>
</div>
<div id='map'></div>
<div id="sound-meter"></div>
<script>
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyDdvg3bdmO8-UnWiVPlptrWPr3Af77IerM",
authDomain: "noiselogger-7a546.firebaseapp.com",
databaseURL: "https://noiselogger-7a546-default-rtdb.firebaseio.com",
projectId: "noiselogger-7a546",
storageBucket: "noiselogger-7a546.appspot.com",
messagingSenderId: "1088883369572",
appId: "1:1088883369572:web:4047fde03df55f864b2171",
measurementId: "G-VPDTDN640G"
};
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
// Generate a unique ID for this user
const userId = 'user_' + Math.random().toString(36).substr(2, 9);
// Function to calculate weighted average
function calculateWeightedAverage(readings) {
if (readings.length === 0) return 0;
let sum = 0;
let weightSum = 0;
for (let i = 0; i < readings.length; i++) {
let weight = (i + 1) / readings.length; // More recent readings have higher weight
sum += readings[i] * weight;
weightSum += weight;
}
return sum / weightSum;
}
// Create sound meter bars
const soundMeter = document.getElementById('sound-meter');
const numBars = 30;
for (let i = 0; i < numBars; i++) {
const bar = document.createElement('div');
bar.className = 'meter-bar';
soundMeter.appendChild(bar);
}
// Function to update the sound meter
function updateSoundMeter(db) {
const bars = document.querySelectorAll('.meter-bar');
const percentage = Math.min(100, Math.max(0, db));
const activeBars = Math.floor(percentage / 100 * numBars);
bars.forEach((bar, index) => {
if (index < activeBars) {
bar.style.height = '100%';
if (index < numBars * 0.6) {
bar.style.backgroundColor = '#4CAF50'; // Green
} else if (index < numBars * 0.8) {
bar.style.backgroundColor = '#FFC107'; // Yellow
} else {
bar.style.backgroundColor = '#F44336'; // Red
}
} else {
bar.style.height = '10%';
bar.style.backgroundColor = '#ddd';
}
});
}
// Array to store sound level readings
let soundReadings = [];
let userLocation = [73.8, 15.6]; // Default location
let map;
let noiseHistory = []; // Array to store noise history
document.addEventListener('DOMContentLoaded', () => {
mapboxgl.accessToken = 'pk.eyJ1IjoicGxhbmVtYWQiLCJhIjoiY2x2MzZwbGRyMGdheDJtbXVwdDA4aDNyaCJ9.nbvz6aNGQo68xa4NtWH26A';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/planemad/cm0c67r0100py01qybp7s2enn',
center: userLocation,
zoom: 9,
hash: true
});
// Add geolocate control to the map
const geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true,
showUserHeading: true
});
map.addControl(geolocate);
map.on('load', () => {
// Trigger the geolocate control to start tracking the user's location
geolocate.trigger();
geolocate.on('geolocate', function (e) {
userLocation = [e.coords.longitude, e.coords.latitude];
map.flyTo({ center: userLocation, zoom: 14 });
});
map.addSource('noise', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': []
}
});
map.addLayer({
'id': 'noise-level',
'type': 'circle',
'source': 'noise',
'paint': {
'circle-radius': [
'interpolate',
['linear'],
['get', 'db'],
0, 5,
100, 50
],
'circle-color': [
'interpolate',
['linear'],
['get', 'db'],
0, '#00ff00',
50, '#ffff00',
100, '#ff0000'
],
'circle-opacity': 0.8
}
});
initializeAudio();
});
});
function initializeAudio() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Float32Array(bufferLength);
let isRecording = true;
let lastUpdateTime = 0;
let lastSnapshotTime = 0;
let allReadings = [];
function updateNoiseLevel(timestamp) {
if (!isRecording) return;
if (timestamp - lastUpdateTime >= 100) { // Update every 100ms for smoother meter
analyser.getFloatTimeDomainData(dataArray);
let rms = 0;
for (let i = 0; i < bufferLength; i++) {
rms += dataArray[i] * dataArray[i];
}
rms = Math.sqrt(rms / bufferLength);
let db = 20 * Math.log10(rms);
db = Math.max(30, Math.min(90, db + 90));
db = Math.round(db);
updateSoundMeter(db);
if (timestamp - lastUpdateTime >= 1000) { // Update stats every 1 second
document.getElementById('current-level').textContent = db;
soundReadings.push(db);
allReadings.push(db);
if (soundReadings.length > 10) {
soundReadings.shift();
}
let weightedAvg = Math.round(calculateWeightedAverage(soundReadings));
document.getElementById('avg-level').textContent = weightedAvg;
let min = Math.min(...allReadings);
let max = Math.max(...allReadings);
document.getElementById('min-level').textContent = min;
document.getElementById('max-level').textContent = max;
// Update Firebase with the user's current noise level and location
database.ref('users/' + userId).set({
location: userLocation,
db: db,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
lastUpdateTime = timestamp;
}
// Save snapshot every 10 seconds
if (timestamp - lastSnapshotTime >= 10000) {
noiseHistory.push({
coordinates: [...userLocation],
db: db,
timestamp: Date.now()
});
lastSnapshotTime = timestamp;
}
}
requestAnimationFrame(updateNoiseLevel);
}
updateNoiseLevel(0);
// Listen for changes in the Firebase database
database.ref('users').on('value', (snapshot) => {
const users = snapshot.val();
const features = [];
for (let userId in users) {
const user = users[userId];
features.push({
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': user.location
},
'properties': {
'db': user.db
}
});
}
if (map.loaded()) {
map.getSource('noise').setData({
'type': 'FeatureCollection',
'features': features
});
}
});
// Control buttons functionality
document.getElementById('pauseBtn').addEventListener('click', () => {
isRecording = false;
document.getElementById('pauseBtn').disabled = true;
document.getElementById('resumeBtn').disabled = false;
});
document.getElementById('resumeBtn').addEventListener('click', () => {
isRecording = true;
document.getElementById('pauseBtn').disabled = false;
document.getElementById('resumeBtn').disabled = true;
requestAnimationFrame(updateNoiseLevel);
});
document.getElementById('resetBtn').addEventListener('click', () => {
soundReadings = [];
allReadings = [];
noiseHistory = [];
document.getElementById('current-level').textContent = '0';
document.getElementById('avg-level').textContent = '0';
document.getElementById('min-level').textContent = '0';
document.getElementById('max-level').textContent = '0';
updateSoundMeter(0);
// Remove user data from Firebase
database.ref('users/' + userId).remove();
});
})
.catch(error => console.error('Error accessing microphone:', error));
} else {
console.error('getUserMedia is not supported in this browser');
}
}
</script>
</body>
</html>