Geolocating a visitor who reached your web pages directly from his browser is required when, for example, you need to display the prices of your products in his local currency, display a version of your content translated into his language, or display ads localized in his geographical area.
There are two main ways to geolocalize a visitor: browser-based geolocation and IP address-based geolocation.
It is easy to use in jQuery:
The major disadvantage of browser-based geolocation is that it will ask the user to share his location information with your scripts. This will certainly spoil the user experience because of an annoying pop-up. If the visitor refuses to share his location, then your script will not get any location information.
Also, you should note that geolocation API will only work over HTTPS. Hence you may have difficulties when testing it over your local development server.
An IP address identifies each device connected to the Internet. IANA is the body in charge of distributing these addresses between each continent and then passing responsibility to other organizations to distribute countries' addresses. Here is the list of those organizations:
Therefore, a geolocation service can use these organizations' data to find out in which country your visitors reside.
To obtain accurate location information at the level of regions, cities, and precise GPS coordinates, it will then be necessary to get databases from Internet service providers, as they are responsible for distributing IP addresses within a country.
The most practical solution is to use an API through an AJAX call to obtain the visitor's IP address and his geographical location.
Abstract provides the free IP Geolocation API that is fast and accurate. All you have to do is create an account, which does not require a credit card, to get your private API key. Here's how to use it in jQuery: