A very old tradition holds that when the Apostle St James came from Jerusalem to evangelize Spain, he brought an icon of the Virgin to Madrid for the future crown (according to a manuscript dated 1640).
In the 11th century, the King of Spain Alfonso VI was eager to relocated the ancient image of the Virgin that had been missing since 712 when it was hidden during the Islamic conquest. He organized a procession around the city walls led by the monarchy in person, the clergy, the nobility and the people of Madrid. When they passed in front of a storage place for wheat called the almudith (from the Moorish word almud meaning measure), a cascade of stones fell out of the wall and exposed a niche containing the image of the Virgin—henceforth called the Almudena. Astonishingly, the people saw that two candles were still burning near the painting 300 years later, which explains the darkness of her face. Since November 9, 1085, the Virgin of Almudena has been considered the patron saint of Madrid.
Adapted from paris.catholique.fr