65 lines
3.5 KiB
JavaScript
65 lines
3.5 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function() {
|
|
const liveTrainForm = document.getElementById('live-train-form');
|
|
let map = null; // Variable to hold the map instance
|
|
let trainMarker = null; // Variable to hold the train marker
|
|
|
|
if (liveTrainForm) {
|
|
liveTrainForm.addEventListener('submit', function(e) {
|
|
e.preventDefault();
|
|
|
|
const trainNumber = document.getElementById('train-number').value;
|
|
// Use today's date for the demo
|
|
const trainDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');
|
|
const resultDiv = document.getElementById('live-train-result');
|
|
|
|
resultDiv.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';
|
|
|
|
fetch(`api/live_train_status_handler.php?train_number=${trainNumber}&date=${trainDate}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if(data.ResponseCode == 200) {
|
|
// Handle route display
|
|
let routeHtml = '';
|
|
data.Route.forEach(station => {
|
|
let statusClass = station.IsCurrentStation ? 'text-primary fw-bold' : '';
|
|
routeHtml += `<li class="list-group-item bg-dark text-light ${statusClass}">
|
|
<strong>${station.StationName} (${station.StationCode})</strong><br>
|
|
<small>Arrival: ${station.ActualArrival} | Departure: ${station.ActualDeparture}</small>
|
|
</li>`;
|
|
});
|
|
resultDiv.innerHTML = `
|
|
<h5 class="text-primary">Current Status: ${data.Position}</h5>
|
|
<ul class="list-group list-group-flush">${routeHtml}</ul>
|
|
`;
|
|
|
|
// Handle map display
|
|
const coords = data.CurrentStation;
|
|
if (coords.latitude && coords.longitude) {
|
|
const latLng = [coords.latitude, coords.longitude];
|
|
if (!map) {
|
|
// Initialize map
|
|
map = L.map('live-train-map').setView(latLng, 13);
|
|
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
|
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
|
}).addTo(map);
|
|
trainMarker = L.marker(latLng).addTo(map);
|
|
} else {
|
|
// Update map
|
|
map.setView(latLng, 13);
|
|
trainMarker.setLatLng(latLng);
|
|
}
|
|
trainMarker.bindPopup(`<b>${data.TrainName}</b><br>${data.Position}`).openPopup();
|
|
}
|
|
|
|
} else {
|
|
resultDiv.innerHTML = `<div class="alert alert-danger">${data.Message || 'Could not fetch live train status.'}</div>`;
|
|
}
|
|
})
|
|
.catch(err => {
|
|
console.error('Error:', err);
|
|
resultDiv.innerHTML = `<div class="alert alert-danger">An error occurred.</div>`;
|
|
});
|
|
});
|
|
}
|
|
});
|