It is narrated from Sayyiduna al-Bara' bin Azib (may Allah be pleased with him) that when the Messenger of Allah (peace and blessings be upon him) came to Madinah, he kept praying facing Bayt al-Maqdis for sixteen or seventeen months, but he wished to pray facing the Ka'bah. So Allah Almighty revealed this verse: "We see the turning of your face towards the heaven. We shall surely turn you to a qiblah that you will be pleased with. So turn your face towards al-Masjid al-Haram." [Surah al-Baqarah: 144]
A man who had been praying with the Messenger of Allah (peace and blessings be upon him) passed by some people of the Ansar who were praying facing Bayt al-Maqdis and were in the state of bowing (ruku'), and he said: I bear witness that the Messenger of Allah (peace and blessings be upon him) (has received the command to face the Ka'bah). So those people also turned towards the Ka'bah. Some foolish people, who were in fact the Jews, said: "What has turned them away from their qiblah which they used to face?" [Surah al-Baqarah: 142] Then Allah Almighty said: "Say: To Allah belong the east and the west. He guides whom He wills to a straight path." [Surah al-Baqarah: 142]
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الصلاة / 2190