How to Get User Location with JavaScript: A Comprehensive Guide

JavaScript developers can leverage user location data to create dynamic web apps that adjust map views, show nearby points of interest, and offer personalized recommendations
JavaScript developers can leverage user location data to create dynamic web apps that adjust map views, show nearby points of interest, and offer personalized recommendations

Getting user location is essential for many web applications, as it enables personalized experiences and targeted marketing campaigns. For example, an e-commerce website can display products relevant to the user's location or provide shipping estimates based on their address. Similarly, a news website can display local news stories based on the user's location. Obtaining accurate user location data can help businesses improve user engagement, increase conversions, and drive revenue.

With JavaScript, developers can use the built-in navigator.geolocation method to retrieve user location data. However, this method has limitations, and there are other ways to get user locations that offer additional features and benefits.

In this article, we'll explore various techniques to get user location with JavaScript, including navigator.geolocation, IP geolocation, and other methods. By the end, you'll have a solid understanding of the options available and which is best for your needs.

1. Using HTML Geolocation API

"navigator.geolocation" is the browser's built-in interface to obtain the user's location

One of the most common ways to get a user's location with JavaScript is by using the built-in navigator.geolocation method. This API provides access to the user's current location via their device's GPS or other location sensors. It is supported by most modern web browsers and can be accessed using JavaScript.

It's important to note that user location is sensitive information, so the user must first grant permission for a web application to access it. Most modern web browsers will prompt users to grant or deny location-sharing permissions when a page tries to access navigator.geolocation.

Here's an example code snippet that demonstrates how to get a user position with the navigator.geolocation interface:

// Check if geolocation is supported by the browser
if ("geolocation" in navigator) {
  // Prompt user for permission to access their location
  navigator.geolocation.getCurrentPosition(
    // Success callback function
    (position) => {
      // Get the user's latitude and longitude coordinates
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;

      // Do something with the location data, e.g. display on a map
      console.log(`Latitude: ${lat}, longitude: ${lng}`);
    },
    // Error callback function
    (error) => {
      // Handle errors, e.g. user denied location sharing permissions
      console.error("Error getting user location:", error);
    }
  );
} else {
  // Geolocation is not supported by the browser
  console.error("Geolocation is not supported by this browser.");
}

In this example, the code first checks if navigator.geolocation is supported by the user's browser. If it is, the getCurrentPosition() method is called to obtain the user's current location. The method takes two callback functions as parameters: one for success and one for error handling.

The navigator.geolocation can also be used to follow the user's position in real-time as they move. This is done by calling the watchPosition() method instead of getCurrentPosition(). The watchPosition() method takes the same two callback functions as getCurrentPosition(), but it is called repeatedly every time the user's position changes.

Here's an example code snippet that demonstrates how to use watchPosition() to track the user's position and update a map in real-time:

// Check if geolocation is supported by the browser
if ("geolocation" in navigator) {
  // Prompt user for permission to access their location
  navigator.geolocation.watchPosition(
    // Success callback function
    function(position) {
      // Get the user's latitude and longitude coordinates
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;

      // Update the map with the user's new location
      console.log(`Latitude: ${lat}, longitude: ${lng}`);
    },
    // Error callback function
    function(error) {
      // Handle errors, e.g. user denied location sharing permissions
      console.error("Error getting user location:", error);
    }
  );
} else {
  // Geolocation is not supported by the browser
  console.error("Geolocation is not supported by this browser.");
}

In this example, the code uses watchPosition() to repeatedly update the user's location on a map as they move.

When you use navigator.geolocation to get a user's location with JavaScript, it's important to consider the advantages and disadvantages of this approach:

Pros:
  • Built-in method: navigator.geolocation is built into most modern web browsers, so it doesn't require any external libraries or APIs to use.
  • Accurate location data: navigator.geolocation uses GPS (Global Positioning System) and other location sensors on the user's device to provide accurate location data.
  • Real-time updates: The watchPosition() method can be used to track the user's position in real-time and update the location on a map or other interface as they move.
  • Simple to implement: The API is easy to use and requires only a few lines of JavaScript code to get started.
Cons:
  • Requires user permission: Since location data is sensitive information, users must grant permission for their location to be shared with the website or application.
  • Limited accuracy indoors: In areas with poor GPS or other location sensor reception, the accuracy of navigator.geolocation may be limited, especially indoors.
  • Not supported by all browsers: While navigator.geolocation is supported by most modern browsers, some older browsers or niche browsers may not support it.
  • Potential privacy concerns: Since location data is sensitive information, it can be a privacy concern if it is shared without the user's knowledge or consent.

