Though prehistoric remains from the Paleolithic, Neolithic, and Bronze Ages have been unearthed in the Manzanares Valley, prior to Madrid's sudden elevation to capital city in 1561 its history was rather undistinguished. Over a period of many centuries crucial in Spanish history, Madrid's significance was negligible. The Romans built their most advanced outpost on the Iberian peninsula, but left nothing of consequence in Madrid. Armies of North African nomads, intent on disseminating Islam, invaded the peninsula in a.d. Within 10 years, they had overrun most of Spain. If Madrid played any role in these pivotal events, no record of it remains. The first solid references to this obscure settlement on the Castilian plateau, guarded by the looming Guadarrama mountain range, appear in the 9th century. The Arabic name for "place of many springs," variously recorded as Magerit, Mayrit or Magrit, eventually evolved into Madrid. The hamlet entered historical chronicles for its military significance; it was located near the main line of resistance to the Christian reconquest. Over centuries of struggle, the defending Moorish army built a full-scale fort, or Alcázar, on the heights of Madrid commanding the Manzanares valley. After several unsuccessful skirmishes, the Christian forces of Alfonso VI captured Madrid in 1083. The Alcázar became a fort of the crown of Castile. During a counter-offensive in 1109, the town was overrun by the Moors, but the Christianized fortress held. The Moors were expelled from the town, but they remained in control of southern Spain for almost four centuries. Meanwhile, Madrid enjoyed brief prominence in 1308 when king Ferdinand IV and his Cortes, an early version of parliament, held a formal meeting in the fledgling town. From then on, the kings of Spain began to visit Madrid, where the air was invigorating and the hunting excellent. Ferdinand and Isabella, the Catholic monarchs that united all the provinces of Spain, first visited Madrid in 1477. 
Who had overun most of Spain?
Armies of North African forces