Indoor, underground, or underwater threedimensional (3D) localization provides fundamental support to the applications of mobile wireless sensor networks (WSNs). In these applications, a single robot cannot work, as there are no GPS signals and few references for the robot to loalizae itself in the large in-door spaces. Existing in-door localization approaches usually rely on the projection of the 3D topology graph onto a horizontal plane. Such projection is infeasible in a narrow vertical space, either, since it requires three location-known nodes, called anchors, as reference nodes on a large horizontal plane. In this paper, we propose a new distributed 3D localization protocol, FlagLoc, for the mobile WSNs. FlagLoc uses a flag that is composed of three anchor nodes on a plane of any angle to start the localization and to lead the network motion of a mobile WSN. Furthermore, FlagLoc compensates for distance and motion measurement errors. The evaluation shows that FlagLoc significantly outperforms the existing state-of-the-art schemes in terms of accuracy.