HTML5 Geolocation API

The Geolocation API allows web applications to access the user's geographic location (with permission). It's useful for maps, location-based services, and local content delivery.

Getting User Location

The Geolocation API is accessed via navigator.geolocation in JavaScript.

Use getCurrentPosition() to get the user's current location once.

The browser requests permission before accessing location data.

Location data includes latitude, longitude, accuracy, altitude (if available), and timestamp.

The API works via GPS on mobile devices and WiFi/IP geolocation on desktops.

<!-- HTML button to trigger location request -->
<button onclick="getLocation()">Get My Location</button>
<p id="location"></p>

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

function showPosition(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  document.getElementById('location').textContent = 
    `Latitude: ${lat}, Longitude: ${lon}`;
}

function showError(error) {
  document.getElementById('location').textContent = 
    `Error: ${error.message}`;
}
</script>

Position Object Properties

coords.latitude: Geographic latitude in decimal degrees.

coords.longitude: Geographic longitude in decimal degrees.

coords.accuracy: Location accuracy in meters.

coords.altitude: Height in meters above sea level (may be null).

coords.altitudeAccuracy: Altitude accuracy in meters (may be null).

coords.heading: Direction of travel in degrees (may be null).

coords.speed: Speed in meters per second (may be null).

timestamp: Date/time when position was acquired.

<button onclick="getDetailedLocation()">Get Detailed Location</button>
<div id="details"></div>

<script>
function getDetailedLocation() {
  navigator.geolocation.getCurrentPosition(function(position) {
    const details = `
      <strong>Location Details:</strong><br>
      Latitude: ${position.coords.latitude}°<br>
      Longitude: ${position.coords.longitude}°<br>
      Accuracy: ${position.coords.accuracy} meters<br>
      Altitude: ${position.coords.altitude || 'N/A'}<br>
      Speed: ${position.coords.speed || 'N/A'} m/s<br>
      Heading: ${position.coords.heading || 'N/A'}°<br>
      Time: ${new Date(position.timestamp).toLocaleString()}
    `;
    document.getElementById('details').innerHTML = details;
  });
}
</script>

Watching Position Changes

Use watchPosition() to continuously monitor location as the user moves.

Returns a watch ID that can be used to stop watching with clearWatch().

Useful for navigation apps, fitness trackers, or real-time location sharing.

Be mindful of battery usage - continuous GPS polling drains battery quickly.

Set appropriate timeout and maximumAge options to balance accuracy and power consumption.

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

<script>
let watchID = null;

function startTracking() {
  if (navigator.geolocation) {
    watchID = navigator.geolocation.watchPosition(
      function(position) {
        document.getElementById('tracking').textContent = 
          `Lat: ${position.coords.latitude.toFixed(4)}, ` +
          `Lon: ${position.coords.longitude.toFixed(4)}, ` +
          `Updated: ${new Date(position.timestamp).toLocaleTimeString()}`;
      },
      function(error) {
        document.getElementById('tracking').textContent = 
          `Tracking error: ${error.message}`;
      },
      { enableHighAccuracy: true, maximumAge: 5000 }
    );
  }
}

function stopTracking() {
  if (watchID !== null) {
    navigator.geolocation.clearWatch(watchID);
    watchID = null;
    document.getElementById('tracking').textContent = 'Tracking stopped.';
  }
}
</script>

Geolocation Options

enableHighAccuracy: Request best possible accuracy (uses GPS, drains battery).

timeout: Maximum time (milliseconds) to wait for location.

maximumAge: Accept cached position if it's not older than this value (milliseconds).

Setting enableHighAccuracy to true provides better accuracy but uses more power.

Use maximumAge to reduce API calls by accepting recent cached positions.

<button onclick="getHighAccuracy()">High Accuracy</button>
<button onclick="getFastLocation()">Fast (Cached OK)</button>
<p id="result"></p>

<script>
function getHighAccuracy() {
  const options = {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0  // Don't use cache
  };
  
  navigator.geolocation.getCurrentPosition(
    pos => {
      document.getElementById('result').textContent = 
        `High accuracy: ${pos.coords.accuracy}m accuracy`;
    },
    err => {
      document.getElementById('result').textContent = `Error: ${err.message}`;
    },
    options
  );
}

function getFastLocation() {
  const options = {
    enableHighAccuracy: false,
    timeout: 5000,
    maximumAge: 30000  // Accept 30-second-old cache
  };
  
  navigator.geolocation.getCurrentPosition(
    pos => {
      document.getElementById('result').textContent = 
        `Fast: ${pos.coords.latitude.toFixed(2)}, ${pos.coords.longitude.toFixed(2)}`;
    },
    err => {
      document.getElementById('result').textContent = `Error: ${err.message}`;
    },
    options
  );
}
</script>

Error Handling and Privacy

Geolocation requires user permission - always handle denial gracefully.

Error codes: PERMISSION_DENIED (1), POSITION_UNAVAILABLE (2), TIMEOUT (3).

HTTPS is required for geolocation in modern browsers (security requirement).

Always explain why you need location data before requesting it.

Provide fallback options if location is denied (e.g., manual location entry).

<button onclick="requestLocation()">Share Location</button>
<p id="status"></p>

<script>
function requestLocation() {
  // Explain why before requesting
  document.getElementById('status').textContent = 
    'Requesting location to show nearby stores...';
  
  if (!navigator.geolocation) {
    document.getElementById('status').textContent = 
      'Geolocation is not supported. Please enter your address manually.';
    return;
  }
  
  navigator.geolocation.getCurrentPosition(
    function(position) {
      document.getElementById('status').textContent = 
        `Location received! Finding stores near you...`;
      // Use position.coords.latitude and position.coords.longitude
    },
    function(error) {
      let message;
      switch(error.code) {
        case error.PERMISSION_DENIED:
          message = "Location access denied. You can manually enter your address.";
          break;
        case error.POSITION_UNAVAILABLE:
          message = "Location unavailable. Please check your device settings.";
          break;
        case error.TIMEOUT:
          message = "Location request timed out. Please try again.";
          break;
        default:
          message = "An unknown error occurred.";
      }
      document.getElementById('status').textContent = message;
    },
    { timeout: 10000 }
  );
}
</script>