Although the marathon roots back to ancient times, evolving more and more into what we see now, what we know as today's version was really established within the 20th century. The first truly organized marathon in 1896 was set at a distance of 40km or about 25 miles. It is said that the 40km was representative of the distance a soldier called Pheidippides ran, in 490 B.C., to share the news of the Greek defeat over the Persians, before collapsing after sharing his message.
The distance is said to have been changed during the 1908 olympics in London to 26.2 miles, in order to accommodate the royal family. Though there were variations in the distance during marathons to follow, the distance we know today finally stuck after several more years of deliberating over the decision.
There are a few variations of the story, however we do know that the distance of 26.2 miles (42.195km) was based on the set distance of the 1908 games in London, officially being adopted in the rules in 1921.
http://www.history.com/news/ask-history/why-is-a-marathon-26-2-miles
https://www.livescience.com/11011-marathons-26-2-miles-long.html
https://www.boston.com/sports/boston-marathon/2017/04/13/why-is-a-marathon-26-2-miles