How to detect website visitor’s location using Javascript?

How to detect website visitor’s location using Javascript?

First blog post on hashnode sharing how to detect user's location using javascript.

·

3 min read

Let’s jump right into it.

If you want to identify the current location of your website visitors using Javascript, you can either use HTML5’s Geolocation API or an IP geolocation API.

The first method requires users’ consent while the second one doesn’t. But the percentage of visitors willing to share their location with you is very less. Hence, you have to depend on an unintrusive method like IP geolocation.

Hence, for foolproof location detection, you have to implement both of the methods in your Javascript code.

HTML5’s Geolocation API

The HTML5’s geolocation API is a simple javascript function that prompts users to share his/her location.

navigator.geolocation.getCurrentPosition(success, error, options)

This function will only work if the user has enabled location access to his/her browser. Otherwise, it will throw an error.

The options variable can be used to tune the level of accuracy of the result. If you pass nothing, it will use a default value.

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

There are 3 parameters within options variable:

  • enableHighAccuracy allows you to choose the accuracy mode of the result.
  • timeout allows you to define the amount of time(milliseconds) to wait for a result before triggering an error.
  • maximumAge is a value provided in milliseconds that allows you to determine if you accept the cached result. By default, it is 0 which means it will always try to retrieve the real current position.

The function will return GeolocationPosition javascript object which contains the location coordinates, along with other useful data.

coordinates{
 accuracy: 41,
 altitude: null,
 altitudeAccuracy: null,
 heading: null,
 latitude: -33.873560, 
 longitude: 151.059745,
 speed: null,
}

Once you have the coordinates, you will need to call a reverse geocoding API to translate this into a readable address.

Reverse Geocoding API

There are many reverse geocoding APIs to choose from. I will be using BigDataCloud's free client-side reverse geocoding API. It is free for client-side implementation and doesn't require any API key or account creation.

Here is an implementation:

var bdcApi = "https://api.bigdatacloud.net/data/reverse-geocode-client";
bdcApi = bdcApi + "?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude + "&localityLanguage=en";

Http.open("GET", bdcApi);
Http.send();
Http.onreadystatechange = function () {
   if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
   }
};

The API returns detailed locality information like postcode, city, state, country and admin-level information along with wikidataid.

Note that the API is free to use as long as the implementation is on the client-side and it uses real-time location data of the client

IP geolocation API

Now let's handle the scenario when the users don't provide permission to access their current location.

The benefit of using BigDataCloud's free client-side reverse geocoding API is that it has a default IP geolocation fallback. So instead of trying to implement a different API service, you can simply call the same API to retrieve locality information using the client's IP address.

Here is how it works:

var bdcApi = "https://api.bigdatacloud.net/data/reverse-geocode-client";

Http.open("GET", bdcApi);
Http.send();
Http.onreadystatechange = function () {
   if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
   }
};

You just have to skip the step of passing coordinates value to the API and it will automatically call its IP geolocation engine instead of reverse geocoding service.

The data format is the exact match of the reverse-geocoding API. The output contains a property called lookupSource which indicates if the data was based on the client's coordinate or IP Address.

{..
  "lookupSource": "coordinates",
}
{..
  "lookupSource": "ip geolocation",
}

Let's recap

So the easiest way to detect your website visitor's current location is to use the combination of HTML5 geolocation API, reverse geocoding API and IP geolocation API.

The benefit of BigDataCloud's API is that you can use a single API to call both reverse geocoding and IP geolocation services and it doesn't require any API key and is free to use.

Here is the full implementation on CodePen.