-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
460 lines (380 loc) · 15.7 KB
/
script.js
File metadata and controls
460 lines (380 loc) · 15.7 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// Map variables
// let map;
// let hazardLayer, shelterLayer, resourceLayer, communityLayer;
// function initMap() {
// // Initialize the map centered on India
// map = L.map('map').setView([20.5937, 78.9629], 5);
// // Add OpenStreetMap tiles
// L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
// maxZoom: 18
// }).addTo(map);
// // Initialize layer groups
// hazardLayer = L.layerGroup().addTo(map);
// shelterLayer = L.layerGroup().addTo(map);
// resourceLayer = L.layerGroup().addTo(map);
// communityLayer = L.layerGroup().addTo(map);
// // Add sample data for Indian cities
// addIndianCityData();
// // Set up button event listeners
// setupMapControls();
// }
// function addIndianCityData() {
// // Delhi Data
// L.marker([28.6139, 77.2090]).addTo(hazardLayer)
// .bindPopup("<b>Delhi</b><br>Heatwave Alert")
// .openPopup();
// // Mumbai Data
// L.marker([19.0760, 72.8777]).addTo(shelterLayer)
// .bindPopup("<b>Mumbai</b><br>Emergency Shelter");
// // Bangalore Data
// L.marker([12.9716, 77.5946]).addTo(resourceLayer)
// .bindPopup("<b>Bangalore</b><br>Medical Resources");
// }
// function setupMapControls() {
// document.getElementById('showShelters').addEventListener('click', function() {
// map.removeLayer(hazardLayer);
// map.removeLayer(resourceLayer);
// map.removeLayer(communityLayer);
// shelterLayer.addTo(map);
// map.setView([19.0760, 72.8777], 10); // Focus on Mumbai
// });
// document.getElementById('showHazards').addEventListener('click', function() {
// map.removeLayer(shelterLayer);
// map.removeLayer(resourceLayer);
// map.removeLayer(communityLayer);
// hazardLayer.addTo(map);
// map.setView([28.6139, 77.2090], 10); // Focus on Delhi
// });
// document.getElementById('showResources').addEventListener('click', function() {
// map.removeLayer(hazardLayer);
// map.removeLayer(shelterLayer);
// map.removeLayer(communityLayer);
// resourceLayer.addTo(map);
// map.setView([12.9716, 77.5946], 10); // Focus on Bangalore
// });
// document.getElementById('showCommunity').addEventListener('click', function() {
// // For demonstration - same as resources
// map.removeLayer(hazardLayer);
// map.removeLayer(shelterLayer);
// map.removeLayer(resourceLayer);
// communityLayer.addTo(map);
// map.setView([20.5937, 78.9629], 5); // Back to India view
// });
// }
// // Initialize the map when page loads
// document.addEventListener('DOMContentLoaded', function() {
// initMap();
// });
//for news alert api connection
// In your script.js
// News API Configuration
// // Map variables
// fetch('newsupdate.html')
// .then(response => response.text())
// .then(data => {
// document.getElementById('newsWidgetContainer').innerHTML += data;
// })
// .catch(error => console.error('Error loading news widget:', error));
const API_KEY = '0f0b1a6904ba46caaef35433250405';
const BASE_URL = 'https://api.weatherapi.com/v1';
async function getWeather() {
const city = document.getElementById('cityInput').value.trim();
if (!city) {
alert('Please enter a city name');
return;
}
try {
// Get current weather and forecast
const response = await fetch(`${BASE_URL}/forecast.json?key=${API_KEY}&q=${city}&days=5&aqi=no&alerts=no`);
const data = await response.json();
if (data.error) {
throw new Error(data.error.message);
}
displayWeather(data);
} catch (error) {
console.error('Error fetching weather data:', error);
alert(`Error: ${error.message}`);
}
}
function displayWeather(data) {
const current = data.current;
const location = data.location;
// Display current weather
document.getElementById('cityName').textContent = `${location.name}, ${location.country}`;
const currentWeatherHTML = `
<img src="${current.condition.icon}" alt="${current.condition.text}">
<p>${Math.round(current.temp_c)}°C</p>
<p>${current.condition.text}</p>
<p>Humidity: ${current.humidity}%</p>
<p>Wind: ${current.wind_kph} km/h</p>
`;
document.getElementById('currentWeather').innerHTML = currentWeatherHTML;
// Display forecast
const forecastContainer = document.getElementById('forecast');
forecastContainer.innerHTML = '';
data.forecast.forecastday.forEach(day => {
const date = new Date(day.date);
const weekday = date.toLocaleDateString('en-US', { weekday: 'short' });
const forecastHTML = `
<div class="forecast-item">
<p>${weekday}</p>
<img src="${day.day.condition.icon}" alt="${day.day.condition.text}">
<p>${Math.round(day.day.maxtemp_c)}°/${Math.round(day.day.mintemp_c)}°</p>
</div>
`;
forecastContainer.innerHTML += forecastHTML;
});
// Show the weather container
document.getElementById('weatherInfo').style.display = 'block';
}
function toggleChatbot() {
const container = document.getElementById('chatbotContainer');
container.style.display = container.style.display === 'block' ? 'none' : 'block';
}
// Configuration
// Configuration
const EMERGENCY_CONTACT = {
email: "emergency@example.com",
phone: "+1234567890"
};
// State variables
let pressCount = 0;
let lastPressTime = 0;
let mediaRecorder;
let audioChunks = [];
let map1; // Changed from 'map' to 'map1'
let locationMarker;
let locationInterval;
// DOM Elements
const panicButton = document.getElementById('panicButton');
const statusText = document.getElementById('statusText');
const mapElement = document.getElementById('map');
// Initialize
function init() {
panicButton.addEventListener('click', handlePanicButtonPress);
updateStatus("Ready. Press button 3 times quickly to activate emergency mode.");
}
// Handle panic button press
function handlePanicButtonPress() {
const currentTime = Date.now();
// Reset count if more than 1 second between presses
if (currentTime - lastPressTime > 1000) {
pressCount = 0;
}
pressCount++;
lastPressTime = currentTime;
if (pressCount === 3) {
activateEmergencyMode();
pressCount = 0; // Reset after activation
}
}
// Activate emergency mode
async function activateEmergencyMode() {
panicButton.classList.add('activated');
updateStatus("EMERGENCY ACTIVATED! Recording audio and sharing location...");
try {
// Start audio recording
await startRecording();
// Get and share location
await shareLocation();
// Simulate sending data to emergency contact
setTimeout(() => {
sendEmergencyData();
}, 5000);
} catch (error) {
console.error("Emergency activation failed:", error);
updateStatus(`Error: ${error.message}`);
}
}
// Start audio recording
async function startRecording() {
updateStatus("Starting audio recording...");
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = event => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
// In a real app, you would send this blob to your server
console.log("Audio recording complete", audioBlob);
};
mediaRecorder.start();
updateStatus("Recording audio... Speak clearly to leave a message.");
// Stop recording after 30 seconds
setTimeout(() => {
if (mediaRecorder.state === 'recording') {
mediaRecorder.stop();
updateStatus("Audio recording complete.");
}
}, 30000);
} catch (error) {
throw new Error("Could not access microphone: " + error.message);
}
}
// Share location
async function shareLocation() {
updateStatus("Getting your location...");
try {
// Show map
mapElement.style.display = 'block';
if (!map1) { // Changed from 'map' to 'map1'
map1 = L.map('map').setView([0, 0], 2); // Changed from 'map' to 'map1'
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map1); // Changed from 'map' to 'map1'
}
// Get initial position
const position = await getCurrentPosition();
updateLocationOnMap(position.coords);
updateStatus(`Location found: ${position.coords.latitude}, ${position.coords.longitude}`);
// Continue updating location every 10 seconds
locationInterval = setInterval(async () => {
try {
const updatedPosition = await getCurrentPosition();
updateLocationOnMap(updatedPosition.coords);
} catch (error) {
console.error("Error updating location:", error);
}
}, 10000);
} catch (error) {
throw new Error("Could not get location: " + error.message);
}
}
// Get current position with timeout
function getCurrentPosition() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error("Geolocation not supported"));
return;
}
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
}
// Update location on map
function updateLocationOnMap(coords) {
const { latitude, longitude } = coords;
if (locationMarker) {
map1.removeLayer(locationMarker); // Changed from 'map' to 'map1'
}
locationMarker = L.marker([latitude, longitude]).addTo(map1) // Changed from 'map' to 'map1'
.bindPopup("Your Location")
.openPopup();
map1.setView([latitude, longitude], 15); // Changed from 'map' to 'map1'
}
// Simulate sending emergency data
function sendEmergencyData() {
updateStatus("Sending emergency data to contacts...");
// In a real implementation, you would:
// 1. Upload audio recording to a server
// 2. Send location data
// 3. Notify emergency contacts via email/SMS
// This is just a simulation
setTimeout(() => {
updateStatus(`Emergency data sent to ${EMERGENCY_CONTACT.email} and ${EMERGENCY_CONTACT.phone}`);
// Create a downloadable link for the audio (demo only)
if (audioChunks.length > 0) {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const downloadLink = document.createElement('a');
downloadLink.href = audioUrl;
downloadLink.download = 'emergency-recording.wav';
downloadLink.textContent = 'Download Recording (demo)';
statusText.appendChild(document.createElement('br'));
statusText.appendChild(downloadLink);
}
}, 2000);
}
// Update status text
function updateStatus(message, type = 'info') {
statusText.textContent = message;
statusText.className = 'status';
if (type === 'error') {
statusText.classList.add('error');
} else if (type === 'recording') {
statusText.classList.add('recording');
} else if (type === 'location') {
statusText.classList.add('location');
}
}
// Clean up
function cleanup() {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
if (locationInterval) {
clearInterval(locationInterval);
}
panicButton.classList.remove('activated');
}
// Initialize when page loads
window.addEventListener('load', init);
window.addEventListener('beforeunload', cleanup);
document.addEventListener('DOMContentLoaded', function() {
// Elements
const amountButtons = document.querySelectorAll('.amount-btn');
const customAmountInput = document.getElementById('custom-amount');
const donateBtn = document.querySelector('.donate-btn');
const qrContainer = document.getElementById('qrContainer');
const qrImage = document.getElementById('qrImage');
const backBtn = document.getElementById('backBtn');
const donationOptions = document.querySelector('.donation-options > div:not(#qrContainer)');
// Sample QR code image (replace with your actual QR code)
const sampleQR = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://example.com/donate';
// Handle amount button clicks
amountButtons.forEach(button => {
button.addEventListener('click', function() {
amountButtons.forEach(btn => btn.classList.remove('active'));
this.classList.add('active');
customAmountInput.value = this.dataset.amount;
});
});
// Handle custom amount input
customAmountInput.addEventListener('input', function() {
amountButtons.forEach(btn => btn.classList.remove('active'));
});
// Handle donate button click
donateBtn.addEventListener('click', function() {
const amount = customAmountInput.value || '0';
const method = document.querySelector('input[name="payment-method"]:checked').value;
if (parseFloat(amount) <= 0) {
alert('Please enter a valid donation amount');
return;
}
// Show QR code for mobile/crypto payments
if (method === 'crypto' || method === 'paypal') {
// Hide donation options
Array.from(donationOptions).forEach(el => el.style.display = 'none');
// Set QR code image based on payment method
if (method === 'crypto') {
qrImage.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=crypto:0xYourCryptoAddress?amount=' + amount;
qrImage.alt = 'Crypto Donation QR Code';
} else {
qrImage.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://paypal.com/donate?amount=' + amount;
qrImage.alt = 'PayPal Donation QR Code';
}
// Show QR container
qrContainer.style.display = 'block';
}
else {
// For credit card, proceed with normal payment flow
alert(`Thank you for your donation of $${amount}! You selected ${method} payment.`);
// In a real implementation, you would process the payment here
}
});
// Handle back button click
backBtn.addEventListener('click', function() {
// Hide QR container
qrContainer.style.display = 'none';
// Show donation options
Array.from(donationOptions).forEach(el => el.style.display = 'block');
});
});