TExcelTAD
Home › HTML › HTML Geolocation

HTML Geolocation

The Geolocation API lets a web page ask for the user's physical location — latitude and longitude — so it can show nearby shops, the local weather or a "you are here" pin on a map. Location is personal data, so the browser always asks the user for permission first, and the user can say no.

How it works

The API lives on navigator.geolocation. The main method is getCurrentPosition, which takes up to three arguments:

js
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
  1. onSuccess(position) — called with a position object if the location is found.
  2. onError(error) — called if the user refuses, the location is unavailable, or it takes too long.
  3. options — optional settings such as a timeout.

The call is asynchronous: your page keeps running while the browser asks for permission and finds the location.

Requirements

  • The page must be served over HTTPS (or localhost). On plain HTTP the API is blocked.
  • The user must grant permission.
  • Embedded frames need explicit permission from the parent page (allow="geolocation" on the iframe).

Note: ExcelTAD's playgrounds run in a sandboxed iframe without that permission, so in the examples below you will most likely see the error path. That is deliberate: a good location feature must always work when permission is denied.

A robust example

This example checks that the API exists, handles every error code, and offers a manual alternative.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <button id="find">Where am I?</button>
  <p id="result">Click the button.</p>
  <script>
    const result = document.getElementById('result');

    function success(pos) {
      const lat = pos.coords.latitude.toFixed(4);
      const lon = pos.coords.longitude.toFixed(4);
      result.textContent = 'You are at ' + lat + ', ' + lon +
        ' (accuracy about ' + Math.round(pos.coords.accuracy) + ' m).';
    }

    function failure(err) {
      const reasons = {
        1: 'Permission denied — that is fine, you can type your city instead.',
        2: 'Position unavailable — the device could not work out where it is.',
        3: 'Timed out — finding the location took too long.'
      };
      result.textContent = reasons[err.code] || ('Unknown error: ' + err.message);
    }

    document.getElementById('find').onclick = function () {
      if (!('geolocation' in navigator)) {
        result.textContent = 'Geolocation is not supported by this browser.';
        return;
      }
      result.textContent = 'Locating…';
      try {
        navigator.geolocation.getCurrentPosition(success, failure, { timeout: 8000 });
      } catch (e) {
        result.textContent = 'Geolocation is blocked here: ' + e.message;
      }
    };
  </script>
</body>
</html>

The position object

Property Meaning
coords.latitude Degrees north (+) or south (−) of the equator
coords.longitude Degrees east (+) or west (−) of Greenwich
coords.accuracy Accuracy radius in metres
coords.altitude Height in metres (may be null)
coords.heading Direction of travel in degrees (may be null)
coords.speed Speed in m/s (may be null)
timestamp When the position was measured

Error codes

error.code Constant When it happens
1 PERMISSION_DENIED The user (or the page's settings) refused
2 POSITION_UNAVAILABLE No GPS, Wi-Fi or network data available
3 TIMEOUT The timeout option expired

Options

Option Meaning
enableHighAccuracy true asks for GPS-level precision (slower, uses more battery)
timeout Milliseconds to wait before giving up
maximumAge Accept a cached position this many milliseconds old

Tracking movement

watchPosition works like getCurrentPosition but calls your success function every time the position changes, which is useful for navigation or fitness apps. It returns an id you pass to clearWatch to stop.

js
const watchId = navigator.geolocation.watchPosition(update, failure);
// later…
navigator.geolocation.clearWatch(watchId);

Always provide a fallback

Many people decline location requests, so design for that. A good pattern is: ask only when the user clicks a button (never on page load), and offer a manual input as well.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <label>Your city: <input id="city" placeholder="e.g. Hanoi"></label>
  <button id="useCity">Show weather</button>
  <button id="useGps">Use my location</button>
  <p id="out"></p>
  <script>
    const out = document.getElementById('out');
    document.getElementById('useCity').onclick = function () {
      const city = document.getElementById('city').value.trim();
      out.textContent = city ? 'Showing weather for ' + city + '.' : 'Please type a city first.';
    };
    document.getElementById('useGps').onclick = function () {
      if (!navigator.geolocation) { out.textContent = 'Location not supported — please type your city.'; return; }
      out.textContent = 'Asking for permission…';
      try {
        navigator.geolocation.getCurrentPosition(
          function (p) { out.textContent = 'Showing weather near ' + p.coords.latitude.toFixed(2) + ', ' + p.coords.longitude.toFixed(2) + '.'; },
          function () { out.textContent = 'Location unavailable — please type your city instead.'; document.getElementById('city').focus(); },
          { timeout: 8000 }
        );
      } catch (e) {
        out.textContent = 'Location blocked — please type your city instead.';
      }
    };
  </script>
</body>
</html>

Tip: Explain why you want the location before the browser prompt appears. Users are much more likely to agree when they understand the benefit.

Test yourself

What must happen before a page can read the user's location?

  1. Nothing — it is always available
  2. The user must grant permission (and the page must be on HTTPS)
  3. The page must include a <map> element
  4. The user must install a plug-in

Which error.code means the user refused to share their location?

  1. 0
  2. 1
  3. 2
  4. 3

Which method keeps reporting the position as the user moves?

  1. getCurrentPosition
  2. watchPosition
  3. trackPosition
  4. setInterval