In the Mosque the direction was set by a Mihrab, the prayer-niche in the Jerusalem wall; but when he was outside the town the Prophet would check his direction himself either by the sun if it were during the day and by the stars if it be at night.
"We have seen the turning of thy face to heaven for guidance, O Mohammad. And now verily We shall make thee turn in prayer toward a Qiblah which is dear to thee. So turn thy face toward the Inviolable Place of Worship, and ye O Muslims, wheresoever ye may be, turn your faces when ye pray toward it. Lo! Those who have received the Scripture know that this revelation is the Truth from their Lord. And Allah is not unaware of what they do."
Koran: II - verse:144
A Mihrab was forth with made in the south wall of the Prophet's Mosque, facing towards the holy city of Mecca, and the change was accepted with joy by the Prophet and all his Companions.
From that day on the Muslims have turned in the direction of the holy and sacred Kabah for the performance of the ritual prayer, and by extension for all other rites and riyuals.