How To Detect The Location of Your Website’s Visitor Using JavaScript

Detecting the location of your website’s users is useful for a variety of reasons. You might for instance want to display different content, perhaps in different languages for people from different countries, or display targeted information to visitors from different locations. Whatever your reasons might be, you have two options

  1. The Geolocation API and
  2. IP Address Lookup

The Geolocation API

The geolocation API is a new html5 feature that allows a web page’s visitor to share their location with you if they so choose. When you try to retrieve the location using this API, a prompt is shown to the user asking them if they will like to share their location with your site.

Example of the kind of prompt shown to the user

Obviously, this means that you won’t get the location if the user decides not to share their location with you.

if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
},
  function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving
location', error_message)
}
});
} else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
}

Drawbacks: It only works on secure servers (https). It is not supported on Internet Explorer 10 and below and OperaMini.

The output from the code only gives us the coordinates. What if you need the actual location or say address in words? Say no more. We’ll talk about this after we discuss IP lookup. Up next==>

IP Address Lookup

An IP address lookup is another way to get the location of your visitor. We usually use Public IP lookup services/API for this option. Some are paid services, while some are free services.

Examples include http://ip-api.com/ , https://ipinfo.io , geoip-db.com etc They provide the data in various formats too (JSON/XML/CSV…). To get a good understanding of how to use this various services, reading their documentation helps.

I’ll be using http://ip-api.com/ for my example. I could use vanillla JavaScript, but I won’t. Life has been made easier by libraries like jquery.

function ipLookUp () {
$.ajax('
http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
      },

function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
ipLookUp()

And I get this as an output in my console

Drawbacks: Although the country given by most IP lookup services is almost always accurate, the coordinates are not always accurate. Also, If you are going to be making plenty of requests, some of these services require that you get an API Key , and that you pay.

You could use the ip lookup as an alternative or backup for the geolocation API in browsers that don’t support geolocation or say when an error occurs like this

if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
},
 function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving
location', error_message)
ipLookUp()
}
});
} else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}

Now that we have our location in one way or the other, we are going to convert the latitude and longitude we retrieved to a more comprehensive address using the Google Maps Reverse Geocoding API.

According to google, Reverse geocoding is the process of converting geographic coordinates into a human-readable address. All we need is an api key. Follow the steps to get one here

function getAddress (latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?
latlng=' + latitude + ',' + longitude + '&key=' +
GOOGLE_MAP_KEY)
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
getAddress(6.4531, 3.3958)

Here’s what I got in my console.

Example output of the Reverse Geocoding API

You can play around with the object, to get the desired address in the format you like best.

Putting it all together, we have this.
NOTE: the ipLookUp function was modified

function ipLookUp () {
$.ajax('
http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAdress(response.lat, response.lon)
},

function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress (latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?
latlng=' + latitude + ',' + longitude + '&key=' +
GOOGLE_MAP_KEY)
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
getAddress(position.coords.latitude,
position.coords.longitude)
   },
function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving
location', error_message)
ipLookUp()
}
});
} else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}

At this point we know how to retrieve location for our user no matter what, and you can now tailor the code to your own unique problem. I hope you learnt something. 
You can the find the code for this article on github

tldr? too bad, go ahead and start reading :)

Cheers~