split templates

This commit is contained in:
Tykayn 2025-09-26 15:08:33 +02:00 committed by tykayn
parent 6548460478
commit 9aa8da5872
22 changed files with 2980 additions and 2384 deletions

View file

@ -0,0 +1,98 @@
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
margin-top: 0;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"],
input[type="datetime-local"],
select,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
font-size: 14px;
}
.required:after {
content: " *";
color: red;
}
.form-row {
display: flex;
gap: 15px;
}
.form-row .form-group {
flex: 1;
}
button {
background-color: #0078ff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #0056b3;
}
.note {
font-size: 12px;
color: #666;
margin-top: 5px;
}
#map {
width: 100%;
height: 300px;
margin-bottom: 15px;
border-radius: 4px;
}
#result {
margin-top: 20px;
padding: 10px;
border-radius: 4px;
display: none;
}
#result.success {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
#result.error {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.nav-links {
margin-bottom: 20px;
}
.nav-links a {
color: #0078ff;
text-decoration: none;
margin-right: 15px;
}
.nav-links a:hover {
text-decoration: underline;
}

View file

@ -0,0 +1,209 @@
// Initialize the map
const map = new maplibregl.Map({
container: 'map',
style: 'https://tiles.openfreemap.org/styles/liberty',
center: [2.2137, 46.2276], // Default center (center of metropolitan France)
zoom: 5
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
// Add attribution control with OpenStreetMap attribution
map.addControl(new maplibregl.AttributionControl({
customAttribution: '© <a href="https://www.openstreetmap.org/copyright" >OpenStreetMap</a> contributors'
}));
// Add marker for event location
let marker = new maplibregl.Marker({
draggable: true
});
// Function to populate form with event data
function populateForm() {
if (!eventData || !eventData.properties) {
showResult('Error loading event data', 'error');
return;
}
const properties = eventData.properties;
// Set form values
document.getElementById('label').value = properties.label || '';
document.getElementById('type').value = properties.type || 'scheduled';
document.getElementById('what').value = properties.what || '';
// Handle optional fields
if (properties['what:series']) {
document.getElementById('what_series').value = properties['what:series'];
}
if (properties.where) {
document.getElementById('where').value = properties.where;
}
// Format dates for datetime-local input
if (properties.start) {
const startDate = new Date(properties.start);
document.getElementById('start').value = startDate.toISOString().slice(0, 16);
}
if (properties.stop) {
const stopDate = new Date(properties.stop);
document.getElementById('stop').value = stopDate.toISOString().slice(0, 16);
}
// Set marker on map
if (eventData.geometry && eventData.geometry.coordinates) {
const coords = eventData.geometry.coordinates;
marker.setLngLat(coords).addTo(map);
// Center map on event location
map.flyTo({
center: coords,
zoom: 10
});
}
}
// Call function to populate form
populateForm();
// Add marker on map click
map.on('click', function(e) {
marker.setLngLat(e.lngLat).addTo(map);
});
// Function to show result message
function showResult(message, type) {
const resultElement = document.getElementById('result');
resultElement.textContent = message;
resultElement.className = type;
resultElement.style.display = 'block';
// Scroll to result
resultElement.scrollIntoView({ behavior: 'smooth' });
}
// Handle form submission
document.getElementById('eventForm').addEventListener('submit', function(e) {
e.preventDefault();
// Get event ID
const eventId = document.getElementById('eventId').value;
// Get form values
const label = document.getElementById('label').value;
const type = document.getElementById('type').value;
const what = document.getElementById('what').value;
const what_series = document.getElementById('what_series').value;
const where = document.getElementById('where').value;
const start = document.getElementById('start').value;
const stop = document.getElementById('stop').value;
// Check if marker is set
if (!marker.getLngLat()) {
showResult('Please set a location by clicking on the map', 'error');
return;
}
// Get marker coordinates
const lngLat = marker.getLngLat();
// Create event object
const event = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [lngLat.lng, lngLat.lat]
},
properties: {
label: label,
type: type,
what: what,
start: start,
stop: stop
}
};
// Add optional properties if provided
if (what_series) {
event.properties['what:series'] = what_series;
}
if (where) {
event.properties.where = where;
}
// Submit event to API
fetch(`/event/${eventId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
})
.then(response => {
if (response.ok) {
return response.json();
} else {
return response.text().then(text => {
throw new Error(text || response.statusText);
});
}
})
.then(data => {
showResult(`Event updated successfully with ID: ${data.id}`, 'success');
// Add link to view the event
const resultElement = document.getElementById('result');
resultElement.innerHTML += `<p><a href="/event/${data.id}" >View Event</a> | <a href="/demo">Back to Map</a></p>`;
})
.catch(error => {
showResult(`Error: ${error.message}`, 'error');
});
});
// Handle delete button click
document.getElementById('deleteButton').addEventListener('click', function() {
// Get event ID
const eventId = document.getElementById('eventId').value;
// Show confirmation dialog
if (confirm('Are you sure you want to delete this event? This action cannot be undone.')) {
// Submit delete request to API
fetch(`/event/${eventId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.ok) {
showResult('Event deleted successfully', 'success');
// Add link to go back to map
const resultElement = document.getElementById('result');
resultElement.innerHTML += `<p><a href="/demo">Back to Map</a></p>`;
// Disable form controls
const formElements = document.querySelectorAll('#eventForm input, #eventForm select, #eventForm button');
formElements.forEach(element => {
element.disabled = true;
});
// Redirect to demo page after 2 seconds
setTimeout(() => {
window.location.href = '/demo';
}, 2000);
} else {
return response.text().then(text => {
throw new Error(text || response.statusText);
});
}
})
.catch(error => {
showResult(`Error deleting event: ${error.message}`, 'error');
});
}
});

View file

@ -0,0 +1,112 @@
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.map-overlay {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 300px;
max-height: 90vh;
overflow-y: auto;
}
.filter-overlay {
position: absolute;
top: 10px;
right: 10px;
background: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 300px;
max-height: 90vh;
overflow-y: auto;
}
h2, h3 {
margin-top: 0;
}
ul {
padding-left: 20px;
}
a {
color: #0078ff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.event-popup {
max-width: 300px;
}
.filter-list {
list-style: none;
padding: 0;
margin: 0;
}
.filter-item {
margin-bottom: 8px;
display: flex;
align-items: center;
}
.filter-item input {
margin-right: 8px;
}
.filter-item label {
cursor: pointer;
flex-grow: 1;
}
.filter-count {
color: #666;
font-size: 0.8em;
margin-left: 5px;
}
.color-dot {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 5px;
}
.nav {
margin-bottom: 15px;
}
.nav a {
margin-right: 15px;
}
button {
background-color: #0078ff;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
margin-right: 5px;
margin-bottom: 5px;
}
button:hover {
background-color: #0056b3;
}

View file

@ -0,0 +1,302 @@
// Initialize the map
const map = new maplibregl.Map({
container: 'map',
style: 'https://tiles.openfreemap.org/styles/liberty',
center: [2.3522, 48.8566], // Default center (Paris)
zoom: 4
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
// Add attribution control with OpenStreetMap attribution
map.addControl(new maplibregl.AttributionControl({
customAttribution: '© <a href="https://www.openstreetmap.org/copyright" >OpenStreetMap</a> contributors'
}));
// Store all events and their types
let allEvents = null;
let eventTypes = new Set();
let eventsByType = {};
let markersByType = {};
let colorsByType = {};
// Generate a color for each event type
function getColorForType(type, index) {
// Predefined colors for better visual distinction
const colors = [
'#FF5722', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5',
'#2196F3', '#03A9F4', '#00BCD4', '#009688', '#4CAF50',
'#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800'
];
return colors[index % colors.length];
}
// Fetch events when the map is loaded
map.on('load', function() {
fetchEvents();
});
// Function to fetch events from the API
function fetchEvents() {
// Update event info
document.getElementById('event-info').innerHTML = '<p>Loading events...</p>';
// Fetch events from the public API - using limit=1000 to get more events
fetch('https://api.openeventdatabase.org/event?limit=1000')
.then(response => response.json())
.then(data => {
if (data.features && data.features.length > 0) {
// Store all events
allEvents = data;
// Process events by type
processEventsByType(data);
// Create filter UI
createFilterUI();
// Add all events to the map initially
addAllEventsToMap();
// Fit map to events bounds
fitMapToBounds(data);
// Update event info
document.getElementById('event-info').innerHTML =
`<p>Found ${data.features.length} events across ${eventTypes.size} different types.</p>`;
} else {
document.getElementById('event-info').innerHTML = '<p>No events found.</p>';
document.getElementById('filter-list').innerHTML = '<li>No event types available.</li>';
}
})
.catch(error => {
console.error('Error fetching events:', error);
document.getElementById('event-info').innerHTML =
`<p>Error loading events: ${error.message}</p>`;
});
}
// Process events by their "what" type
function processEventsByType(data) {
eventTypes = new Set();
eventsByType = {};
// Group events by their "what" type
data.features.forEach(feature => {
const properties = feature.properties;
const what = properties.what || 'Unknown';
// Add to set of event types
eventTypes.add(what);
// Add to events by type
if (!eventsByType[what]) {
eventsByType[what] = [];
}
eventsByType[what].push(feature);
});
// Assign colors to each type
let index = 0;
eventTypes.forEach(type => {
colorsByType[type] = getColorForType(type, index);
index++;
});
}
// Create the filter UI
function createFilterUI() {
const filterList = document.getElementById('filter-list');
filterList.innerHTML = '';
// Sort event types alphabetically
const sortedTypes = Array.from(eventTypes).sort();
// Create a checkbox for each event type
sortedTypes.forEach(type => {
const count = eventsByType[type].length;
const color = colorsByType[type];
const li = document.createElement('li');
li.className = 'filter-item';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = `filter-${type}`;
checkbox.checked = true;
checkbox.addEventListener('change', () => {
toggleEventType(type, checkbox.checked);
});
const colorDot = document.createElement('span');
colorDot.className = 'color-dot';
colorDot.style.backgroundColor = color;
const label = document.createElement('label');
label.htmlFor = `filter-${type}`;
label.appendChild(colorDot);
label.appendChild(document.createTextNode(type));
const countSpan = document.createElement('span');
countSpan.className = 'filter-count';
countSpan.textContent = `(${count})`;
label.appendChild(countSpan);
li.appendChild(checkbox);
li.appendChild(label);
filterList.appendChild(li);
});
// Add event listeners for select/deselect all buttons
document.getElementById('select-all').addEventListener('click', selectAllEventTypes);
document.getElementById('deselect-all').addEventListener('click', deselectAllEventTypes);
}
// Add all events to the map
function addAllEventsToMap() {
// Clear existing markers
clearAllMarkers();
// Add markers for each event type
Object.keys(eventsByType).forEach(type => {
addEventsOfTypeToMap(type);
});
}
// Add events of a specific type to the map
function addEventsOfTypeToMap(type) {
if (!markersByType[type]) {
markersByType[type] = [];
}
const events = eventsByType[type];
const color = colorsByType[type];
events.forEach(feature => {
const coordinates = feature.geometry.coordinates.slice();
const properties = feature.properties;
// Create popup content
let popupContent = '<div class="event-popup">';
popupContent += `<h3>${properties.label || 'Event'}</h3>`;
popupContent += `<p><strong>Type:</strong> ${type}</p>`;
// Display all properties
popupContent += '<div style="max-height: 300px; overflow-y: auto;">';
popupContent += '<table style="width: 100%; border-collapse: collapse;">';
// Sort properties alphabetically for better organization
const sortedKeys = Object.keys(properties).sort();
for (const key of sortedKeys) {
// Skip the label as it's already displayed as the title
if (key === 'label') continue;
const value = properties[key];
let displayValue;
// Format the value based on its type
if (value === null || value === undefined) {
displayValue = '<em>null</em>';
} else if (typeof value === 'object') {
displayValue = `<pre style="margin: 0; white-space: pre-wrap;">${JSON.stringify(value, null, 2)}</pre>`;
} else if (typeof value === 'string' && value.startsWith('http')) {
displayValue = `<a href="${value}" >${value}</a>`;
} else {
displayValue = String(value);
}
popupContent += `
<tr style="border-bottom: 1px solid #eee;">
<td style="padding: 4px; font-weight: bold; vertical-align: top;">${key}:</td>
<td style="padding: 4px;">${displayValue}</td>
</tr>`;
}
popupContent += '</table>';
popupContent += '</div>';
popupContent += '</div>';
// Create popup
const popup = new maplibregl.Popup({
closeButton: true,
closeOnClick: true
}).setHTML(popupContent);
// Add marker with popup
const marker = new maplibregl.Marker({
color: color
})
.setLngLat(coordinates)
.setPopup(popup)
.addTo(map);
// Store marker reference
markersByType[type].push(marker);
});
}
// Toggle visibility of events by type
function toggleEventType(type, visible) {
if (!markersByType[type]) return;
markersByType[type].forEach(marker => {
if (visible) {
marker.addTo(map);
} else {
marker.remove();
}
});
}
// Select all event types
function selectAllEventTypes() {
const checkboxes = document.querySelectorAll('#filter-list input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = true;
const type = checkbox.id.replace('filter-', '');
toggleEventType(type, true);
});
}
// Deselect all event types
function deselectAllEventTypes() {
const checkboxes = document.querySelectorAll('#filter-list input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = false;
const type = checkbox.id.replace('filter-', '');
toggleEventType(type, false);
});
}
// Clear all markers from the map
function clearAllMarkers() {
Object.keys(markersByType).forEach(type => {
if (markersByType[type]) {
markersByType[type].forEach(marker => marker.remove());
}
});
markersByType = {};
}
// Function to fit map to events bounds
function fitMapToBounds(geojson) {
if (geojson.features.length === 0) return;
// Create a bounds object
const bounds = new maplibregl.LngLatBounds();
// Extend bounds with each feature
geojson.features.forEach(feature => {
bounds.extend(feature.geometry.coordinates);
});
// Fit map to bounds with padding
map.fitBounds(bounds, {
padding: 50,
maxZoom: 12
});
}

View file

@ -0,0 +1,153 @@
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
.container {
max-width: 1200px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
margin-top: 0;
color: #333;
}
.nav-links {
margin-bottom: 20px;
}
.nav-links a {
color: #0078ff;
text-decoration: none;
margin-right: 15px;
}
.nav-links a:hover {
text-decoration: underline;
}
.tabs-container {
margin-top: 20px;
}
.tab-content {
display: none;
padding: 20px;
border: 1px solid #ddd;
border-top: none;
}
.tab-content.active {
display: block;
}
.tab-buttons {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-button {
padding: 10px 20px;
background-color: #f1f1f1;
border: 1px solid #ddd;
border-bottom: none;
cursor: pointer;
margin-right: 5px;
}
.tab-button.active {
background-color: white;
border-bottom: 1px solid white;
margin-bottom: -1px;
}
#map {
width: 100%;
height: 500px;
margin-top: 20px;
border-radius: 4px;
}
.results-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.results-table th, .results-table td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.results-table th {
background-color: #f2f2f2;
}
.download-buttons {
margin-top: 20px;
text-align: right;
}
.download-button {
display: inline-block;
padding: 8px 16px;
background-color: #0078ff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
text-decoration: none;
}
.download-button:hover {
background-color: #0056b3;
}
.form-row {
display: flex;
gap: 15px;
margin-bottom: 15px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"],
input[type="datetime-local"],
input[type="number"],
select,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
font-size: 14px;
}
.note {
font-size: 12px;
color: #666;
margin-top: 5px;
}
button {
background-color: #0078ff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #0056b3;
}
#result {
margin-top: 20px;
padding: 10px;
border-radius: 4px;
display: none;
}
#result.success {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
#result.error {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}

