The origin of accents in a mother tongue

In the UK, accents vary enormously, often within a matter of a few miles. Why is this and what is their origin?

This is because people used to be very immobile, living in the same places for generations. Over time, with little contact with the outside world, people’s ways of speaking slowly drift apart, not being kept in check by a predominant standard. This would be much less likely today, since people are much more mobile, and because the voices of mass media make their way into people’s homes daily. Despite mass media, however, many people continue to speak in their accustomed ways today, possibly as a way of maintaining their regional identities. There have in fact been many studies on these and similar topics.
This is by the way, by no means a phenomenon unique to English or the UK. Most languages have many different dialects/accents, and it is often a matter of dispute as to what constitutes a dialect and what consitutes a language (and this has been the matter of debate on many a thread here as well).

It’s that simple and purely random? I hoped it would have something to do with invaders and the influence of their languages in the areas in which they settled when communication and transport were slow or, effectively non-existent.

It was a bit difficult to word the question I wanted to ask (and I used the UK merely as an example of a country, which is small and has so many variants in accent - eg North, South and East London sounding different, etc). What I wanted to know was whether there was a reason for why accents sound like they do.

Yes, the invasions and outside influences also played a great role in forming British dialects. In the north, for example, there are more Norse words than in the south.
Geographical isolation and separation is, however, what keeps the differences between the dialects from dissapating, and contact promotes homogeneity.