First look at the inner SELECT, it is doing two things for you:
1. It sums the distances based on the name. This is done by The SUM(dist) and the GROUP BY name. The GROUP BY combines the records by the name , so that only the record with the same name are used in the SUM() operation.
2. It finds the MAX and MIN id again based in the name. The GROUP BY ensures that it only looks at the the ids of the records with the same name
The "g" is used as an alias of the result set generated by the inner query.
Then the JOIN is used to combine result sets based on some criteria. Think about it as putting two or more tables side by side based on a common column. IN this case is the ids of the names.
Finally look at what the outer select is using : g.name,first.slat,first.slon,last.elat,last.elon,g.totaldist
g.name and g.totaldist are taken from the table "generated in the first query"
first.slat and first.slon are taken from the columns of the first table .
Similarly, last.elat and last.elon are taken from the columns of the last table .
It might help to learn more about how the JOIN works . Take a look at this link, it is not a perfect explanation , but it might help