2. Using IP Geolocation

Get the geographical location of an Internet-connected device by its IP

IP geolocation is another powerful tool for obtaining customer location data, as it allows you to determine the geographical location of an Internet-connected device by its IP address.

There are several third-party services that allow you to obtain customer location data by their IP address. These services maintain extensive databases of IP address locations and provide APIs that allow you to access this data programmatically.

One such service is Geoapify's IP Geolocation API, which provides a simple and reliable way to obtain accurate location data for IP addresses around the world. The following demo returns your location, determined by your IP address:

Using Geoapify's IP Geolocation API is simple and straightforward. You can make an API request using HTTP or HTTPS and receive a JSON response containing information about the user's location, including their country, region, city, and latitude and longitude coordinates. You can then use this information to display the location on a map or provide location-based services. Here is an example of calling IP Geolocation API:

fetch('https://api.geoapify.com/v1/ipinfo?apiKey=YOUR_API_KEY_HERE')
  .then(response => response.json())
  .then(data => {
    // You can now access the location data in the "data" object
    console.log(data);
  })

In this example, you would replace "YOUR_API_KEY_HERE" with your actual API key provided by Geoapify. Once you make the request, you'll receive a JSON response containing the location data for the user's IP address.

It's important to keep in mind that IP geolocation may not always be 100% accurate, as a variety of factors can affect the accuracy of the data, such as network topology, VPNs, and proxies. However, in most cases, IP geolocation can provide a reasonable estimate of the user's location and can be a valuable tool for enhancing the user experience and providing location-based services.

Pros:
  • No user permission required: Unlike navigator.geolocation, IP geolocation does not require the user to grant permission for their location to be shared, which can improve user experience.
  • Wide range of devices: Since IP geolocation is based on the device's IP address, it can be used on a wide range of devices, including those that do not have GPS or other location sensors.
  • Easy to implement: IP geolocation APIs are widely available and easy to integrate into web applications, typically requiring only a few lines of code.
Cons:
  • Less accurate: IP geolocation is generally less accurate than navigator.geolocation, as it only provides location data based on the IP address of the device rather than using GPS or other location sensors.
  • Dependent on IP database quality: The accuracy of IP geolocation is heavily dependent on the quality and currency of the IP address database being used by the API provider.
  • Limited real-time tracking: Unlike navigator.geolocation's watchPosition() method, IP geolocation is typically a one-time lookup and does not provide real-time tracking of the user's location.

3. Best practices

Which option to choose to get a user's location

When it comes to choosing the best way to get a user's location for your application or website, there are several factors to consider:

  • User privacy and location sharing: It's important to remember that location data is sensitive information, and users must grant permission to share their location. Therefore, it's best practice to only ask for a user's location if it's absolutely necessary for your application's functionality and to clarify why you are requesting this information.
  • GPS-level accuracy: If accuracy is a top priority, then navigator.geolocation is the best choice, as it provides GPS-level accuracy. However, it is important to remember that users must grant permission for their location to be shared, and some users may be hesitant to do so due to privacy concerns. Additionally, not all browsers support navigator.geolocation.
  • City-level accuracy: On the other hand, IP geolocation is less accurate than navigator.geolocation, as it only provides city-level accuracy. However, it is widely available and doesn't require user permission, so it can be a good alternative if privacy concerns are a priority.
  • UX practices: In terms of best UX practices, it's generally a good idea to avoid asking users to share their location unless it's necessary for the functionality of the website or application. When asking for permission to access the user's location, it's important to provide clear information on why the location is needed and how it will be used. It's also a good practice to provide an option for users to disable location tracking if they choose to do so.

It's worth noting that when it comes to choosing between navigator.geolocation and IP geolocation, it's not always an either/or situation. In fact, a combination of both approaches can be highly effective for many applications. For example, you could use IP geolocation to get a user's city-level location, which can be helpful for displaying local content or offers. Then, you could offer the user the option to share their precise location by clicking a "locate me" button or another similar option. This approach lets you provide a better user experience while still respecting the user's privacy and preferences.

4. JavaScript Code Sample

Using IP Geolocation and HTML Geolocation together

