Tutorials JavaScript Geolocation API
Ch 60 / 78
Chapter 60 Intermediate 15 min read JavaScript

JavaScript Geolocation API

The Geolocation API lets your web application access the user's real-world geographic location — latitude, longitude, altitude, and speed — directly from the browser, with a single permission prompt and no external library.

What you'll learn
What the Geolocation API is and how it works
How to use getCurrentPosition()
The full coords object explained
Handling all three error codes gracefully
Continuous tracking with watchPosition()
Real-world map integration using Leaflet.js

What Is the Geolocation API?

The Geolocation API is a W3C standard browser interface that allows web pages to request the user's geographical position. It is exposed through the read-only property navigator.geolocation and requires explicit user consent before any coordinates are shared.

The browser can determine location using one or more of the following sources, depending on device capabilities:

GPS
Most accurate (±1–5 m). Used on mobile devices with GPS chip. Slower to acquire, drains battery.
Wi-Fi Triangulation
Good indoor accuracy (±15–40 m). Uses nearby Wi-Fi network BSSIDs against a database.
Cell Tower
Lower accuracy (±100–1000 m). Works without Wi-Fi, useful as a fallback on mobile.
IP Address
Least accurate (±1–50 km). Last resort when other methods are unavailable. Often city-level only.
HTTPS Required
Most browsers only grant Geolocation permission on secure origins (https://) or localhost. On plain HTTP the permission will be blocked or permanently denied.

Checking for Browser Support

Always verify that navigator.geolocation exists before calling any method. This is a feature check — it does not test whether the user has granted permission.

JavaScript
// Feature detection — always do this first
if ("geolocation" in navigator) {
  console.log("✓ Geolocation is supported");
  // safe to call geolocation methods
} else {
  console.log("✗ Geolocation is NOT supported");
  // show a fallback UI or message
}
Pro Tip
Geolocation is supported in all modern browsers (Chrome 5+, Firefox 3.5+, Safari 5+, Edge 12+). You only need this check if you must support very old environments.

getCurrentPosition()

navigator.geolocation.getCurrentPosition() is the primary method. It fires the success callback once with a GeolocationPosition object when the device's position is determined.

successCallback
Required. Receives a GeolocationPosition object containing coords and timestamp.
errorCallback
Optional but recommended. Receives a GeolocationPositionError with code and message.
options
Optional. A PositionOptions object to control accuracy, timeout, and cache age.
JavaScript — Basic Usage
navigator.geolocation.getCurrentPosition(
  // ✅ Success callback
  function(position) {
    const lat  = position.coords.latitude;
    const lon  = position.coords.longitude;
    const acc  = position.coords.accuracy;  // metres
    const time = position.timestamp;        // ms since epoch

    console.log(`📍 Lat: ${lat}, Lon: ${lon}`);
    console.log(`🎯 Accuracy: ±${acc} m`);
  },

  // ❌ Error callback
  function(error) {
    console.error("Location error:", error.message);
  }
);
Advertisement

The coords Object

The position.coords property is a GeolocationCoordinates object with seven read-only properties. latitude, longitude, and accuracy are always present. The rest may be null depending on the device:

Property Type Unit Always present? Description
latitude Number Degrees
Yes
Geographic latitude (−90 to +90)
longitude Number Degrees
Yes
Geographic longitude (−180 to +180)
accuracy Number Metres
Yes
Radius of lat/lon confidence circle
altitude Number | null Metres
Maybe
Height above WGS84 reference ellipsoid
altitudeAccuracy Number | null Metres
Maybe
Accuracy of the altitude value
heading Number | null Degrees
Maybe
Direction of travel (0 = North, clockwise). NaN if speed = 0.
speed Number | null m/s
Maybe
Magnitude of device velocity
JavaScript — Reading All Properties
navigator.geolocation.getCurrentPosition((position) => {
  const {
    latitude, longitude, accuracy,
    altitude, altitudeAccuracy,
    heading, speed
  } = position.coords;

  console.log(`Lat / Lon : ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`);
  console.log(`Accuracy  : ±${accuracy.toFixed(1)} m`);

  if (altitude !== null) {
    console.log(`Altitude  : ${altitude.toFixed(1)} m`);
  }

  if (speed !== null) {
    // Convert m/s → km/h
    console.log(`Speed     : ${(speed * 3.6).toFixed(1)} km/h`);
  }

  const readableTime = new Date(position.timestamp).toLocaleString();
  console.log(`Timestamp : ${readableTime}`);
});

Error Handling

The error callback receives a GeolocationPositionError object. Always handle all three error codes — users regularly deny location access, especially on desktop.

code Constant When it fires
1 PERMISSION_DENIED User clicked "Block" or the browser policy denies access
2 POSITION_UNAVAILABLE Location hardware / network source returned an error
3 TIMEOUT Acquisition exceeded the timeout option
JavaScript — Full Error Handler
function handleGeoError(error) {
  const messages = {
    1: "Permission denied. Please allow location in your browser settings.",
    2: "Position unavailable. Check device sensors or network.",
    3: "Request timed out. Try again."
  };

  const msg = messages[error.code] || `Unknown error: ${error.message}`;
  console.error(`[Geo error ${error.code}] ${msg}`);

  // Show user-friendly UI
  document.getElementById("geoStatus").textContent = msg;
}

navigator.geolocation.getCurrentPosition(
  (pos) => console.log(pos.coords),
  handleGeoError
);
Common Mistake
If the user dismisses the browser permission prompt without choosing, neither callback fires immediately. The browser may re-prompt later or permanently block the origin after repeated dismissals — always provide a fallback UI.

PositionOptions

All three geolocation methods accept an optional PositionOptions object as the third argument, letting you balance accuracy, speed, and battery life:

Option Type Default Description
enableHighAccuracy Boolean false Hint to use GPS if available — slower and drains more battery.
timeout Number Infinity Max milliseconds the browser may take to return a position before triggering error code 3.
maximumAge Number 0 Max age (ms) of a cached position the browser may return. 0 = always fresh. Infinity = always use cache.
JavaScript — PositionOptions Example
const options = {
  enableHighAccuracy: true,   // prefer GPS over Wi-Fi / IP
  timeout:           10000,  // give up after 10 seconds
  maximumAge:        30000   // re-use a fix ≤ 30 s old
};

navigator.geolocation.getCurrentPosition(
  (pos)  => console.log("Coords:", pos.coords),
  (err)  => console.error("Error:", err.message),
  options                    // ← third argument
);
Battery Tip
Use maximumAge: 60000 combined with enableHighAccuracy: false for non-real-time use cases (e.g. showing a city-level weather forecast). This avoids waking the GPS chip on every call.
Advertisement

watchPosition()

Unlike getCurrentPosition(), which fires once, watchPosition() keeps firing the success callback every time the device position changes. It returns a numeric watchId that you must store to stop the watch later.

JavaScript — watchPosition
let watchId;   // store the ID so we can stop later

function startTracking() {
  watchId = navigator.geolocation.watchPosition(
    (position) => {
      const { latitude, longitude, accuracy } = position.coords;
      console.log(`🔄 Update → ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`);
      updateMapMarker(latitude, longitude);   // your map function
    },
    (err) => console.error(err.message),
    { enableHighAccuracy: true, timeout: 5000 }
  );

  console.log(`Watch started with ID: ${watchId}`);
}

clearWatch()

Call navigator.geolocation.clearWatch(watchId) to stop continuous tracking. Always call this when the user navigates away or when location is no longer needed — an active watch keeps the GPS radio alive and drains battery.

JavaScript — clearWatch
function stopTracking() {
  if (watchId !== undefined) {
    navigator.geolocation.clearWatch(watchId);
    console.log(`Watch ${watchId} cleared.`);
    watchId = undefined;
  }
}

// ✅ Good practice — clean up before user leaves the page
window.addEventListener("beforeunload", stopTracking);

// ✅ In React — clean up inside useEffect return
useEffect(() => {
  const id = navigator.geolocation.watchPosition(onSuccess, onError);
  return () => navigator.geolocation.clearWatch(id);  // cleanup
}, []);

Real-World Map Integration (Leaflet.js)

The most common Geolocation use case is rendering the user's position on an interactive map. Leaflet.js is a free, open-source mapping library that pairs perfectly with the Geolocation API.

⚡
Free Resource
Download our JavaScript Cheat Sheet
Geolocation, Web Workers, Canvas, IndexedDB — all Web APIs on one page.
Get Sheet
HTML — Load Leaflet
<!-- 1. Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

<!-- 2. Map container -->
<div id="map" style="height:420px; border-radius:12px;"></div>

<!-- 3. Leaflet JS -->
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
JavaScript — Full Map + Geolocation
// 1. Initialise map at a world-level default view
const map = L.map("map").setView([20, 78], 5);

// 2. Add OpenStreetMap tiles (free, no API key needed)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution: "© <a href='https://openstreetmap.org'>OpenStreetMap</a> contributors"
}).addTo(map);

