It is called Geolocation.
Like the one we use, geolocation services have access to several databases that give them the information needed to locate someone online through their IP address. A primary source for IP address data is the Regional Internet Registries. These organizations are responsible for managing and distributing IP addresses in specific regions of the world. For more granularity, geolocation services use other sources to find the location of your IP address.
Some Internet Service Providers (ISPs) also may contribute information to databases that are helpful to geolocation services. The services might use statistical formulas and other sophisticated analytical tools and analyze the data submitted by us in our specific online activities. This helps them fine-tune their search and improve their service to subscribers.
One of the downfalls of Geolocation is that if you are not using a fixed or static IP address (an unchanging number assigned to your computer or router), this can play havoc with the service as does using a VPN or connecting to an office network, whilst working from home. The same computer may be as a result, in a period of time connect to various IP addresses in various locations and as a consequence, generate spurious results.