We put forward a scheme to study the anisotropic magnetic couplings in Sr2IrO4 by mapping fully relativistic constrained noncollinear density functional theory including an on-site Hubbard U correction onto a general spin model Hamiltonian. This procedure allows for the simultaneous account and direct control of the lattice, spin and orbital interactions within a fully ab initio scheme. We compute the isotropic, single site anisotropy and Dzyaloshinskii-Moriya (DM) coupling parameters, and clarify that the origin of the canted magnetic state in Sr2IrO4 arises from the interplay between structural distortions and the competition between isotropic exchange and DM interactions. A complete magnetic phase diagram with respect to the tetragonal distortion and the rotation of IrO6 octahedra is constructed, revealing the presence of two types of canted to collinear magnetic transitions: a spin-flop transition with increasing tetragonal distortion and a complete quenching of the basal weak ferromagnetic moment below a critical octahedral rotation.