Guides
Last updated
July 25, 2023

How to geolocate an IP address in JavaScript

Emma Jagger
Emma Jagger

Table of Contents:

Get your free
IP Geolocation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

You would have definitely noticed how e-commerce platforms and many other websites provide filtered and targeted information to their visitors based on their location. Applications of such customization mechanism are, for example, displaying product prices in the local currency or offering directions to the most convenient physical store.This blog post will guide you to efficiently implement Geolocation from your visitors’ IP address using JavaScript.

This blog post will guide you to efficiently implement Geolocation from your visitors’ IP address using JavaScript.

Geo-locating a visitor using JavaScript’s Geolocation library

To get details about the geographical position of a client, you have to use Geolocation libraries of JavaScript.

Geolocation libraries may or may not be available on the client’s web browser. The geolocation method of the navigator object returns a boolean indicating whether the browser supports or not geolocation. A simple test is enough:

CODE TO BE DISPLAYED ON PAGE GOES HERE

if ( navigator.geolocation ) {
// geolocation is supported
} else {
// geolocation is not supported
}

To obtain the user's current location, you can call the navigator.geolocation.getCurrentPosition() method, which takes from one to three parameters:

  • a callback that is executed when the geolocation succeeded
  • a callback that is executed in case of error
  • a PositionOptions object which has three optional properties: enableHighAccuracy, timeout, and maximumAge


navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
{
enableHighAccuracy : true,
timeout : 2000,
maximumAge : 10000
}
);

Here is the explanation of the properties for the third parameter:

  • enableHighAccuracy is a precision indicator. If set to true, the geolocation method will be the most accurate, but it will be slower.
  • timeout is the time in milliseconds after which the position search is stopped, and the error callback function is called.
  • maximumAge is related to cache's use, and is expressing the time in milliseconds below which, if a position search has already been done, a new position search is not repeated.

When geolocation succeeds, the first callback is called. This function takes as a parameter a GeolocationPosition object that encapsulates the geolocation information:

  • position.coords.altitude returns the altitude
  • position.coords.longitude returns the longitude

Here is a full implementation:



var showLocation = function(position) {
console.log('Longitude ' + position.coords.longitude);
console.log('Latitude ' + position.coords.latitude);
}

if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
}


Enter an IP address to start
Need inspiration? Try
73.162.0.1
LOCATE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Checking
5
Results for
ip address
Country:
TEST
Region:
TEST
City:
TEST
Coordinates:
TEST
Zip code:
TEST
Connection:
TEST
Get free credits, more data, and faster results

The disadvantages of using JavaScript's Geolocation library

For obvious reasons of confidentiality, the browser will not communicate geographical coordinates to your scripts without the user's explicit consent. A call to getCurrentPosition() will necessarily provoke a warning message for the user. This can be seen as an annoyance by the user and prevent you from getting the data you need.

Since 2016-2017 most web browsers require to use the HTTPS protocol to access geolocation, which won't be available if you do your tests locally and for classic HTTP websites.

Geolocation may not be available on every web browser.

By default, getCurrentPosition() tries to respond as quickly as possible even if the result is not very accurate. Depending on the level of detail you expect, this may be an issue.

Geo-locating a visitor using Abstract API

Abstract provides a convenient way to obtain location details of an IP address through the IP Geolocation API. Calling Abstract API can be done from any web browser, without annoying the user with a warning message, and with a high accuracy level.

Similar to most API resource providers, you will first need to get an API key. At Abstract, this process is extremely simplified, as you only need to create an account (no credit card needed), then your API key is automatically generated. The key is included in the code snippets within the documentation pages, so using it is as simple as copy-paste.

Here is how to call IP Geolocation API from JavaScript:

var api_key = "abc123"; // Api key obtained from your account page var url = `https://ipgeolocation.abstractapi.com/v1/?api_key=${api_key}`; function httpGetAsync(url, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(xmlHttp.responseText); } xmlHttp.open("GET", url, true); // true for asynchronous xmlHttp.send(null); } function showLocation(data) { console.log(data); } httpGetAsync(url, showLocation)

Here is an example of the output for an IP address located in France:

{ "ip": "92.184.105.98", "city": "Caen", "city_geoname_id": 3029241, "region": "Normandie", "region_iso_code": "FR-NOR", "region_geoname_id": 11071621, "postal_code": "14949", "country": "France", "country_code": "FR", "country_geoname_id": 3017382, "country_is_eu": true, "continent": "Europe", "continent_code": "EU", "continent_geoname_id": 6255148, "longitude": 49.185850, "latitude": -0.359120, "security": { "is_vpn": false }, "timezone": { "name": "Central European Time", "abbreviation": "CET", "gmt_offset": "+1", "current_time": "2020-03-29T07:35:08-07:00", "is_dst": true }, "flag": { "emoji": "🇫🇷", "unicode": "U+1F1EB U+1F1F7", "svg": "https://static.abstractapi.com/country-flags/fr_flag.svg", "png": "https://static.abstractapi.com/country-flags/fr_flag.png" }, "connection": { "autonomous_system_number": "AS3215", "autonomous_system_organization": "France Telecom - Orange, FR", "connection_type": "wireless", "isp_name": "Orange S.A.", "organization_name": "Internet OM" } }