View file

@ -0,0 +1,412 @@
// Initialize the map
const map = new maplibregl.Map({
container: 'map',
style: 'https://tiles.openfreemap.org/styles/liberty',
center: [2.3522, 48.8566], // Default center (Paris)
zoom: 4
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
// Add draw controls for polygon
let drawnPolygon = null;
let drawingMode = false;
let points = [];
let lineString = null;
let polygonFill = null;
// Add a button to toggle drawing mode
const drawButton = document.createElement('button');
drawButton.textContent = 'Draw Polygon';
drawButton.style.position = 'absolute';
drawButton.style.top = '10px';
drawButton.style.right = '10px';
drawButton.style.zIndex = '1';
drawButton.style.padding = '5px 10px';
drawButton.style.backgroundColor = '#0078ff';
drawButton.style.color = 'white';
drawButton.style.border = 'none';
drawButton.style.borderRadius = '3px';
drawButton.style.cursor = 'pointer';
document.getElementById('map').appendChild(drawButton);
drawButton.addEventListener('click', () => {
drawingMode = !drawingMode;
drawButton.textContent = drawingMode ? 'Cancel Drawing' : 'Draw Polygon';
if (!drawingMode) {
// Clear the drawing
points = [];
if (lineString) {
map.removeLayer('line-string');
map.removeSource('line-string');
lineString = null;
}
if (polygonFill) {
map.removeLayer('polygon-fill');
map.removeSource('polygon-fill');
polygonFill = null;
}
}
});
// Handle map click events for drawing
map.on('click', (e) => {
if (!drawingMode) return;
const coords = [e.lngLat.lng, e.lngLat.lat];
points.push(coords);
// If we have at least 3 points, create a polygon
if (points.length >= 3) {
const polygonCoords = [...points, points[0]]; // Close the polygon
// Create or update the line string
if (lineString) {
map.removeLayer('line-string');
map.removeSource('line-string');
}
lineString = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: polygonCoords
}
};
map.addSource('line-string', {
type: 'geojson',
data: lineString
});
map.addLayer({
id: 'line-string',
type: 'line',
source: 'line-string',
paint: {
'line-color': '#0078ff',
'line-width': 2
}
});
// Create or update the polygon fill
if (polygonFill) {
map.removeLayer('polygon-fill');
map.removeSource('polygon-fill');
}
polygonFill = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [polygonCoords]
}
};
map.addSource('polygon-fill', {
type: 'geojson',
data: polygonFill
});
map.addLayer({
id: 'polygon-fill',
type: 'fill',
source: 'polygon-fill',
paint: {
'fill-color': '#0078ff',
'fill-opacity': 0.2
}
});
// Store the drawn polygon for search
drawnPolygon = {
type: 'Polygon',
coordinates: [polygonCoords]
};
}
});
// Handle custom date range selection
document.getElementById('when').addEventListener('change', function() {
const customDateGroup = document.getElementById('customDateGroup');
const customDateEndGroup = document.getElementById('customDateEndGroup');
if (this.value === 'custom') {
customDateGroup.style.display = 'block';
customDateEndGroup.style.display = 'block';
} else {
customDateGroup.style.display = 'none';
customDateEndGroup.style.display = 'none';
}
});
// Handle form submission
document.getElementById('searchForm').addEventListener('submit', function(e) {
e.preventDefault();
// Show loading message
const resultElement = document.getElementById('result');
resultElement.textContent = 'Searching...';
resultElement.className = '';
resultElement.style.display = 'block';
// Get form values
const formData = new FormData(this);
const params = new URLSearchParams();
// Add form fields to params
for (const [key, value] of formData.entries()) {
if (value) {
params.append(key, value);
}
}
// Handle custom date range
if (formData.get('when') === 'custom') {
params.delete('when');
} else {
params.delete('start');
params.delete('stop');
}
// Prepare the request
let url = '/event/search';
let method = 'POST';
let body = null;
// If we have a drawn polygon, use it for the search
if (drawnPolygon) {
body = JSON.stringify({
geometry: drawnPolygon
});
} else if (formData.get('near') || formData.get('bbox')) {
// If we have near or bbox parameters, use GET request
url = '/event?' + params.toString();
method = 'GET';
} else {
// Default to a simple point search in Paris if no spatial filter is provided
body = JSON.stringify({
geometry: {
type: 'Point',
coordinates: [2.3522, 48.8566]
}
});
}
// Make the request
fetch(url + (method === 'GET' ? '' : '?' + params.toString()), {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: method === 'POST' ? body : null
})
.then(response => {
if (response.ok) {
return response.json();
} else {
return response.text().then(text => {
throw new Error(text || response.statusText);
});
}
})
.then(data => {
// Show success message
resultElement.textContent = `Found ${data.features ? data.features.length : 0} events`;
resultElement.className = 'success';
// Display results
displayResults(data);
})
.catch(error => {
// Show error message
resultElement.textContent = `Error: ${error.message}`;
resultElement.className = 'error';
// Hide results container
document.getElementById('resultsContainer').style.display = 'none';
});
});
// Function to display search results
function displayResults(data) {
// Show results container
document.getElementById('resultsContainer').style.display = 'block';
// Initialize results map
const resultsMap = new maplibregl.Map({
container: 'resultsMap',
style: 'https://tiles.openfreemap.org/styles/liberty',
center: [2.3522, 48.8566], // Default center (Paris)
zoom: 4
});
// Add navigation controls to results map
resultsMap.addControl(new maplibregl.NavigationControl());
// Add events to the map
resultsMap.on('load', function() {
// Add events as a source
resultsMap.addSource('events', {
type: 'geojson',
data: data
});
// Add a circle layer for events
resultsMap.addLayer({
id: 'events-circle',
type: 'circle',
source: 'events',
paint: {
'circle-radius': 8,
'circle-color': '#FF5722',
'circle-stroke-width': 2,
'circle-stroke-color': '#FFFFFF'
}
});
// Add popups for events
if (data.features) {
data.features.forEach(feature => {
const coordinates = feature.geometry.coordinates.slice();
const properties = feature.properties;
// Create popup content
let popupContent = '<div class="event-popup">';
popupContent += `<h3>${properties.label || 'Event'}</h3>`;
// Display key properties
if (properties.what) {
popupContent += `<p><strong>Type:</strong> ${properties.what}</p>`;
}
if (properties.where) {
popupContent += `<p><strong>Where:</strong> ${properties.where}</p>`;
}
if (properties.start) {
popupContent += `<p><strong>Start:</strong> ${properties.start}</p>`;
}
if (properties.stop) {
popupContent += `<p><strong>End:</strong> ${properties.stop}</p>`;
}
// Add link to view full event
popupContent += `<p><a href="/event/${properties.id}" >View Event</a></p>`;
popupContent += '</div>';
// Create popup
const popup = new maplibregl.Popup({
closeButton: true,
closeOnClick: true
}).setHTML(popupContent);
// Add marker with popup
new maplibregl.Marker({
color: '#FF5722'
})
.setLngLat(coordinates)
.setPopup(popup)
.addTo(resultsMap);
});
// Fit map to events bounds
if (data.features.length > 0) {
const bounds = new maplibregl.LngLatBounds();
data.features.forEach(feature => {
bounds.extend(feature.geometry.coordinates);
});
resultsMap.fitBounds(bounds, {
padding: 50,
maxZoom: 12
});
}
}
});
// Populate table with results
const tableBody = document.getElementById('resultsTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = '';
if (data.features) {
data.features.forEach(feature => {
const properties = feature.properties;
const row = tableBody.insertRow();
row.insertCell(0).textContent = properties.id || '';
row.insertCell(1).textContent = properties.label || '';
row.insertCell(2).textContent = properties.type || '';
row.insertCell(3).textContent = properties.what || '';
row.insertCell(4).textContent = properties.where || '';
row.insertCell(5).textContent = properties.start || '';
row.insertCell(6).textContent = properties.stop || '';
});
}
// Store the data for download
window.searchResults = data;
}
// Handle tab switching
document.querySelectorAll('.tab-button').forEach(button => {
button.addEventListener('click', () => {
// Remove active class from all buttons and content
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Add active class to clicked button and corresponding content
button.classList.add('active');
document.getElementById(button.dataset.tab).classList.add('active');
});
});
// Handle CSV download
document.getElementById('downloadCsv').addEventListener('click', () => {
if (!window.searchResults || !window.searchResults.features) {
alert('No search results to download');
return;
}
// Convert GeoJSON to CSV
let csv = 'id,label,type,what,where,start,stop,longitude,latitude\n';
window.searchResults.features.forEach(feature => {
const p = feature.properties;
const coords = feature.geometry.coordinates;
csv += `"${p.id || ''}","${p.label || ''}","${p.type || ''}","${p.what || ''}","${p.where || ''}","${p.start || ''}","${p.stop || ''}",${coords[0]},${coords[1]}\n`;
});
// Create download link
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'search_results.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// Handle JSON download
document.getElementById('downloadJson').addEventListener('click', () => {
if (!window.searchResults) {
alert('No search results to download');
return;
}
// Create download link
const blob = new Blob([JSON.stringify(window.searchResults, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'search_results.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,63 @@
// traffic_tabs.js - Handle query parameters for tab selection in traffic.html
document.addEventListener('DOMContentLoaded', function() {
// Get all tab items
const tabItems = document.querySelectorAll('.tab-item');
// Function to activate a tab
function activateTab(tabName) {
// Find the tab item with the given tab name
const tabItem = document.querySelector(`.tab-item[data-tab="${tabName}"]`);
if (!tabItem) return;
// Remove active class from all tab items
tabItems.forEach(item => item.classList.remove('active'));
// Add active class to the selected tab item
tabItem.classList.add('active');
// Get all tab panes
const tabPanes = document.querySelectorAll('.tab-pane');
// Remove active class from all tab panes
tabPanes.forEach(pane => pane.classList.remove('active'));
// Add active class to the corresponding tab pane
document.getElementById(tabName + '-tab').classList.add('active');
// Save active tab to localStorage
localStorage.setItem('activeTab', tabName);
// Update URL with query parameter
const url = new URL(window.location.href);
url.searchParams.set('tab', tabName);
history.replaceState(null, '', url);
}
// Add click event listener to each tab item
tabItems.forEach(tab => {
tab.addEventListener('click', function() {
// Get the tab name from data-tab attribute
const tabName = this.getAttribute('data-tab');
// Activate the tab
activateTab(tabName);
});
});
// Check for tab query parameter
const urlParams = new URLSearchParams(window.location.search);
const tabParam = urlParams.get('tab');
if (tabParam) {
// Activate the tab from query parameter
activateTab(tabParam);
} else {
// Restore active tab from localStorage if no query parameter
const activeTab = localStorage.getItem('activeTab');
if (activeTab) {
// Activate the tab from localStorage
activateTab(activeTab);
}
}
});

View file

@ -0,0 +1,174 @@
// view_events.js - JavaScript for the view saved events page
// Global variables
let map;
let markers = [];
// Initialize the map when the page loads
document.addEventListener('DOMContentLoaded', function() {
initMap();
// Set up refresh button
const refreshBtn = document.getElementById('refresh-btn');
if (refreshBtn) {
refreshBtn.addEventListener('click', loadEvents);
}
// Set up clear button
const clearBtn = document.getElementById('clear-btn');
if (clearBtn) {
clearBtn.addEventListener('click', clearEvents);
}
});
// Initialize the map
function initMap() {
// Create the map
map = new maplibregl.Map({
container: 'map',
style: 'https://tiles.openfreemap.org/styles/liberty',
center: [2.2137, 46.2276], // Default center (center of metropolitan France)
zoom: 5
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
// Add attribution control with OpenStreetMap attribution
map.addControl(new maplibregl.AttributionControl({
customAttribution: '© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}));
// Load events when the map is loaded
map.on('load', function() {
loadEvents();
});
}
// Function to load events from localStorage
function loadEvents() {
// Clear existing markers
markers.forEach(marker => marker.remove());
markers = [];
// Get events from localStorage
const savedEvents = JSON.parse(localStorage.getItem('oedb_events') || '[]');
// Update event count
document.getElementById('event-count').textContent =
`${savedEvents.length} event${savedEvents.length !== 1 ? 's' : ''} found`;
// Clear event list
const eventList = document.getElementById('event-list');
eventList.innerHTML = '';
// If no events, show message
if (savedEvents.length === 0) {
eventList.innerHTML = '<div class="no-events">No saved events found. Use the demo map to save events.</div>';
return;
}
// Create bounds object to fit map to all markers
const bounds = new maplibregl.LngLatBounds();
// Add markers and list items for each event
savedEvents.forEach((event, index) => {
// Skip events without geometry
if (!event.geometry || !event.geometry.coordinates) return;
// Get coordinates
const coordinates = event.geometry.coordinates;
// Add marker to map
const marker = new maplibregl.Marker()
.setLngLat(coordinates)
.addTo(map);
// Add popup with event info
const popup = new maplibregl.Popup({ offset: 25 })
.setHTML(`
<h3>${event.label || 'Unnamed Event'}</h3>
<p><strong>Type:</strong> ${event.what || 'Unknown'}</p>
<p><strong>Start:</strong> ${formatDate(event.start)}</p>
<p><strong>End:</strong> ${formatDate(event.stop)}</p>
${event.description ? `<p><strong>Description:</strong> ${event.description}</p>` : ''}
<button class="delete-event-btn" onclick="deleteEvent(${index})">Delete</button>
`);
marker.setPopup(popup);
markers.push(marker);
// Extend bounds to include this marker
bounds.extend(coordinates);
// Add to event list
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
eventItem.innerHTML = `
<div class="event-header">
<h3>${event.label || 'Unnamed Event'}</h3>
<div class="event-actions">
<button class="zoom-btn" onclick="zoomToEvent(${coordinates[0]}, ${coordinates[1]})">
<i class="fas fa-search-location"></i>
</button>
<button class="delete-btn" onclick="deleteEvent(${index})">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</div>
<div class="event-details">
<p><strong>Type:</strong> ${event.what || 'Unknown'}</p>
<p><strong>When:</strong> ${formatDate(event.start)} to ${formatDate(event.stop)}</p>
${event.description ? `<p><strong>Description:</strong> ${event.description}</p>` : ''}
</div>
`;
eventList.appendChild(eventItem);
});
// Fit map to bounds if we have any markers
if (!bounds.isEmpty()) {
map.fitBounds(bounds, { padding: 50 });
}
}
// Format date for display
function formatDate(dateString) {
if (!dateString) return 'Unknown';
const date = new Date(dateString);
return date.toLocaleString();
}
// Zoom to a specific event
function zoomToEvent(lng, lat) {
map.flyTo({
center: [lng, lat],
zoom: 14
});
}
// Delete an event
function deleteEvent(index) {
// Get events from localStorage
const savedEvents = JSON.parse(localStorage.getItem('oedb_events') || '[]');
// Remove the event at the specified index
savedEvents.splice(index, 1);
// Save the updated events back to localStorage
localStorage.setItem('oedb_events', JSON.stringify(savedEvents));
// Reload the events
loadEvents();
}
// Clear all events
function clearEvents() {
if (confirm('Are you sure you want to delete all saved events?')) {
// Clear events from localStorage
localStorage.removeItem('oedb_events');
// Reload the events
loadEvents();
}
}