We listen to dumps, buses and trains in Prague and draw them on a map

Where are the trams, buses and suburban trains in Prague at the moment? | Shows official map and mobile app | But did you know that an API is also available? Let’s try today

© Provider: Zive.cz

Urban and regional public transport in the Czech Republic is undoubtedly one of the best in the world. No wonder, unlike the United States, for example, that there was a massive, market-based disruption to the circulation of individual cars only with the fall of the previous regime.

Check out other articles in the Let’s Program Electronics series

Vehicles are often equipped with a satellite position receiver, so it was only a matter of time before carriers came up with mobile and web apps that displayed the approach of the bus or tram on a map and in near real time.

First was Brno, then Prague was added, and both cities today also publish location data on their fleet via Open and free API. Each of you can use them and build almost any application on them:

All trams, buses and trains around Prague

Today we are going to try it in the simplest possible application in Javascript and HTML. The result will be a file salinoleaks.htmlwhich when loaded in a browser displays the OSM map using the Leaflet library, then connects to the Golemio API server and downloads a huge JSON with all the buses, trams, trains and other vehicles that are part of the Prague PID integrated transport system.

For this to work, we will first generate a personal API key on the Golemio API site to identify ourselves. As we said above, access to the API is free, so don’t be afraid of packages, but the key is also needed so that the system administrator can block, for example, users who overload the API.

Golemio API, give me a list of all vehicles

So we have a key in the form of a long string of text, so now ask the server where all the PID vehicles equipped with the satellite receiver are moving at the moment. Use the HTTP GET /vehiclepositions request to do this.

On the link above you will find all its parameters and when you call it in its simplest form https://api.golemio.cz/v2/vehiclepositionsso…

So nothing happens and the server responds with an error message because we are not connected. We didn’t use the API key which we need to send to the server in a special header access token x.

We download JSON from the command line

On Linux systems, the cURL text from the HTTP client and a command that saves the result to the praha.json file would help us:

curl –header “x-access-token: API key” https://api.golemio.cz/v2/vehiclepositions> praha.json

Under Windows and its PowerShell, we would get the same thing with the command:

iwr https://api.golemio.cz/v2/vehiclepositions -Headers@{“x-access-token”=”API klic”} -OutFile praha.json

Iwr stands for Invoke-WebRequest powershell HTTP client.

And now let’s try it in modern JavaScript

Ok, we should have a command line, but we will download the data in Javascript. But first, I apologize to readers who pay homage to prehistoric versions of web browsers.

They have a big red stop sign in the programming series because I intend to use only modern versions of ECMAScript, which is also the basis for javascript implementations in browsers.

The Fetch API downloads the giant JSON

In short, if you’re not reading this article in Internet Explorer, where it really won’t work, you can download Golemio data with me using the built-in javascript interface. Fetch API for asynchronous HTTP communication.

The request, including the special header with the key and reading the result in JSON format, could look like this:

retrieve(“https://api.golemio.cz/v2/vehiclepositions”, {method: “GET”, headers: {“x-access-token”: golemio_klic}}). then(response => response.json( )) .then(data => {console.log(“Downloaded and decoded JSON:”); console.log(data);});

Hundreds of geographic coordinates

JSON response for the request / vehicle positions contains a field features, which is actually a list of all registered PID funds, which are currently moving in and around Prague. There will be hundreds of vehicles during the day.

Each element also contains objects geometry and Properties.

Inside the geometry we find a field contact information to latitude and longitude coordinates Vehicles. This way we could draw anonymous points on the map and take advantage of Prague’s built-in traffic density, however, in the giant JSON we still have properties object.

Properties offers a lot of additional information about the connection. For example, a nested element properties.last_position.bearingwhich contains the heading/azimuth of the vehicle in whole degrees, or the object properties.last_position.delay with additional data on the current delay.

Is it a tram? Where is he going? And who runs it?

Everything else is hidden in the building travel.properties. In the sub-object property.trip.gtfs it will take an article type_route, which identifies the line type by a numeric index. Value 0 represented tram, 1 belongs metre, 2 railways, 3 bus etc

For a full list, see the GTFS specification documentation, which stands for genergy Jransit Fneed WITHspecification. It is primarily used by Google to describe public transport, and others have joined, including our Prague API.

Another interesting element is trip_headsigni.e. the destination of the vehicle (Kladno-Ostrovec), or trip_short_name (respectively alternative route_short_name), which reveals the row number (Os 9826). Article trip.agency_name.scheduled finally contains the name of the carrier (ČESKÉ DRÁHY).

Library of leaflets with OSM maps

That might be enough to get started, but we still need the map. The Leaflet JavaScript library works similarly to Google’s Map API, but with the difference that it doesn’t offer any map layers on its own.

It can work with nice tiles from the paid Mapbox, for example, but it can also handle the basic OpenStreetMap map. If the conditions are met fair use you can communicate with its map server via Leaflet without paying a single euro cent.

Fair use is, in particular, that in this way the mapserver will not be burdened by a hypothetical large commercial service with many visitors. It is assumed that he downloads the raw OSM vector data and starts the map server at his own expense. But of course, do-it-yourselfers will adapt to foggy conditions.

We will create a map object

Viewing the map in Javascript is really easy. In HTML, just create a DIV container with the appropriate ID:

And in Javascript, we then connect it to the Leaflet library map object, specifying i map center coordinates (z.š. a zd) a zoom rate (higher number, bigger zoom):

flight map = L.map(“map”).setView(,8);

We have started the map object, but we still need to connect it to a map tile provider service. As we said, we choose the OSM project, so the rest of the code could look like this:

let dlazdice = L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, {attribution: ‘Bastl:Živě.cz |’+’ Data: PID | ‘+’ API: Golemio | ‘+’ Map: OpenStreetMap ‘}).AddTo(map);

Part of the OSM tile layer connection is the user footer, which appears in the lower right corner and contains copyright and resource information. We are inspired by OSM, so there must be a link to meet the license conditions. Even if it was not an obligation, at least it is decency!

Marker on the map with a tram icon

The map is still empty, but when we return to JSON with the current positions of Prague’s integrated transport vehicles, we can bring markers above the map. And since we know the type of each vehicle (the route_type entry), each tag can have a specific icon depending on whether it is a tram, a bus, a train, etc.

Here’s how to create a tag with your own icon:

flight icon = L.icon({iconUrl: “tramvaj.png”, iconSize:}); flightmark = L.marker(,{icon:icon}).addTo(map);

As you can see we will use the image as a brand icon tramvaj.pngwhich we downloaded from flaticon.com. The image is sized 24×24 pixel. Settings 50.1589 and 16.47899 in the object, the new tags correspond to the latitude and longitude and the parameters icon we will refer to the icon we created in the previous step.

When clicked, a bubble with connection details will appear

To make our map interactive, clicking on any marker on the map will show a bubble with details about the specific vehicle or line. We will use the data we read in the section Properties for each giant terrain feature features with the individual vehicles that the API currently registers.

How to do? We attach the bubble to the tag using the bindPopup method, whose parameter is the HTML code that appears in the dialog box when clicked:


Route 1234

“+”Vehicle: Train

“+”Carrier: Czech Railways

“+”Go to : Čmelakovice

“+”Small size : Yes”);

And that’s all. As soon as our Javascript iterates through the entire JSON field, it easily draws hundreds of sub-markers above the map. You can freely zoom here, move around and click on the markers for more details.

If you want to display the situation in real time, all you have to do is query the traffic API continuously and refresh the data above the map. However, beware the JSON is really big – there are hundreds of vehicles –you should therefore consider the frequency in this case so as not to overload the server unnecessarily and violate the rules of fair use.

But this is already a task for you and for further study of the application interface, which offers dozens of other settings and functions.

Source code

Finally, the complete source code must not be missing salinoleaks.htmI. Just save it to a file of the same name, insert a custom API key into the golemio_key constantthat we generated at the beginning of the article, and load the file into a web browser.

Leaks from Šalin: PRAGUE

Read also :

Leave a Comment