A Train Ride in Three.js

For today's #30DayMapChallenge - Network, I was inspired by DLR Rider to try and create a first-person view of a train network. I decided that recreating London's Docklands Light Railway network using just elevation and railway data might look a little boring so instead I've mapped a section of the Swiss railway network. This makes for a much more dramatic journey (although in truth it is only a tiny, tiny part of a much larger network).

Bernina Switchbacks 3D is the result: a Three.js experiment that puts you in the driver's seat of a train travelling through the Swiss Alps. You can ride along the railway, reverse direction, change speed and follow your progress on a small interactive map.

The 3D landscape is created using elevation tiles from Mapterhorn. These tiles provide digital elevation data which I use to construct a 3D terrain mesh in Three.js. The elevation values are decoded from the RGB colours in the tiles and used to position the vertices of the terrain mesh at their corresponding heights. I then colour the landscape according to elevation, creating green lower slopes, darker rocky terrain and snow-covered peaks.

The railway itself comes from OpenStreetMap. I downloaded the railway data as GeoJSON and used JavaScript to join the individual railway sections together into a continuous route. This involves checking the distances between the endpoints of each section and joining the closest ones.

The first-person view is created by positioning the Three.js camera just above the railway and continually moving it along this curve. You can pause the journey, reverse direction or adjust the speed using the controls in the top-left corner. I've also included a small MapLibre inset map in the bottom-right corner, using the OpenFreeMap Liberty style. This shows the complete railway route, the train's current position and the section of track already travelled.

There is still plenty of scope for improvement. For example buildings and trees could be added to the map to create a more complete 3D environment. Nevertheless, it's an interesting experiment in combining OpenStreetMap, digital elevation models and Three.js to turn a geographical network into something that you can actually travel along from a first person perspective.

Comments

Popular Posts