This code sample demonstrates using Geoapify API and Maplibre GL JS library to display a map and get the user's location in a web application. The code combines IP geolocation to provide a general idea of the user's location and a "locate me" button that calls navigator.geolocation to enable the user to share their precise location. The code also uses Geoapify's Reverse Geocoding API to get the address of the user's precise location.

const map = new maplibregl.Map({
  container: 'map',
  style: `https://maps.geoapify.com/v1/styles/klokantech-basic/style.json?apiKey=${myAPIKey}`,
});

fetch(`https://api.geoapify.com/v1/ipinfo?apiKey=${myAPIKey}`)
  .then(response => response.json())
  .then(positionData => {
     console.log(`Lat: ${positionData.location.latitude}, lon: ${positionData.location.longitude}`);
     
     // Locate the map to the city level
     map.flyTo({center: [positionData.location.longitude, positionData.location.latitude], zoom: 10});
  });

// Create the geolocate control.
const geolocate = new maplibregl.GeolocateControl({
  positionOptions: { enableHighAccuracy: true },
  trackUserLocation: false
});

// Add the control to the map
map.addControl(geolocate, 'bottom-right');

// Listen for the geolocate event
geolocate.on('geolocate', function(positionData) {
  // get address by coordinates with Geoapify Reverse Geocoding API
  console.log(`Lat: ${positionData.coords.latitude}, lon: ${positionData.coords.longitude}`);
  getAddress(positionData.coords.latitude, positionData.coords.longitude).then(address => {
    console.log(address);
  })
});

function getAddress(lat, lon) {
  return fetch(`https://api.geoapify.com/v1/geocode/reverse?lat=${lat}&lon=${lon}&format=json&apiKey=${myAPIKey}`).then(result => result.json()).then(result => {
    if (result && result.results.length) {
      return result.results[0].formatted
    }

    return null
  })
}
  • First, we create a new map object with the MaplibreGL library using Geoapify's vector map tiles.

  • Then we make a request to the Geoapify IP Geolocation API to get the user's location based on their IP address. Once the response is received, the latitude and longitude values of the user's location are used to center the map with the flyTo() method, providing a city-level view of the user's location.

  • We create a geolocate control and add it to the bottom-right of the map. When the user clicks on the geolocate button, the geolocate object calls the navigator.geolocation.getCurrentPosition() and triggers the on('geolocate') callback function.

  • The callback function gets the latitude and longitude values of the user's location from the positionData object and uses the getAddress() function to convert the coordinates to a readable address.

  • The getAddress() function sends a request to the Geoapify Reverse Geocoding API to get the address data for the provided latitude and longitude values. Once the response is received, the function returns the formatted address data.

Overall, this code combines IP geolocation and geolocation-based address lookup functionality using the MaplibreGL and Geoapify APIs, providing a simple and effective way to display user location information on a map-based application.

Here is a working demo of this JavaScript code in JSFiddle.

FAQ

How can I get a user's location with JavaScript?

To get a user's location using JavaScript, you can use the built-in 'navigator.geolocation' object, which provides access to the device's location. Another way is to call IP Geolocation API which returns the user's location with accuracy up to the city level.

What is the difference between navigator.geolocation and IP geolocation?

The main difference between 'navigator.geolocation' and IP geolocation is the way they determine the user's location. The 'navigator.geolocation' relies on the GPS receiver of the device, which provides accurate real-time location data. On the other hand, IP geolocation uses the user's IP address to estimate their location, which is usually accurate only at the city or region level. Additionally, 'navigator.geolocation' requires the user's explicit consent to share their location, while IP geolocation does not.

Can I get a user's precise location without their permission?

No, using a user's location without their permission is not ethical or legal. Location data is considered sensitive information, and users must grant explicit consent to share their location. In addition, unauthorized access to a user's location can violate their privacy and potentially put them in danger.

How accurate is IP geolocation compared to GPS-level accuracy provided by 'navigator.geolocation'?

IP geolocation is less accurate than GPS-level accuracy provided by 'navigator.geolocation'. IP geolocation is typically precise up to the city level, whereas 'navigator.geolocation' can provide location data with sub-meter accuracy. However, it's important to note that the accuracy of 'navigator.geolocation' can be affected by factors such as weather conditions, tall buildings, and other obstructions that can interfere with GPS signals.

World map

Try Geoapify IP Geolocation

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