Android, Apple and other companies have access to a huge data base where they can look up Wlan-Device-Id (the Mac-Adress of your WLAN Router) to lat/lon coordinates.
So when your phone detects a "known" WLAN, it can either:
- look up a local cache of Wlan-id to coordinate, or if you have internet connection active,
- it can connect and query the coordinate for the Wlan id via that data base.
Remains the question where they have the coordinate of your WLAN-id?
Probably the first time when you have GPS active while connected to your WLAN.
SkyHook is such a company that provides that data.