ajout de reality check dans les évènements traffic qui complète une propriété de l'évènement

This commit is contained in:
Tykayn 2025-09-21 23:59:01 +02:00 committed by tykayn
parent f18383fb9e
commit f66e5e3f7b
5 changed files with 675 additions and 37 deletions

View file

@ -318,7 +318,7 @@
// Clear existing markers first
existingMarkers.forEach(marker => marker.remove());
existingMarkers = [];
// Fetch traffic events from the API
fetch('https://api.openeventdatabase.org/event?what=traffic')
.then(response => {
@ -334,29 +334,56 @@
data.features.forEach(event => {
if (event.geometry && event.geometry.type === 'Point') {
const coords = event.geometry.coordinates;
// Create a gray marker for existing events
// Check if this event needs reality check (created more than 1 hour ago)
const needsRealityCheck = checkIfNeedsRealityCheck(event);
// Create a marker for existing events (gray for regular, orange for those needing reality check)
const markerColor = needsRealityCheck ? '#ff9800' : '#888888';
const eventMarker = new maplibregl.Marker({
color: '#888888' // Gray color for existing events
color: markerColor
})
.setLngLat(coords)
.addTo(map);
// Add popup with event details
let popupContent = `
<h3>${event.properties.label || 'Traffic Event'}</h3>
<p>Type: ${event.properties.what || 'Unknown'}</p>
<p>Start: ${event.properties.start || 'Unknown'}</p>
<p>End: ${event.properties.stop || 'Unknown'}</p>
`;
// Add reality check buttons if needed
if (needsRealityCheck) {
popupContent += `
<div class="reality-check">
<p>Is this traffic event still present?</p>
<div class="reality-check-buttons">
<button class="confirm-btn" onclick="confirmEvent('${event.properties.id}', true)">Yes, still there</button>
<button class="deny-btn" onclick="confirmEvent('${event.properties.id}', false)">No, it's gone</button>
</div>
</div>
`;
} else if (event.properties['reality_check']) {
// Show reality check information if it exists
popupContent += `
<div class="reality-check-info">
<p>Reality check: ${event.properties['reality_check']}</p>
</div>
`;
}
const popup = new maplibregl.Popup({ offset: 25 })
.setHTML(`
<h3>${event.properties.label || 'Traffic Event'}</h3>
<p>Type: ${event.properties.what || 'Unknown'}</p>
<p>Start: ${event.properties.start || 'Unknown'}</p>
<p>End: ${event.properties.stop || 'Unknown'}</p>
`);
.setHTML(popupContent);
eventMarker.setPopup(popup);
// Store marker reference for later removal
existingMarkers.push(eventMarker);
}
});
console.log(`Loaded ${existingMarkers.length} existing traffic events`);
}
})
@ -364,6 +391,32 @@
console.error('Error fetching traffic events:', error);
});
}
// Function to check if an event needs a reality check (created more than 1 hour ago)
function checkIfNeedsRealityCheck(event) {
// Skip if event already has a reality check
if (event.properties['reality_check']) {
return false;
}
// Check if the event is a traffic event
if (!event.properties.what || !event.properties.what.startsWith('traffic')) {
return false;
}
// Check creation date
const createDate = event.properties.createdate;
if (!createDate) {
return false;
}
const createTime = new Date(createDate).getTime();
const currentTime = new Date().getTime();
const oneHourInMs = 60 * 60 * 1000;
// Return true if the event was created more than 1 hour ago
return (currentTime - createTime) > oneHourInMs;
}
// Fetch existing events when the map loads
map.on('load', fetchExistingTrafficEvents);
@ -843,6 +896,201 @@
// Scroll to result
resultElement.scrollIntoView({ behavior: 'smooth' });
}
// Function to handle event confirmation or denial
function confirmEvent(eventId, isConfirmed) {
// Get username from localStorage or prompt for it
let username = localStorage.getItem('oedb_username');
if (!username) {
username = promptForUsername();
if (!username) {
// User cancelled the prompt
return;
}
}
// Current date and time
const now = new Date();
const dateTimeString = now.toISOString();
// Create reality check string
const realityCheckStatus = isConfirmed ? 'confirmed' : 'not confirmed';
const realityCheckValue = `${dateTimeString} | ${username} | ${realityCheckStatus}`;
// Fetch the event to update
fetch(`https://api.openeventdatabase.org/event/${eventId}`)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Failed to fetch event ${eventId}`);
}
})
.then(event => {
// Add reality_check property
event.properties['reality_check'] = realityCheckValue;
// Update the event
return fetch(`https://api.openeventdatabase.org/event/${eventId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
});
})
.then(response => {
if (response.ok) {
// Save contribution to localStorage
saveContribution(eventId, isConfirmed);
// Award points
awardPoints(3);
// Show success message
showResult(`Thank you for your contribution! You've earned 3 points.`, 'success');
// Update user info display
updateUserInfoDisplay();
// Refresh events to update the display
fetchExistingTrafficEvents();
} else {
throw new Error('Failed to update event');
}
})
.catch(error => {
console.error('Error updating event:', error);
showResult(`Error: ${error.message}`, 'error');
});
}
// Function to prompt for username
function promptForUsername() {
const username = prompt('Please enter your username:');
if (username) {
localStorage.setItem('oedb_username', username);
return username;
}
return null;
}
// Function to save contribution to localStorage
function saveContribution(eventId, isConfirmed) {
// Get existing contributions
let contributions = JSON.parse(localStorage.getItem('oedb_contributions') || '[]');
// Add new contribution
contributions.push({
eventId: eventId,
timestamp: new Date().toISOString(),
isConfirmed: isConfirmed
});
// Save back to localStorage
localStorage.setItem('oedb_contributions', JSON.stringify(contributions));
}
// Function to award points
function awardPoints(points) {
// Get current points
let currentPoints = parseInt(localStorage.getItem('oedb_points') || '0');
// Add new points
currentPoints += points;
// Save back to localStorage
localStorage.setItem('oedb_points', currentPoints.toString());
}
// Function to update user info display in side panel
function updateUserInfoDisplay() {
const username = localStorage.getItem('oedb_username') || 'Anonymous';
const points = localStorage.getItem('oedb_points') || '0';
// Check if user info panel exists, create it if not
let userInfoPanel = document.getElementById('user-info-panel');
if (!userInfoPanel) {
// Create user info panel
userInfoPanel = document.createElement('div');
userInfoPanel.id = 'user-info-panel';
userInfoPanel.className = 'user-info-panel';
// Add it to the page (after the nav-links)
const navLinks = document.querySelector('.nav-links');
navLinks.parentNode.insertBefore(userInfoPanel, navLinks.nextSibling);
// Add some CSS for the panel
const style = document.createElement('style');
style.textContent = `
.user-info-panel {
background-color: #f5f5f5;
border-radius: 4px;
padding: 10px;
margin: 10px 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.user-info-panel h3 {
margin-top: 0;
margin-bottom: 10px;
color: #333;
}
.user-info-panel p {
margin: 5px 0;
}
.user-points {
font-weight: bold;
color: #0078ff;
}
.reality-check {
margin-top: 10px;
padding: 10px;
background-color: #fff3e0;
border-radius: 4px;
}
.reality-check-buttons {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
.confirm-btn, .deny-btn {
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.confirm-btn {
background-color: #4caf50;
color: white;
}
.deny-btn {
background-color: #f44336;
color: white;
}
.reality-check-info {
margin-top: 10px;
padding: 8px;
background-color: #e8f5e9;
border-radius: 4px;
font-size: 0.9em;
}
`;
document.head.appendChild(style);
}
// Update the content
userInfoPanel.innerHTML = `
<h3>User Information</h3>
<p>Username: <strong>${username}</strong></p>
<p>Points: <span class="user-points">${points}</span></p>
`;
}
// Initialize user info display when page loads
document.addEventListener('DOMContentLoaded', function() {
updateUserInfoDisplay();
});
</script>
</body>
</html>