There are two basic methods for identifying the geolocation of your website users; these are either using an IP lookup method, or by using a Geolocation API.
One helpful tool built into HTML5 is a geolocation API. If you choose to use this method, users will be prompted to ask if they are willing to provide their geographic location. This method should work with all modern browsers (or at least all of those other than Internet Explorer 10 and older, and Opera Mini)
The advantage of this approach is that it is likely to provide fairly accurate results, and it will provide you with the geolocation coordinates, or the longitude and latitude of the user. The disadvantage of this is that it will not provide you information unless the user voluntarily provides the information, which may not be the case in many circumstances. Examples of this can include the user's local timezone, currency, as well as other things like ISP and connection type (such as VPN or proxy). Understandably, many users are concerned about privacy and will choose not to allow this functionality.
However, that said, we will show you how to implement this with this free public 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.
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.
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. Have fun!