Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 122 Β· Web APIs

Geolocation

Get the user's location with the Geolocation API. Learn getCurrentPosition, watchPosition, the options object, every error code, permissions and HTTPS.

The Geolocation API lets a page ask the browser where the device is. The answer can come from GPS, nearby Wi-Fi networks, mobile cell towers or the IP address, and the browser decides which. Your code just receives a latitude, a longitude and an estimate of how accurate they are.

Location is personal data, so this API is a perfect example of the rules from Introduction to Web APIs: it works only on secure pages, it always asks the user first, and it can fail in several ways. This lesson shows the whole API and, just as importantly, how to handle every failure gracefully.

Requirements

Before any code runs, three conditions must be met:

  1. A secure context. The page must be served over HTTPS (or from localhost during development).
  2. The user's permission. The first call triggers a prompt such as "example.com wants to know your location". The user can allow, block or dismiss it.
  3. Policy allows it. Inside an iframe, the parent page must grant access with allow="geolocation". The editors on this site do not, so every call made in them fails, which makes them a good place to practice error handling.

Always feature-detect first:

JavaScript
if (!('geolocation' in navigator)) {
  showMessage('Your browser cannot share its location.');
}

Getting the current position

navigator.geolocation.getCurrentPosition() asks for the location once. It uses callbacks rather than a promise. You pass in a success function, an optional error function and an optional options object:

JavaScript
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);

The success callback receives a GeolocationPosition object. Its coords property holds the numbers you care about:

Property Meaning
coords.latitude Degrees north (positive) or south (negative) of the equator
coords.longitude Degrees east (positive) or west (negative) of Greenwich
coords.accuracy Radius of uncertainty in meters (smaller is better)
coords.altitude Meters above sea level, or null if unknown
coords.altitudeAccuracy Accuracy of the altitude in meters, or null
coords.heading Direction of travel in degrees from true north, or null
coords.speed Speed in meters per second, or null
timestamp When the position was measured (milliseconds since 1970)

A typical call to copy into your own page looks like this:

HTML
<button id="locate">Show my location</button>
<p id="where"></p>

<script>
  document.getElementById('locate').addEventListener('click', () => {
    const where = document.getElementById('where');
    where.textContent = 'Locating…';

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        where.textContent =
          `You are at ${latitude.toFixed(4)}, ${longitude.toFixed(4)} ` +
          `(within about ${Math.round(accuracy)} m).`;
      },
      (error) => {
        where.textContent = 'Could not get your location: ' + error.message;
      }
    );
  });
</script>

The request starts from a button click. That is deliberate: as you learned in the previous lesson, people accept prompts that follow their own actions, and browsers may block prompts that appear on page load.

Handling errors

The error callback receives a GeolocationPositionError with two properties: a numeric code and a human-readable message. The code is one of three constants:

Code Constant What happened
1 PERMISSION_DENIED The user (or a policy) refused access
2 POSITION_UNAVAILABLE The device could not work out a position, for example with no signal
3 TIMEOUT No position arrived within the timeout you set

The message text differs between browsers and is meant for developers, so show your own wording to users and switch on code. Run the example below. In this sandbox the browser refuses straight away, so you will see the error branch in action.

The error path

The console line under the preview shows the raw code and the browser's own message. Save the same code as an .html file, open it from localhost, and you will get a real prompt and, if you allow it, your real coordinates.

Always offer a fallback. If the location is denied or unavailable, let people type a city or postal code. A store finder that only works with GPS is a store finder that fails for many visitors.

Options

The third argument is an options object with three settings:

Option Default Effect
enableHighAccuracy false Ask for the most precise position (often GPS). Slower and uses more battery.
timeout Infinity Maximum time in milliseconds to wait for a position before calling the error callback with TIMEOUT.
maximumAge 0 Accept a cached position up to this many milliseconds old. 0 means "always measure fresh".
JavaScript
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
  enableHighAccuracy: true, // turn-by-turn navigation needs precision
  timeout: 15000,           // give up after 15 seconds
  maximumAge: 60000,        // a fix from the last minute is fine
});

Pick options to match the job. A weather page only needs the right city, so the defaults (or a generous maximumAge) are perfect. A running app needs enableHighAccuracy. Without a timeout, a device with no signal could keep your interface waiting forever.

Watching a moving position

watchPosition() takes the same three arguments but keeps calling your success callback every time the position changes. It returns a numeric watch ID; pass that ID to clearWatch() to stop:

JavaScript
const watchId = navigator.geolocation.watchPosition(onMove, onError, {
  enableHighAccuracy: true,
});

// Later, when the user taps "Stop tracking":
navigator.geolocation.clearWatch(watchId);

Always stop watching when you no longer need updates. A forgotten watch keeps the GPS awake and drains the battery.

Because real tracking cannot run in this sandbox, the next example uses a small mock object with exactly the same method names and callback shapes as navigator.geolocation. It "walks" along a short route and calculates the distance covered with the haversine formula, which finds the distance between two points on a sphere. Swap fakeGeo for navigator.geolocation in a real page and the rest of the code works unchanged.

Tracking a walk (simulated)

Accuracy jitters. Real positions wobble by a few meters even when you stand still. Apps that add up distance usually ignore readings whose accuracy is poor and skip tiny moves smaller than the accuracy radius.

Checking the permission first

You can check whether a prompt would appear before you ask, using the Permissions API from the previous lesson:

JavaScript
const status = await navigator.permissions.query({ name: 'geolocation' });

if (status.state === 'denied') {
  locateButton.hidden = true;     // don't offer something that cannot work
  cityInput.hidden = false;       // offer the manual fallback instead
}

This avoids showing a "Locate me" button that is guaranteed to fail.

Privacy and good manners

  • Ask only when needed, and explain why on the button or next to it ("Use my location to show the nearest branch").
  • Use the lowest precision that works. Rounding to two decimal places (about 1 km) is plenty for a weather forecast.
  • Don't store or send coordinates unless your feature needs it, and say so in your privacy policy if you do.
  • Remember that location may be wrong. IP-based positions can be off by a whole city. Show the accuracy, or let people correct it.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Your page calls getCurrentPosition() over plain HTTP on a public domain. What happens?

    Geolocation is only available in secure contexts (HTTPS or localhost). On plain HTTP the request is refused.
  2. 2. The error callback receives an error with code equal to 3. What happened?

    Code 3 is TIMEOUT. Code 1 is PERMISSION_DENIED and code 2 is POSITION_UNAVAILABLE.
  3. 3. Which option lets the browser reuse a position measured in the last five minutes?

    maximumAge is the oldest cached position, in milliseconds, that you will accept. timeout limits how long to wait for a new one.
  4. 4. How do you stop the updates started by watchPosition()?

    watchPosition() returns a watch ID. Passing it to navigator.geolocation.clearWatch() stops the updates and lets the device save power.

Summary

  • navigator.geolocation works only in secure contexts, after the user grants permission, and in iframes only with allow="geolocation".
  • getCurrentPosition(success, error, options) asks once; position.coords holds latitude, longitude, accuracy and more.
  • Handle the three error codes: PERMISSION_DENIED (1), POSITION_UNAVAILABLE (2) and TIMEOUT (3), and always offer a manual fallback.
  • Tune requests with enableHighAccuracy, timeout and maximumAge.
  • watchPosition() delivers continuous updates; stop it with clearWatch(id).

Next lesson: Drag and Drop, where you let people move elements and files around the page with the mouse.