This commit is contained in:
2025-07-16 07:50:54 +09:00
parent fb145c44f2
commit 8f4d89325b
3 changed files with 199 additions and 5201 deletions

View File

@@ -11,165 +11,170 @@
crossorigin=""></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
#map {
height: calc(100vh - 60px);
background-color: #e5e5e5;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.station-label {
text-align: center;
font-weight: bold;
font-size: 15px;
color: black;
}
#map {
height: 100%;
}
.train-marker {
text-align: center;
}
.station-label {
text-align: center;
font-weight: bold;
font-size: 15px;
color: black;
}
.bottombar {
height: 40px;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
}
.train-marker {
text-align: center;
}
.bottombar .left {
display: flex;
align-items: center;
}
#reload {
padding: 5px 10px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
.bottombar .left input[type="checkbox"] {
margin-right: 10px;
}
#reload:hover {
background-color: #0056b3;
}
.bottombar .right {
display: flex;
align-items: center;
}
.hidden {
display: none;
}
.bottombar .loading {
margin-right: 15px;
}
#reloadTrains {
padding: 5px 10px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
#reloadTrains:hover {
background-color: #0056b3;
}
.hidden {
display: none;
}
#info {
position: fixed;
bottom: 10px;
left: 10px;
z-index: 1000;
}
#loading {
margin-left: 10px;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="bottombar">
<div class="left">
<input type="checkbox" id="layer0"> Express
<input type="checkbox" id="layer1"> Semi
<input type="checkbox" id="layer2"> Normal
<input type="checkbox" id="layer3"> Passenger
<input type="checkbox" id="layer4"> Subway
<input type="checkbox" id="layer5"> Logis
</div>
<div class="right">
<span class="loading" id="loading">Loading...</span>
<button id="reloadTrains">Reload</button>
<input type="checkbox" id="autoReload"> Auto
</div>
<div id="info">
<button id="reload">Reload</button>
<span id="loading">Loading...</span>
</div>
<script>
const trainAPI = 'https://gis.korail.com/api/train?bbox=120.6263671875,28.07910949377748,134.0736328125,45.094739803960664'
const server = ''
let openPopupTrainId = null;
let followingTrainId = null;
let isFollowing = false;
async function myFetch(url, options = {}) {
let headers = options.headers
let f = fetch('https://proxy.devpg.net', {
return fetch('https://proxy/', {
headers: {
'X-Proxy-URL': url,
'X-Proxy-Header': JSON.stringify(headers),
'X-Proxy-Cache': '0'
}
});
console.log(`fetch(${url}, headers=${JSON.stringify(headers)}`, f);
return f
}
const trainAPI = 'https://gis.korail.com/api/train?bbox=120.6263671875,28.07910949377748,134.0736328125,45.094739803960664'
const server = ''
const map = L.map('map').setView([36.5, 128], 7.5);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const railLayers = {
express: L.layerGroup().addTo(map),
normal: L.layerGroup().addTo(map),
semi: L.layerGroup().addTo(map),
logis: L.layerGroup().addTo(map)
};
L.tileLayer('https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openrailwaymap.org/">OpenRailwayMap</a>',
maxZoom: 19
}).addTo(map);
const stationLayers = [];
for (let i = 0; i < 64; i++) {
const layerGroup = L.layerGroup().addTo(map);
stationLayers.push(layerGroup);
}
for (let layer of stationLayers) {
map.removeLayer(layer);
stationLayers.push(L.layerGroup());
}
const trainLayer = L.layerGroup().addTo(map);
const trainPositions = new Map();
function startSpinner() {
document.getElementById("loading").classList.remove("hidden");
}
function clearSpinner() {
document.getElementById("loading").classList.add("hidden");
}
function loadRail(type) {
fetch(`${server}/api/rail/${type}`)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok ${response.statusText}`);
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
function calculateAverageSpeed(trainId) {
const positions = trainPositions.get(trainId);
if (!positions || positions.length < 2) return null;
const firstChange = positions[0];
const lastChange = positions[positions.length - 1];
const totalDistance = calculateDistance(firstChange.lat, firstChange.lon, lastChange.lat, lastChange.lon);
const totalTime = (lastChange.timestamp - firstChange.timestamp) / 1000;
if (totalTime === 0) return null;
return (totalDistance / totalTime) * 3600;
}
function updateTrainPosition(trainId, lat, lon, timestamp) {
if (!trainPositions.has(trainId)) {
trainPositions.set(trainId, []);
}
const positions = trainPositions.get(trainId);
if (positions.length > 0) {
const lastPos = positions[positions.length - 1];
if (Math.abs(lastPos.lat - lat) < 0.0001 && Math.abs(lastPos.lon - lon) < 0.0001) {
return;
}
}
const lookbackCount = Math.min(12, positions.length);
for (let i = Math.max(0, positions.length - lookbackCount); i < positions.length; i++) {
const historicalPos = positions[i];
if (Math.abs(historicalPos.lat - lat) < 0.0001 && Math.abs(historicalPos.lon - lon) < 0.0001) {
const positionsBack = positions.length - 1 - i;
if (positionsBack > 0 && positionsBack <= 10) {
return;
}
return response.json();
})
.then(data => {
L.geoJSON(data, {
style: {
color: type === 'express' ? 'blue' : type === 'normal' ? 'green' : type === 'semi' ? 'orange' : 'red'
}
}).addTo(railLayers[type]);
})
.catch(error => console.error(`Error fetching ${type} rail data: `, error));
}
}
positions.push({ lat, lon, timestamp });
if (positions.length > 30) {
positions.shift();
}
}
function loadStations() {
fetch(`${server}/api/station`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(response => response.json())
.then(data => {
L.geoJSON(data, {
pointToLayer: function (feature, latlng) {
const shownLayer = parseInt(feature.properties.shown_layer.slice(2), 2);
const marker = L.marker(latlng, {
icon: L.divIcon({
className: 'station-label',
@@ -180,7 +185,6 @@
if (stationLayers[shownLayer]) {
stationLayers[shownLayer].addLayer(marker);
}
return marker;
}
});
@@ -190,35 +194,47 @@
function loadTrains() {
startSpinner();
const timestamp = Date.now();
let wasPopupOpen = false;
if (map._popup && map._popup._source) {
const popup = map._popup;
if (popup._source.options && popup._source.options.trainId) {
openPopupTrainId = popup._source.options.trainId;
wasPopupOpen = true;
}
}
myFetch(trainAPI, {
headers: {
"x-requested-with": "com.korail.talk",
"referer": "https://gis.korail.com/korailTalk/entrance",
"user-agent": "korailtalk AppVersion/6.3.3"
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
trainLayer.clearLayers();
}
})
.then(response => response.json())
.then(data => {
trainLayer.clearLayers();
let markerToReopen = null;
let markerToFollow = null;
L.geoJSON(data, {
L.geoJSON(data, {
pointToLayer: function (feature, latlng) {
const trainId = `${feature.properties.trn_case}_${feature.properties.trn_no}`;
updateTrainPosition(trainId, latlng.lat, latlng.lng, timestamp);
const avgSpeed = calculateAverageSpeed(trainId);
const speedText = avgSpeed ? `${avgSpeed.toFixed(1)} km/h` : 'N/A';
const followButtonText = followingTrainId === trainId ? 'Unfollow' : 'Follow';
const followButtonColor = followingTrainId === trainId ? '#dc3545' : '#28a745';
const trainIconHtml = `
<div style="position: relative; text-align: center;">
<div style="background-color: #007bff;
border-radius: 50%;
width: 16px;
height: 16px;
display: inline-block;
border: 2px solid white;"></div>
<div style="font-size: 12px;
color: black;
background-color: white;
color: ${feature.properties.trn_case === "SRT" ? 'white' : 'black'};
background-color: ${feature.properties.trn_case === "SRT" ? '#572b4c' : '#007bff'};
border: 1px solid black;
margin-top: 2px;
padding: 1px 3px;
@@ -229,61 +245,72 @@
transform: translateX(-50%);
white-space: nowrap;">${feature.properties.trn_case} ${feature.properties.trn_no}</div>
</div>`;
return L.marker(latlng, {
const marker = L.marker(latlng, {
icon: L.divIcon({
className: 'train-marker',
html: trainIconHtml,
iconSize: [30, 42],
iconAnchor: [15, 21]
})
}),
trainId: trainId
}).bindPopup(`${feature.properties.trn_case} ${feature.properties.trn_no}<br>
(${feature.properties.dpt_stn_nm} -> ${feature.properties.arv_stn_nm})<br>
${feature.properties.now_stn} ${feature.properties.next_stn}`);
${feature.properties.now_stn} ${feature.properties.next_stn}<br>
<strong>Avg Speed: ${speedText}</strong><br>
<button onclick="toggleFollow('${trainId}')"
style="background-color: ${followButtonColor};
color: white;
border: none;
padding: 3px 8px;
border-radius: 3px;
cursor: pointer;
margin-top: 5px;">${followButtonText}</button>`);
if (wasPopupOpen && trainId === openPopupTrainId) {
markerToReopen = marker;
}
}).addTo(trainLayer);
clearSpinner();
})
.catch(error => console.error('Error fetching train data: ', error));
}
loadRail('express');
loadRail('normal');
loadRail('semi');
loadRail('logis');
for (let f = 0; f < 6; f++) {
document.getElementById(`layer${f}`).addEventListener('change', function () { // lable0: 0b 1XXXXX, label1: 0bX1XXXX, ...
for (let i = 0; i < 64; i++) {
if ( i & (1 << (5 - 0)) ) {
if (this.checked) {
map.addLayer(stationLayers[i]);
} else {
map.removeLayer(stationLayers[i]);
if (isFollowing && trainId === followingTrainId) {
markerToFollow = marker;
}
return marker;
}
}).addTo(trainLayer);
if (markerToReopen) {
setTimeout(() => markerToReopen.openPopup(), 100);
}
if (markerToFollow) {
setTimeout(() => map.setView(markerToFollow.getLatLng(), map.getZoom()), 100);
}
clearSpinner();
})
.catch(error => {
console.error('Error fetching train data: ', error);
clearSpinner();
});
}
document.getElementById('reloadTrains').addEventListener('click', loadTrains);
document.getElementById('autoReload').addEventListener('click', autoReload);
let reloadInterval = null
function autoReload() {
if (this.checked) {
reloadInterval = setInterval(loadTrains, 2000);
}
else {
if (reloadInterval) {
clearInterval(reloadInterval);
reloadInterval = null;
}
function toggleFollow(trainId) {
if (followingTrainId === trainId) {
followingTrainId = null;
isFollowing = false;
} else {
followingTrainId = trainId;
isFollowing = true;
}
loadTrains();
}
document.getElementById('reload').addEventListener('click', loadTrains);
loadStations();
loadTrains();
setInterval(loadTrains, 2000);
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -41,10 +41,6 @@ async def getApiTrain():
return tapi.json()
with open("json/trains.json", "r") as f:
return json.load(f)
if __name__=="__main__":
import uvicorn
uvicorn.run(app)