Stellar dynamos generate magnetic fields that are of fundamental importance to the variability and evolution of Sun-like and low-mass stars, and for the development of their planetary systems. As a key to understanding stellar dynamos, empirical relations between stellar parameters and magnetic fields are required for comparison to ab initio predictions from dynamo models. We report measurements of surface-average magnetic fields in 292 M dwarfs from a comparison with radiative transfer calculations; for 260 of them, this is the first measurement of this kind. Our data were obtained from more than 15000 high-resolution spectra taken during the CARMENES project. They reveal a relation between average field strength, <B>, and Rossby number, Ro, resembling the well-studied rotation-activity relation. Among the slowly rotating stars, we find that magnetic flux, {Phi}_B_, is proportional to rotation period, P, and among the rapidly rotating stars that average surface fields do not grow significantly beyond the level set by the available kinetic energy. Furthermore, we find close relations between nonthermal coronal X-ray emission, chromospheric H{alpha} and Ca H&K emission, and magnetic flux. Taken together, these relations demonstrate empirically that the rotation-activity relation can be traced back to a dependence of the magnetic dynamo on rotation. We advocate the picture that the magnetic dynamo generates magnetic flux on the stellar surface proportional to rotation rate with a saturation limit set by the available kinetic energy, and we provide relations for average field strengths and nonthermal emission that are independent of the choice of the convective turnover time. We also find that Ca H&K emission saturates at average field strengths of <B>~800G while H{alpha} and X-ray emission grow further with stronger fields in the more rapidly rotating stars. This is in conflict with the coronal stripping scenario predicting that in the most rapidly rotating stars coronal plasma would be cooled to chromospheric temperatures.