Magnetic fields produced by dc railways can disturb operations at geomagnetic observatories. These magnetic fields consist of two parts: the ideal "full-loop" field due to the traction current in an overhead wire and in the rails, and the "leakage" field due to currents leaking from the track into the ground. Pirjola et al. (2007) present formulas with numerical examples for the magnetic field assuming a constant leakage current density between the train and the feeding substation. Lowes (2009) considers this assumption questionable. In this paper, we derive exact formulas for the magnetic field assuming that the leakage current density changes linearly being largest at the train and decreasing to zero at the substation. The Earth is considered layered. Computer codes enable calculations of the magnetic fields due to any number and configuration of the train-substation pairs at any points of observation. Numerical examples show that the value of 10 pT can easily be exceeded. An important conclusion is that the magnetic fields in the cases of a linearly changing and a constant leakage current density do not differ much. Particular attention is paid to the temporal behaviour of the magnetic field when one or two trains travel along a railway.