HTML Geolocation


The HTML Geolocation API allows your website to request the user’s current location. It can detect latitude, longitude and in some cases speed, accuracy and altitude. This feature is widely used in map applications, delivery tracking, ride-booking, weather updates and check-in systems. The browser always asks for permission before sharing location, so it is safe and privacy-controlled. In this chapter, you will learn how the Geolocation API works, how to request location, how to handle errors and how to watch continuous location updates.

What Is the Geolocation API

The Geolocation API is a browser-based interface that allows JavaScript to access the device’s GPS or network-based location data. HTML itself does not track location, but JavaScript uses the browser’s built-in API through the navigator.geolocation object.

Key capabilities

  • Get user’s current location

  • Track live movement

  • Show map positions

  • Use for delivery, rides and check-in

  • Works on phones, laptops and tablets

Because the browser manages permissions, the user is always in control.

Checking If Geolocation Is Supported

Before using the API, check if the browser supports it. This prevents errors on older browsers.

<script>
if ("geolocation" in navigator) {
  console.log("Geolocation supported");
} else {
  console.log("Geolocation not supported");
}
</script>

If supported, you can safely request location.

Getting Current Location with getCurrentPosition()

The most common method is getCurrentPosition(). It fetches the location only once.

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

<script>
function getLocation() {
  navigator.geolocation.getCurrentPosition(showPosition, showError);
}

function showPosition(pos) {
  document.getElementById("output").textContent =
    "Latitude: " + pos.coords.latitude +
    " | Longitude: " + pos.coords.longitude;
}

function showError(err) {
  document.getElementById("output").textContent = err.message;
}
</script>

When the user clicks the button, the browser shows a permission popup. If the user allows it, you get coordinates.

Understanding the Position Object

The pos object contains several useful properties:

Coordinates inside pos.coords

  • latitude

  • longitude

  • accuracy – meters

  • altitude – optional

  • speed – optional

  • heading – direction in degrees

Example

pos.coords.latitude
pos.coords.longitude
pos.coords.accuracy

Accuracy tells you how close the reading is to the real location.

Handling Errors with showError()

The Geolocation API produces different error messages. Handling them helps you guide the user.

Common error codes

  • 1 → Permission denied

  • 2 → Position unavailable

  • 3 → Timeout

Example message handling

function showError(error) {
  if (error.code === 1) {
    alert("Please enable location permissions.");
  } else if (error.code === 2) {
    alert("Location unavailable.");
  } else if (error.code === 3) {
    alert("Request timed out.");
  }
}

This improves the user experience.

Tracking Live Location with watchPosition()

Sometimes you need continuous location tracking, such as for delivery apps, running trackers or live navigation. For this, use watchPosition().

<button onclick="startTracking()">Start Tracking</button>
<p id="live"></p>

<script>
let watchId;

function startTracking() {
  watchId = navigator.geolocation.watchPosition(updateLive);
}

function updateLive(pos) {
  document.getElementById("live").textContent =
    "Live Latitude: " + pos.coords.latitude +
    " | Live Longitude: " + pos.coords.longitude;
}
</script>

This keeps updating coordinates as the user moves.

Stopping the Tracking

Tracking continues until you stop it manually. Use clearWatch().

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

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

Stopping tracking reduces battery usage and prevents unnecessary updates.

Improving Accuracy

You can pass options to improve accuracy. High accuracy uses GPS directly, which gives better results but may use more battery.

Options parameter

navigator.geolocation.getCurrentPosition(showPosition, showError, {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
});
  • enableHighAccuracy: true → better GPS

  • timeout → max waiting time

  • maximumAge → avoid using old cached data

Displaying Location on Google Maps

You can show the coordinates on Google Maps using a basic link.

<script>
function showPosition(pos) {
  let lat = pos.coords.latitude;
  let lon = pos.coords.longitude;

  window.open(
    "https://www.google.com/maps?q=" + lat + "," + lon,
    "_blank"
  );
}
</script>

This opens the exact location in a new tab.

Embedding Maps Inside the Page

You can load Google Maps inside an iframe with coordinates.

<iframe id="map" width="300" height="300"></iframe>

<script>
function showPosition(pos) {
  let lat = pos.coords.latitude;
  let lon = pos.coords.longitude;

  document.getElementById("map").src =
    "https://maps.google.com/maps?q=" + lat + "," + lon + "&z=15&output=embed";
}
</script>

Your page shows an interactive map with the user’s position.

Common Use Cases

Delivery services

Track delivery partners moving on the map.

Ride-booking

Drivers and users share their live location.

Weather apps

Show weather based on current location.

Attendance and check-in

Employees check-in from fixed locations.

Event apps

Locate nearby events or stalls.

Fitness tracking

Record running or cycling paths using live tracking.

The Geolocation API is the foundation of these real-world features.

Privacy and Permission Rules

Browsers take strict steps to protect location data.

  • User must always grant permission

  • HTTPS is required on most browsers

  • Permission can be blocked anytime

  • Apps must clearly explain why location is needed

This makes the API safe for users.

Complete Working Example

Here is a simple UI that displays location in text and shows it on a map.

<button onclick="locate()">Show My Location</button>
<p id="details"></p>
<iframe id="map" width="300" height="300"></iframe>

<script>
function locate() {
  navigator.geolocation.getCurrentPosition(success, showError);
}

function success(pos) {
  let lat = pos.coords.latitude;
  let lon = pos.coords.longitude;

  document.getElementById("details").textContent =
    "Latitude: " + lat + " | Longitude: " + lon;

  document.getElementById("map").src =
    "https://maps.google.com/maps?q=" + lat + "," + lon + "&z=15&output=embed";
}

function showError(err) {
  document.getElementById("details").textContent = err.message;
}
</script>

This combines everything you learned in this chapter.

Summary of HTML Geolocation

The Geolocation API allows websites to request and track user location safely. You learned how to check browser support, get current position, handle errors, track live movement, improve accuracy and display coordinates on Google Maps. With these tools, you can build features like delivery tracking, ride apps, check-ins and weather systems. Geolocation is one of the most useful browser APIs in modern web development.


Practice Questions

Q1. Use navigator.geolocation.getCurrentPosition() to show latitude and longitude.

Q2. Add a button that fetches location on click.

Q3. Display an error message if the user denies location permission.

Q4. Use watchPosition() to track real-time movement.

Q5. Display a live Google Maps link using the coordinates.

Q6. Show coordinates only when accessed over HTTPS.

Q7. Log errors for debugging using showError() function.

Q8. Update a <div> with coordinates every 5 seconds using watchPosition.

Q9. Create a fallback message for unsupported browsers.

Q10. Use clearWatch() to stop location tracking with a "Stop" button.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top