DEV Community

Muslim Zabirov
Muslim Zabirov

Posted on

How to get visitor's location (country) using geolocation in JavaScript?

I wanted to localize client side pricing for few countries without using any external API, so I used local Date object to fetch the country using new Date()).toString().split('(')[1].split(" ")[0]

document.write((new Date()).toString().split('(')[1].split(" ")[0])
Enter fullscreen mode Exit fullscreen mode

Basically this small code snippet extracts the first word from the Date object. To check for various time zone, you can change the time of your local machine.

In my case, our service only included three countries, so I was able to get the location using the following code.

const countries = ["India", "Australia", "Singapore"]
const countryTimeZoneCodes = {
  "IND": 0,
  "IST": 0,
  "AUS": 1,
  "AES": 1,
  "ACS": 1,
  "AWS": 1,
  "SGT": 2,
  "SIN": 2,
  "SST": 2
} // Probable three characters from timezone part of Date object
let index = 0
try {
  const codeToCheck = (new Date()).toString().split('(')[1].split(" ")[0].toUpperCase().substring(0, 3)
  index = countryTimeZoneCodes[codeToCheck]

} catch (e) {

  document.write(e)
  index = 0
}

document.write(countries[index])
Enter fullscreen mode Exit fullscreen mode

This was just to improve user experience. It's not a full proof solution to detect location. As a fallback for not detecting correctly, I added a dropdown in the menubar for selecting the country.


Another solution:

You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.

Here is a client-side example with Ipregistry:

fetch('https://api.ipregistry.co/?key=tryout')
    .then(function (response) {
        return response.json();
    })
    .then(function (payload) {
        console.log(payload.location.country.name + ', ' + payload.location.city);
    });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)