On this page10 sections
  1. Learning Objectives
  2. 1. Permission First
  3. 2. Getting the Position
  4. 3. What You Get Back
  5. 4. Showing It on a Map
  6. 5. Tracking Movement
  7. Common Beginner Mistakes
  8. Practice Questions
  9. Practice Answers
  10. Key Takeaways

Lecture 043: Geolocation API

Category8: Web APIs
Lecture043 of 048
Estimated video length10 min
TargetHTML5 · any modern browser
LevelBeginner

A Web API is a feature the browser gives JavaScript. The Geolocation API asks "where is this device?" With the visitor's permission, it returns a latitude and longitude, which are used for maps, "stores near me" and weather.


Learning Objectives

  • Explain what a Web API is
  • Get the visitor's position with navigator.geolocation.getCurrentPosition()
  • Handle permission refusals and errors
  • Track movement with watchPosition()

1. Permission First

The browser always asks the visitor before sharing their location, and it only works on secure pages (https://, or a file opened from your own computer). If they say no, your code gets an error, so always handle it.

These examples can't run inside this page's preview box, because previews are sandboxed for safety and location is blocked there. Copy the code into a file such as location.html and open it in your browser.


2. Getting the Position

html
<button type="button" onclick="locate()">Where am I?</button>
<p id="out"></p>

<script>
  function locate() {
    const out = document.getElementById('out');
    if (!('geolocation' in navigator)) {
      out.textContent = 'Geolocation is not supported by this browser.';
      return;
    }
    out.textContent = 'Locating…';
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  }

  function showPosition(position) {
    const { latitude, longitude, accuracy } = position.coords;
    document.getElementById('out').textContent =
      `Latitude ${latitude.toFixed(4)}, longitude ${longitude.toFixed(4)} (within ${Math.round(accuracy)} m)`;
  }

  function showError(error) {
    const messages = {
      1: 'You refused to share your location.',
      2: 'Your position is unavailable.',
      3: 'Finding your position took too long.',
    };
    document.getElementById('out').textContent = messages[error.code] || 'Unknown error.';
  }
</script>

getCurrentPosition takes a success function and an error function. It doesn't return the answer straight away, because finding the position takes time.


3. What You Get Back

PropertyMeaning
coords.latitude / coords.longitudePosition in degrees
coords.accuracyHow accurate, in metres
coords.altitudeHeight above sea level (if available)
coords.speed / coords.headingSpeed and direction (if moving)
timestampWhen the position was measured

4. Showing It on a Map

Open the coordinates in Google Maps:

html
<script>
  function showPosition(position) {
    const { latitude, longitude } = position.coords;
    const url = `https://www.google.com/maps?q=${latitude},${longitude}`;
    document.getElementById('out').innerHTML = `<a href="${url}" target="_blank" rel="noopener">Open my location on a map</a>`;
  }
</script>

5. Tracking Movement

watchPosition calls your function every time the position changes, which is useful for running or delivery apps. Stop it with clearWatch.

html
<script>
  const watchId = navigator.geolocation.watchPosition(showPosition, showError, { enableHighAccuracy: true });
  // later…
  navigator.geolocation.clearWatch(watchId);
</script>

Common Beginner Mistakes

1. Not handling errors. Many visitors say no. Always pass an error function.

2. Asking as soon as the page loads. Ask when the visitor presses a button, so they understand why.

3. Testing on plain http://. Geolocation needs https:// (or a local file).


Practice Questions

  1. What is a Web API?
  2. Which object holds the Geolocation API?
  3. What two functions does getCurrentPosition take?
  4. Which property tells you how accurate the position is?
  5. Which method keeps reporting new positions?
  6. Why is it better to ask for the location after a button click?

Practice Answers

  1. A feature the browser provides to JavaScript, such as location, storage or drag and drop.
  2. navigator.geolocation
  3. A success function and an error function.
  4. coords.accuracy
  5. watchPosition()
  6. Visitors understand why you're asking, so they're more likely to agree.

Key Takeaways

  • Geolocation needs the visitor's permission and a secure page.
  • getCurrentPosition(success, error) gives coords.latitude and coords.longitude.
  • Always handle errors; watchPosition tracks movement.