Frequently Asked Questions

What is IP geolocation in JavaScript?

IP geolocation in JavaScript is the process of determining a visitor's physical location (such as city, region, country, and coordinates) based on their IP address. You can do this either through the browser's built-in Geolocation API or by calling a third-party IP geolocation API like Abstract's.

What is the difference between the browser Geolocation API and an IP geolocation API?

The browser's navigator.geolocation API asks the user for explicit permission before returning location data and only works over HTTPS. An IP geolocation API runs server-side, requires no user consent prompt, and returns additional data like ISP, timezone, and VPN detection, making it more practical for most production use cases.

How do I use navigator.geolocation to get a user's location in JavaScript?

Call navigator.geolocation.getCurrentPosition(callback) after checking that navigator.geolocation exists. The callback receives a position object with latitude, longitude, and altitude. Keep in mind that the browser will display a permission prompt, and the API is unavailable over plain HTTP; your page must be served over HTTPS.

How do I call Abstract's IP Geolocation API from JavaScript?

Make an HTTP request to Abstract's API endpoint with your API key as a query parameter. You can use XMLHttpRequest or the Fetch API to send the request asynchronously and handle the JSON response in a callback or promise. Abstract's API returns fields including city, region, country, coordinates, ISP, and timezone in a single call.

Why would I use an IP geolocation API instead of the browser's built-in geolocation?

An IP geolocation API avoids the user-facing consent dialog that the browser API requires, which can reduce friction and drop-off. It also works without HTTPS restrictions during development and provides richer data (such as ISP, VPN detection, and timezone) that navigator.geolocation does not expose.

What are common use cases for IP geolocation in JavaScript apps?

Common use cases include displaying local currency, showing region-specific content or store directions, restricting access based on country, and pre-filling shipping or language preferences. Because the lookup happens without requiring any action from the visitor, it integrates smoothly into page-load logic or API middleware.

Emma Jagger
Emma Jagger

Emma Jagger is an experienced engineer and Google alumna with a degree from Carnegie Mellon University. She specializes in email validation, IP geolocation, and API integration, focusing on creating practical and scalable solutions through her technical writing.

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Guides
Last updated
July 25, 2023

How to geolocate an IP address in JavaScript

Emma Jagger
Emma Jagger

Table of Contents:

Get your free
IP Geolocation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

You would have definitely noticed how e-commerce platforms and many other websites provide filtered and targeted information to their visitors based on their location. Applications of such customization mechanism are, for example, displaying product prices in the local currency or offering directions to the most convenient physical store.This blog post will guide you to efficiently implement Geolocation from your visitors’ IP address using JavaScript.

This blog post will guide you to efficiently implement Geolocation from your visitors’ IP address using JavaScript.

Geo-locating a visitor using JavaScript’s Geolocation library

To get details about the geographical position of a client, you have to use Geolocation libraries of JavaScript.

Geolocation libraries may or may not be available on the client’s web browser. The geolocation method of the navigator object returns a boolean indicating whether the browser supports or not geolocation. A simple test is enough:

CODE TO BE DISPLAYED ON PAGE GOES HERE

if ( navigator.geolocation ) {
// geolocation is supported
} else {
// geolocation is not supported
}

To obtain the user's current location, you can call the navigator.geolocation.getCurrentPosition() method, which takes from one to three parameters:

  • a callback that is executed when the geolocation succeeded
  • a callback that is executed in case of error
  • a PositionOptions object which has three optional properties: enableHighAccuracy, timeout, and maximumAge


navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
{
enableHighAccuracy : true,
timeout : 2000,
maximumAge : 10000
}
);

Here is the explanation of the properties for the third parameter:

  • enableHighAccuracy is a precision indicator. If set to true, the geolocation method will be the most accurate, but it will be slower.
  • timeout is the time in milliseconds after which the position search is stopped, and the error callback function is called.
  • maximumAge is related to cache's use, and is expressing the time in milliseconds below which, if a position search has already been done, a new position search is not repeated.

When geolocation succeeds, the first callback is called. This function takes as a parameter a GeolocationPosition object that encapsulates the geolocation information:

  • position.coords.altitude returns the altitude
  • position.coords.longitude returns the longitude

Here is a full implementation:



var showLocation = function(position) {
console.log('Longitude ' + position.coords.longitude);
console.log('Latitude ' + position.coords.latitude);
}

if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
}


Enter an IP address to start
Need inspiration? Try
73.162.0.1
LOCATE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Checking
5
Results for
ip address
Country:
TEST
Region:
TEST
City:
TEST
Coordinates:
TEST
Zip code:
TEST
Connection:
TEST
Get free credits, more data, and faster results

