How to get user's location with JavaScript

There are several options to detect visitor location. They differ by accuracy level, ease of use, application area, completeness of data, and at the end by price.

In this article, we collect and give you a summary of the possible ways to detect a user location and help you to choose the one that fits your case the best. In addition, we provide you with JavaScript code samples that will help you to add a solution to your project:

Why it's important to know the visitor location?

By getting visitor geolocation, you can determine where your visitor is located, which language he speaks, his timezone, his country currency, and other quite useful information. You can use all this information for geotargeting to provide your customers the best fitting content, that is relevant for their area, translated to their language, and utilizing time and currency of the region.

Moreover, knowing user geolocation can help you to optimize your website and make it comply with Privacy Laws in different countries. For example, you can skip or show the Cookes Consent banner depending on the visitor's country and language.

Get a visitor location on a client-side

There several methods of how to get geolocation information on a client-side. All of them are available with browser functionality and can be used in your web app.

Let's reveiew the options from more accurate to more generic:

Option1. HTML Geolocation API (navigator.geolocation)

All modern browsers have a build-in funtionality to get user's geographical position via HTML Geolocation API.

// get visitor's location
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, handleError);
  } else {
    console.error("Geolocation is not supported by this browser.");
  }
}

// watch visitor's location
function watchLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition, handleError);
  } else {
    console.error("Geolocation is not supported by this browser.");
  }
}

function handleError(error) {
  let errorStr;
  switch (error.code) {
    case error.PERMISSION_DENIED:
      errorStr = 'User denied the request for Geolocation.';
      break;
    case error.POSITION_UNAVAILABLE:
      errorStr = 'Location information is unavailable.';
      break;
    case error.TIMEOUT:
      errorStr = 'The request to get user location timed out.';
      break;
    case error.UNKNOWN_ERROR:
      errorStr = 'An unknown error occurred.';
      break;
    default:
      errorStr = 'An unknown error occurred.';
  }
  console.error('Error occurred: ' + errorStr);
}

