HTML Geolocation API

Geolocation API in HTML: Know Where Your Users Are (With Permission)

Imagine you’re building a weather app, a delivery tracker, or a location-based game. You’ll need to know where the user is — and that’s where the Geolocation API comes in. It’s a powerful tool that lets you fetch a user's current location using just HTML and JavaScript.

1. What Is the Geolocation API?

The Geolocation API is a built-in browser feature that lets websites request a user’s latitude and longitude. This data can come from GPS, Wi-Fi, IP address, or cell tower triangulation — depending on the device and permissions.

2. Accessing User Location

The API is accessed through the navigator.geolocation object. You can use the getCurrentPosition() method to request the user's current location.

<button onclick="getLocation()">Get My Location</button>
<p id="output"></p>

<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    document.getElementById('output').innerText = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  document.getElementById('output').innerText = 
    "Latitude: " + lat + "\nLongitude: " + lon;
}

function showError(error) {
  document.getElementById('output').innerText = "Error: " + error.message;
}
</script>
Latitude: 17.385  
Longitude: 78.486

3. Geolocation API Methods

| Method | Description | |--------|-------------| | getCurrentPosition() | Fetches current location once | | watchPosition() | Tracks location continuously (e.g., for walking apps) | | clearWatch() | Stops tracking initiated by watchPosition() |

4. Example: Real-Time Position Tracking

let watchId;

function startTracking() {
  watchId = navigator.geolocation.watchPosition((pos) => {
    document.getElementById('output').innerText =
      'Tracking...\nLat: ' + pos.coords.latitude + '\nLon: ' + pos.coords.longitude;
  });
}

function stopTracking() {
  navigator.geolocation.clearWatch(watchId);
}
</script>

<button onclick="startTracking()">Start Tracking</button>
<button onclick="stopTracking()">Stop Tracking</button>

5. Permissions and Privacy

  • Browsers always ask the user to allow or block location access.
  • HTTPS is required for geolocation on most browsers (no access via HTTP).
  • Respect the user's privacy: don’t store or share location without consent.

6. Real-World Use Cases

  • Show local weather or time
  • Auto-fill country/state in forms
  • Find nearby stores or service centers
  • Power games or AR experiences based on real locations

7. Error Handling

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      alert("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      alert("The request to get user location timed out.");
      break;
    default:
      alert("An unknown error occurred.");
  }
}

Summary

The HTML5 Geolocation API gives your website a sense of place. You’ve learned how to:

  • Request location with getCurrentPosition()
  • Track updates with watchPosition()
  • Handle errors gracefully
  • Respect user privacy and permissions

Check your understanding 1

Which method is used to get the current position of the user using the Geolocation API?
Choose one answer. You can try again.

Answer and explanation

navigator.geolocation.getCurrentPosition()

The standard method to retrieve the user's current geographical position is navigator.geolocation.getCurrentPosition().

Check your understanding 2

The Geolocation API requires explicit user permission before accessing location data.
Choose one answer. You can try again.

Answer and explanation

True

For privacy reasons, browsers always prompt the user to allow or deny location access before the Geolocation API provides any data.

Check your understanding 3

Choose the option that lists all and only the correct statements.

  1. getCurrentPosition()
  2. watchPosition()
  3. clearWatch()
  4. setPosition()
Which of the following are methods provided by the Geolocation API?
Choose one answer. You can try again.

Answer and explanation

Statements 1 and 2 and 3

getCurrentPosition() gets the current location once, watchPosition() tracks location changes, and clearWatch() stops tracking. There is no setPosition() method.

Check your understanding 4

What is a common real-world use case for the Geolocation API?
Choose one answer. You can try again.

Answer and explanation

Displaying nearby restaurants on a map

The Geolocation API is commonly used for location-based services such as showing nearby restaurants, stores, or other points of interest.

Check your understanding 5

The Geolocation API can work in browsers without HTTPS if the site is served over HTTP.
Choose one answer. You can try again.

Answer and explanation

False

Most modern browsers require a secure context (HTTPS) for the Geolocation API to work to protect user privacy.

Check your understanding 6

Choose the option that lists all and only the correct statements.

  1. Latitude
  2. Longitude
  3. Altitude
  4. User's IP address
Which of the following data can the Geolocation API provide about a user’s location?
Choose one answer. You can try again.

Answer and explanation

Statements 1 and 2 and 3

The Geolocation API provides coordinates such as latitude, longitude, and altitude if available. It does not directly provide the user's IP address.

What’s Next?

Next, we’ll explore how to integrate geolocation data with mapping libraries like Leaflet or Google Maps to visualize user locations in real-time.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: HTML iframe Tag →