Get website visitor location using an IP Geolocation API
Another method is to make use of the IP address which your browser can simply grab through a standard HTTP request. To be able to do this we can get the information about the IP address from public or private services. The advantage of this approach is that the user does not need to agree or approve; the information is provided by the user’s ISP. The disadvantage is that the information may not be as accurate. ISPs tend to rotate their access points so while you will likely get accurate information about the country and city, you may get some variable results in areas where there are smaller towns; the information may be for a town nearby, but not necessarily the location of the actual user.
However, this information can be helpful for gaining a good deal of statistical metadata so you can understand what regions from where your users are accessing your site, and you can provide them with reasonably customized results based on this information.
The method we will use will be Abstract’s free Geolocation lookup.
To do this using jQuery, we can get the information for the user without even having their IP address at hand; the API will automatically get this information from the HTTP request. Here is a list and reviews of the best IP geolocation APIs. You simply need to sign up to get a unique API key, and plug it into your code below:
The advantages of using Abstracts tool is that it will provide you with a wide range of information about the user given their IP address, all of which can be used in whatever method you choose. If you're looking for a more in depth jQuery overview, see our guide on how to do IP geolocation using jQuery.
Here is an example of the output you may receive (you must request the individual data points through the API; the above example only provides IP and country):
It is really that simple. You can go one step further and use a timezone API to get more granular data. Have fun!