It does not automatically know. It is consantly receiving signals from a network of satellites in space which tells it, and consequently you, where it is.
actual mathematics is complicated, but basically by triangulating with multiple satellites by measuring signal time delay and solving a set of simultaneous equations to best convergence.
It doesn't know where you are going, but it knows where you are at the moment. It does this by triangulating your signal with several satellites orbiting the earth in fixed orbit. The technology was...