Understanding the Geolocation API

The Geolocation API allows a webpage to request geographic location information from the user's browser.

JavaScript can use the API to request the device's current position or monitor location changes. Because geographic location can reveal sensitive information, browsers require permission before making location data available to a webpage.

Accessing Geolocation

The Geolocation API is available through the navigator.geolocation object.

navigator.geolocation

Before using the API, JavaScript can check whether the browser exposes the geolocation property.

if ("geolocation" in navigator) {
  // Geolocation is available.
} else {
  // Geolocation is not available.
}

A feature check prevents the script from assuming that the API is available in every browsing environment.

User Permission

Geographic location is sensitive information. A webpage cannot simply retrieve the user's location whenever it wants to.

When location access is requested, the browser controls the permission process. The user can allow or deny access, and previously established browser or site permissions can also affect the result.

Location should therefore be requested when the user understands why it is needed, such as after selecting a clearly labeled feature that depends on their location.

Get the Current Position

The getCurrentPosition() method requests the user's current geographic position.

navigator.geolocation.getCurrentPosition(success);

The function supplied to the method is called when the location request succeeds.

function success(position) {
  console.log(position.coords.latitude);
  console.log(position.coords.longitude);
}

The returned position contains coordinate information supplied by the browser.

The Position Object

A successful location request provides a GeolocationPosition object to the success callback.

Its coords property contains a GeolocationCoordinates object with the geographic information associated with the position.

function success(position) {
  const coordinates = position.coords;

  console.log(coordinates.latitude);
  console.log(coordinates.longitude);
  console.log(coordinates.accuracy);
}

The position also includes a timestamp indicating when the location represented by the position was acquired.

Geolocation Coordinates

The coordinates object can contain several pieces of location-related information. Some values may be unavailable depending on the device and location source.

Property Description
latitude Latitude in decimal degrees.
longitude Longitude in decimal degrees.
accuracy Estimated accuracy of the latitude and longitude in meters.
altitude Height relative to the reference surface in meters, or null when unavailable.
altitudeAccuracy Estimated altitude accuracy in meters, or null when unavailable.
heading Direction of travel in degrees, or null when unavailable.
speed Device speed in meters per second, or null when unavailable.

Location Accuracy

A location returned by the Geolocation API should not be assumed to identify an exact physical point. The accuracy property provides an estimate of the accuracy of the latitude and longitude coordinates in meters.

const accuracy = position.coords.accuracy;

The browser and device determine how location information is obtained. Available sources can vary and may include GPS, Wi-Fi, cellular networks, and other location services.

The accuracy available on one device or in one environment can therefore be very different from another.

Handling Geolocation Errors

A location request can fail, so getCurrentPosition() can also receive an error callback.

navigator.geolocation.getCurrentPosition(success, error);

function error(error) {
  console.log(error.message);
}

A GeolocationPositionError identifies the general reason the request failed.

Error Meaning
PERMISSION_DENIED Permission to access location was denied.
POSITION_UNAVAILABLE The device's position could not be determined.
TIMEOUT The position could not be obtained within the allowed time.

Applications should handle these conditions rather than assuming every location request will succeed.

Position Options

An optional settings object can be supplied to getCurrentPosition() or watchPosition() to control aspects of the location request.

const options = {
  enableHighAccuracy: true,
  timeout: 10000,
  maximumAge: 0
};

navigator.geolocation.getCurrentPosition(success, error, options);
Option Purpose
enableHighAccuracy Requests the best available accuracy when true, which can require additional time or device resources.
timeout Sets the maximum time in milliseconds allowed for obtaining a position.
maximumAge Controls how old a cached position may be and still be accepted.

High accuracy should be requested only when the feature actually benefits from it rather than automatically enabling it for every location request.

Watch Position Changes

The watchPosition() method can request updated positions as the device's location changes.

const watchId = navigator.geolocation.watchPosition(success, error);

The success callback can run multiple times as new position information becomes available.

The method returns an identifier that can later be used to stop the location watch.

Stop Watching Position

When continuous location updates are no longer needed, use clearWatch() with the identifier returned by watchPosition().

navigator.geolocation.clearWatch(watchId);

Stopping unnecessary location monitoring avoids continuing an operation after the feature that required it has finished.

Privacy and Security

The Geolocation API is a powerful feature because location information can reveal sensitive details about a user. Browsers therefore restrict access and require user permission.

Geolocation is generally available only in secure contexts such as webpages delivered through HTTPS. Local development environments can receive special treatment from browsers, but production websites should use HTTPS.

Request only the location information needed for a useful feature, clearly explain why location is being requested, and do not assume that users will grant permission.

If location information is stored, transmitted, or associated with other user information, the website should also consider the privacy and security responsibilities created by that use.

Complete Geolocation Example

The following example requests the user's current location after the button is selected and displays the latitude, longitude, and estimated accuracy.

<button type="button" id="location-button">Get My Location</button>
<p id="result">Your location has not been requested.</p>

<script>
const button = document.querySelector("#location-button");
const result = document.querySelector("#result");

button.addEventListener("click", () => {
  if (!("geolocation" in navigator)) {
    result.textContent = "Geolocation is not available.";
    return;
  }

  result.textContent = "Requesting your location...";

  navigator.geolocation.getCurrentPosition(
    (position) => {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;
      const accuracy = position.coords.accuracy;

      result.textContent =
        "Latitude: " + latitude +
        ", Longitude: " + longitude +
        ", Accuracy: " + accuracy + " meters";
    },
    (error) => {
      result.textContent = "Location could not be retrieved: " + error.message;
    }
  );
});
</script>

The location request begins only after the user selects the button. If permission is granted and a position is available, the coordinates are displayed; otherwise, the page reports that the request could not be completed.

Play in Editor

Common Geolocation Mistakes

Mistake Better Approach
Requesting location immediately when the page loads Request it when the user chooses a feature that clearly needs location.
Assuming permission will be granted Handle denied permission and other errors gracefully.
Assuming coordinates are perfectly accurate Consider the value provided by accuracy.
Ignoring API availability Check for geolocation support before using it.
Always requesting high accuracy Use high accuracy only when the feature benefits from it.
Leaving a position watch running unnecessarily Call clearWatch() when continuous updates are no longer needed.
Ignoring the sensitivity of location data Collect and use location information only for a clear purpose.

Best Practices

  • Request location only when it provides a clear benefit to the user.
  • Explain why location access is needed before requesting it.
  • Request location in response to an understandable user action when practical.
  • Check whether the Geolocation API is available before using it.
  • Handle permission denial, unavailable positions, and timeouts.
  • Do not assume that returned coordinates are perfectly accurate.
  • Request high accuracy only when it is necessary for the feature.
  • Stop location watches when continuous updates are no longer required.
  • Use HTTPS for production websites using geolocation.
  • Treat geographic location as sensitive user information.
  • Provide an alternative when a feature can still function without the user's location.

Summary

The Geolocation API provides controlled access to geographic position information through navigator.geolocation. The getCurrentPosition() method requests a position once, while watchPosition() can receive updated positions until the watch is stopped with clearWatch().

Location access requires careful handling of permission, errors, accuracy, privacy, and browser security requirements. Next, we will look at the Web Storage API and how webpages can store data in the user's browser.