function showPosition(position) {
  console.log(`Latitude: ${position.coords.latitude}, longitude: ${position.coords.longitude}`;
}

However, this information is not accessible by default. First, a browser will show a popup to a user and ask to approve the request. The request popup might look different on different browsers and platforms:

Note, the browser remembers your choice, you need to change the webpage settings to make the popup appear again.

Pros
  • Free - it's free and available as a standard browser functionality;
  • High accuracy - it's the most accurate way to get the geographical position of a user, might be as good as 10-20 meters for devices with GPS;
Cons
  • Shows popup - the API shows a popup to ask for a user consent
  • A user can decline the request - the user can decline your request, so you need to think about fallback solutions
  • No support for non-secure origin - depending on a browser, might not work on a non-secure origin (HTTP);
  • No support in old browsers - need to handle old browsers where Geolocation API is not supported;
  • No support in some countries - might be not supported in some countries;
  • Coordinates only - no address returned as a result. You need to use a reverse geocoder to get the address. Try Geoapify Reverse Geocoding API to search address by coordinates.
Best application areas
  • Position on a map - show user's position on a map;
  • Local search - search points of interest nearby;
  • Navigation - turn-by-turn navigation.

Option 2. Geolocation by IP address

Another way to get a visitor location is calling IP Geolocation API. The API will detect the visitor IP address and match it with geographical positions of IP address diapasons.

For example, Geoapify IP Geolocation API:

All you need to get IP Geolocation API results is to send HTTP Get request (register and get your API key on Geoapify MyProjects):

fetch('https://api.geoapify.com/v1/ipinfo?apiKey=YOUR_API_KEY', { 
  method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
  // use the json
});

Note, that this method can only roughly suggest the location. The location accuracy may vary from provider to provider. For most cases, Geoapify IP Geolocation API returns results with city-level accuracy.

Pros
  • Address details - the address details are returned by the API;
  • No user consent is required - you will not disturb your visitors with popups to get the consent;
  • Result is guaranteed - as the API call is independent of user decision, you can expect that you will get it;
Cons
  • City-level or worse accuracy - while IP addresses are dynamic it's not possible to detect a location with high accuracy;
  • Commercial - it's a service provided by a commercial company. However, most of the IP Geolocation APIs have a free tier. For example, you will be able to make 3000 API calls/day for Free with Geoapify;
Best application areas
  • Set map view - setup a map view on a website;
  • Improve address or places searches - use a location bias for address / places search;
  • Country info - by knowing the country you can setup currency and legal specifics;
  • Geotargeting - setup geotargeting corresponding the location area;

Option 3. Getting timezone

Determine a timezone of a user is one more way to make some guesses about the user's geographical position. As you see on the map below you can guess visitor's location quite good in some cases by knowing his timezone:

World timezones map

Map of official time zones of 2021

You can get a timezone with the ECMAScript Internationalization Intl object:

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

There are also libraries that offer more convenient methods to work with timezones. For example, Moment Timezone or Jstz package. You can use timezone in combination with browser language to improve the accuracy of your suggestions.

Pros
  • Free - it's free and available as a standard browser functionality;
  • Synchronous - no asynchronous calls are required
  • No user consent is required - you will not disturb your visitors with popups to get the consent;
  • Result is guaranteed - you can expect that you will get the result;
Cons
  • Very rough - as you can see on the map above, there are timezones that intersect several countries
Best application areas
  • Detect roughly a country;
  • Set roughly map view;

Get a visitor location on a server-side

You have slightly different tools and methods when you detect visitor's locations on a server-side. The same as for the client-side methods we sorted the available options according to results accuracy:

Option 1. Geolocation by IP address

As you do not have access to a user device and browser methods the IP Geolocation API is the most accurate method to determine a geographical position of a user. The Geoapify IP Geolocation API accepts an IP address as a parameter and returns a location according to it. Here is a code sample of how to make an API call with node-fetch library (register and get your API key on Geoapify MyProjects):

const ipAddress = (req) =>
    (typeof req.headers['x-forwarded-for'] === 'string'
        && req.headers['x-forwarded-for'].split(',').shift())
    || req.connection?.remoteAddress
    || req.socket?.remoteAddress
    || req.connection?.socket?.remoteAddress;

const fetch = require('node-fetch');

fetch(`https://api.geoapify.com/v1/ipinfo?&ip=${ipAddress}&apiKey=YOUR_API_KEY`)
    .then(res => res.json())
    .then(res => console.log(res))
Pros
  • City-level accuracy - the result accuracy depends on the provider of a visitor. The Geoapify IP Geolocation API returns results with city-level accuracy for most of the IP addresses.
  • Easy to use - the API call works via HTTP Get requests, it's cross-platform, can be used with any programming language
Cons
Best application areas
  • Country info - setup page view according to country details;
  • Geotargeting - setup geotargeting corresponding the location area;

Option 2. IP Geolocation headers

Some CDNs and hosting providers offer basic IP Geolocation for customers. Usually, it doesn't cost you extra and can be switched on/of on the CDN control panel. The country name or code is added to the request header and can be easily extracted.

For example, you can get a country code sent by Cloudflare:

const country_code = headers['cf-ipcountry'];
Pros
  • Easy to use - provided with every request within the header
  • No extra costs - usually no extra costs
Cons
  • Should be supported by CND - you need to be a client of a CND that have this feature
  • Country-level accuracy
  • Country code only - no additional information is provided
Best application areas
  • Country info - setup page view according to country details;
  • Geotargeting - setup geotargeting on country level;

Option 3. Accept-Language header

As most the browsers send "Accept-Language" header this can be used to make a guess about visitor's location. This HTTP header advertises the languages the client can understand. It may contain multiple languages with a "weight" value for each language. For example, the header below means: "I would prefer Danish, then British English or any type of English":

Accept-Language: da, en-gb;q=0.8, en;q=0.7

There are several libraries that can be used to parse the "Accept-Language" value. For example, accept-language-parser:

const parser = require('accept-language-parser');

const languages = parser.parse('en-GB,en;q=0.8');

console.log(languages);
Pros
  • Easy to get - provided as a request header
Cons
  • Need to be parsed
  • Very rough - it's very rough way to detect a location, while it could happen that a user uses a certain language but located in different country;
  • Can be undefined - it can happen that the header is missing / not sent by the browser;
Best application areas
  • Page internationalization - return a page content on the user preferred language;
  • Geotargeting - setup roughly geotargeting;

Which method to choose?

We've provided pros and cons for the ways to get the user's location together with recommended application area for every case. We would recommend you choose the method that fits the best your application area. You can think about a combination of the methods for fallbacks and better results.

Try Geoapify IP Geolocation

We offer up to 3000 API calls/day for Free!