How to Get a Website User's Location in JavaScript

Published Jun 30, 2022

How can we obtain our website user’s location in JavaScript?

There are lots of ways to get a user’s location in JavaScript, including the native HTML Geolocation API, third-party services, and the Internationalization Intl object.

1. Using ECMAScript’s Internationalization Intl object

We can use ECMAScript’s Intl object to get a user’s timezone as well as a rough guess of their country (timezones span many countries).

This is a great option because it does not require user permission or any external APIs.

Running the following line of code will give us a timezone.

const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

Depending on where you are, it might return a string like America/Denver.

Suppose we have two maps.

  • countries, which maps country abbreviations to country name
  • timezones, which maps timezones to country abbreviations and other related geodata

Those maps might look something like this.

const countries = { 
  ...,
  US: "United States of America", 
  UY: "Uruguay", 
  ...
};
const timezones = {
  ...,
  "America/Denver": {
    u: -420,
    d: -360,
    c: ["US"]
  },
  "America/Detroit": {
    u: -300,
    d: -240,
    c: ["US"]
  }, 
  ...
};

The entire map of countries can be found here. The entire map of timezones can be found here.

Assuming we have countries and timezones declared and initialized in our code, we can obtain a website visitor’s country by linking timezones to countries.

const getCountry = () => {
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  if (!timezone || timezone === "") return null;
  const countryAbbreviation = timezones[timezone].c[0];
  const country = countries[countryAbbreviation];
  return country;
}

2. Using the Geolocation API

We can also use the Geolocation API to obtain a user’s geographical position (longitude/latitude). This API is now standard in all modern browsers.

const getLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, handleError);
  } else {
    console.error("Geolocation is not supported by this browser.");
  }
}
const handleError = (error) => {
  console.error(`ERROR(${error.code}): ${error.message}`);
}
const showPosition = (position) => {
  const latitude  = position.coords.latitude;
  const longitude = position.coords.longitude;
  console.log(`Lat: ${latitude}, Long: ${longitude}`;
}

This API only returns latitude and longitude; in order to obtain useful information from this (e.g. country, city), we’ll likely need to use another service.

Be sure to read the Mozilla documentation to explore the capabilities of this Geolocation API.

3. Using an external API

The last option is to use a third-party service, generally available through an API we call from the client.

There are lots of options when it comes to geolocation, but most (if not all) are rate limited and have a subscription fee.

Some APIs may include: ipinfo.io, MaxMind, ipregistry, and IP2Location.

Calling the API might look something like this:

const res = await fetch(API_URL);
const json = await res.json();
// Do something with the result