Geolocation API in HTML
Access User Location with JavaScript

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

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.

QUIZ

Question 1:Which method is used to get the current position of the user using the Geolocation API?

Question 2:The Geolocation API requires explicit user permission before accessing location data.

Question 3:Which of the following are methods provided by the Geolocation API?

Question 4:What is a common real-world use case for the Geolocation API?

Question 5:The Geolocation API can work in browsers without HTTPS if the site is served over HTTP.

Question 6:Which of the following data can the Geolocation API provide about a user’s location?