The disadvantages of using JavaScript's Geolocation library

For obvious reasons of confidentiality, the browser will not communicate geographical coordinates to your scripts without the user's explicit consent. A call to getCurrentPosition() will necessarily provoke a warning message for the user. This can be seen as an annoyance by the user and prevent you from getting the data you need.

Since 2016-2017 most web browsers require to use the HTTPS protocol to access geolocation, which won't be available if you do your tests locally and for classic HTTP websites.

Geolocation may not be available on every web browser.

By default, getCurrentPosition() tries to respond as quickly as possible even if the result is not very accurate. Depending on the level of detail you expect, this may be an issue.

Geo-locating a visitor using Abstract API

Abstract provides a convenient way to obtain location details of an IP address through the IP Geolocation API. Calling Abstract API can be done from any web browser, without annoying the user with a warning message, and with a high accuracy level.

Similar to most API resource providers, you will first need to get an API key. At Abstract, this process is extremely simplified, as you only need to create an account (no credit card needed), then your API key is automatically generated. The key is included in the code snippets within the documentation pages, so using it is as simple as copy-paste.

Here is how to call IP Geolocation API from JavaScript:

var api_key = "abc123"; // Api key obtained from your account page var url = `https://ipgeolocation.abstractapi.com/v1/?api_key=${api_key}`; function httpGetAsync(url, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(xmlHttp.responseText); } xmlHttp.open("GET", url, true); // true for asynchronous xmlHttp.send(null); } function showLocation(data) { console.log(data); } httpGetAsync(url, showLocation)

Here is an example of the output for an IP address located in France:

{ "ip": "92.184.105.98", "city": "Caen", "city_geoname_id": 3029241, "region": "Normandie", "region_iso_code": "FR-NOR", "region_geoname_id": 11071621, "postal_code": "14949", "country": "France", "country_code": "FR", "country_geoname_id": 3017382, "country_is_eu": true, "continent": "Europe", "continent_code": "EU", "continent_geoname_id": 6255148, "longitude": 49.185850, "latitude": -0.359120, "security": { "is_vpn": false }, "timezone": { "name": "Central European Time", "abbreviation": "CET", "gmt_offset": "+1", "current_time": "2020-03-29T07:35:08-07:00", "is_dst": true }, "flag": { "emoji": "🇫🇷", "unicode": "U+1F1EB U+1F1F7", "svg": "https://static.abstractapi.com/country-flags/fr_flag.svg", "png": "https://static.abstractapi.com/country-flags/fr_flag.png" }, "connection": { "autonomous_system_number": "AS3215", "autonomous_system_organization": "France Telecom - Orange, FR", "connection_type": "wireless", "isp_name": "Orange S.A.", "organization_name": "Internet OM" } }

Frequently Asked Questions

What is IP geolocation in JavaScript?

IP geolocation in JavaScript is the process of determining a visitor's physical location (such as city, region, country, and coordinates) based on their IP address. You can do this either through the browser's built-in Geolocation API or by calling a third-party IP geolocation API like Abstract's.

What is the difference between the browser Geolocation API and an IP geolocation API?

The browser's navigator.geolocation API asks the user for explicit permission before returning location data and only works over HTTPS. An IP geolocation API runs server-side, requires no user consent prompt, and returns additional data like ISP, timezone, and VPN detection, making it more practical for most production use cases.

How do I use navigator.geolocation to get a user's location in JavaScript?

Call navigator.geolocation.getCurrentPosition(callback) after checking that navigator.geolocation exists. The callback receives a position object with latitude, longitude, and altitude. Keep in mind that the browser will display a permission prompt, and the API is unavailable over plain HTTP; your page must be served over HTTPS.

How do I call Abstract's IP Geolocation API from JavaScript?

Make an HTTP request to Abstract's API endpoint with your API key as a query parameter. You can use XMLHttpRequest or the Fetch API to send the request asynchronously and handle the JSON response in a callback or promise. Abstract's API returns fields including city, region, country, coordinates, ISP, and timezone in a single call.

Why would I use an IP geolocation API instead of the browser's built-in geolocation?

An IP geolocation API avoids the user-facing consent dialog that the browser API requires, which can reduce friction and drop-off. It also works without HTTPS restrictions during development and provides richer data (such as ISP, VPN detection, and timezone) that navigator.geolocation does not expose.

What are common use cases for IP geolocation in JavaScript apps?

Common use cases include displaying local currency, showing region-specific content or store directions, restricting access based on country, and pre-filling shipping or language preferences. Because the lookup happens without requiring any action from the visitor, it integrates smoothly into page-load logic or API middleware.

Emma Jagger
Emma Jagger

Emma Jagger is an experienced engineer and Google alumna with a degree from Carnegie Mellon University. She specializes in email validation, IP geolocation, and API integration, focusing on creating practical and scalable solutions through her technical writing.

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required