// 3. Get position and fly to it
if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition((pos) => {
    const { latitude: lat, longitude: lon, accuracy } = pos.coords;

    // Smooth pan + zoom to user location
    map.flyTo([lat, lon], 15, { duration: 1.5 });

    // Drop a marker with a popup
    L.marker([lat, lon])
      .addTo(map)
      .bindPopup("📍 You are here!")
      .openPopup();

    // Draw an accuracy circle around the fix
    L.circle([lat, lon], {
      radius:      accuracy,
      color:       "#f7df1e",
      fillOpacity: 0.1
    }).addTo(map);

  }, (err) => console.error(err.message), { enableHighAccuracy: true });
}
Other Map Libraries
You can swap Leaflet for Google Maps JS API, Mapbox GL JS, or OpenLayers. The Geolocation code stays identical — only the map library calls change.

Try It Yourself

Edit the code below and click ▶ Run Code to see Geolocation + Leaflet running live. Click Run in Editor for a full-screen editor window.

Live Editor
✎ Editor
👁 Preview
Preview note
The Geolocation permission prompt only fires in the Run in Editor window (served over a proper origin). It won't fire inside the sandboxed preview iframe on this page.

Best Practices

✅ Do
  • Check "geolocation" in navigator first
  • Always provide an error callback
  • Serve over HTTPS in production
  • Call clearWatch() when done
  • Use maximumAge to avoid re-querying GPS
  • Only request location on a user gesture (button click), not page load
  • Show a loading indicator while acquiring position
  • Handle all three error codes with a user-friendly message
❌ Don't
  • Request location on page load without interaction
  • Ignore the error callback
  • Store raw coordinates without user awareness
  • Use enableHighAccuracy: true when low accuracy is sufficient
  • Leave a watchPosition running indefinitely in SPAs
  • Assume altitude, speed, or heading are never null
Advertisement
Quick Check — Chapter 60

Which Geolocation error code fires when the user clicks "Block"?

Chapter Summary
  • The Geolocation API lives at navigator.geolocation and requires HTTPS + user permission.
  • getCurrentPosition(success, error, options) retrieves the position once.
  • watchPosition() fires the callback on every position change and returns a watchId.
  • Always call clearWatch(watchId) to stop tracking and save battery.
  • The coords object provides latitude, longitude, and accuracy (always), plus optional altitude, speed, and heading.
  • Three error codes: 1 PERMISSION_DENIED · 2 POSITION_UNAVAILABLE · 3 TIMEOUT.
  • Use enableHighAccuracy, timeout, and maximumAge in PositionOptions to balance accuracy and battery.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel