Oops! Something went wrong while submitting the form.
No credit card required
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.
The navigator.geolocation javascript APIs of modern browsers make it possible to obtain the precise location. It is widely available and uses the device's GPS location, the GSM antennas' information, or information related to the network stack (IP address, MAC address).
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.
How IP address geolocation works
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:
AFRINIC for Africa Region
APNIC for Asia/Pacific Region
ARIN for Canada, USA, and some Caribbean Islands
LACNIC for Latin America and some Caribbean Islands
RIPE NCC for Europe, the Middle East, and Central Asia
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 advantage of such a method is that it does not require any authorization from the visitor. The two disadvantages are that it is difficult and time-consuming to set up the IP address distribution database by oneself and keep it updated. Secondly, it is impossible to obtain the visitor's IP address directly in jQuery, just like in JavaScript, without an AJAX call to a server that can determine and return this address.
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: