Transport For London Next-train Display
About the project
A handy R-Pi based mini-monitor, displaying the next train on my nearest train station! (Customisable too for any TFL station)
Project info
Items used in this project
Hardware components
Story
Mainly for my partner, but we live roughly a 4 minute walk from the station, our train into the city (And thus to work) leaves every 15 minutes.
TFL has an abundance of data about their services, and I wanted to practice my Javascript too, so worked out pretty well. The app refreshes every 15 seconds, the API refreshes roughly every ~40 seconds, so remains accurate.
- window.onload = function what() {
- $.getJSON("https://api.tfl.gov.uk/StopPoint/910GPCKHMQD/arrivals", function(data) {
- console.log(data);
- var expectedTrains = [];
- for (var i = 0; i < 9; i++) {
- // figuring out timestamp, time expected of train, and then difference, then converting to rounded minutes
- var nextTrain = data[i].destinationName;
- var platform = data[i].platformName;
- var timeStamp = new Date(data[i].timestamp);
- var expected = new Date(data[i].expectedArrival);
- var diff = Math.abs(expected - timeStamp);
- var minDiff = (diff / 60 / 1000).toFixed(0);
- expectedTrains.push({nextTrain, platform, expected, minDiff});
- }
- console.log(expectedTrains);
- // sort in assending order by expected time
- expectedTrains.sort(function(a, b){return a.expected-b.expected});
- console.log(expectedTrains);
- // Platform 1 - Northbound
- var firstOnPlatform1 = expectedTrains.find(function(element) {
- return element.platform == "Platform 1";
- });
- document.getElementById("number1").innerHTML = (firstOnPlatform1.nextTrain) + " in " + (firstOnPlatform1.minDiff) + " minutes " + "on " + (firstOnPlatform1.platform);
- // Platform 2 - Southbound
- var firstOnPlatform2 = expectedTrains.find(function(element) {
- return element.platform == "Platform 2";
- });
- document.getElementById("number2").innerHTML = (firstOnPlatform2.nextTrain) + " in " + (firstOnPlatform2.minDiff) + " minutes " + "on " + (firstOnPlatform2.platform);
- });
- };
- // Method to look at next time for date formats.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Customisation
Next steps would be to integrate a dropdown box to choose which station to monitor... one day!
The following .getJSON:
- $.getJSON("https://api.tfl.gov.uk/StopPoint/910GPCKHMQD/arrivals")
Can be customised to any TFL station, by changing the `910GPCKHMQD, the code can be found by searching this link
https://tfl.gov.uk/travel-information/stations-stops-and-piers
and snipping the link of the result. For example, Caledonian Road's URL is
Thus it's unique identifier is 910GCLDNNRB.
Leave your feedback...