HTML Geolocation

Learn how to get the user's geographical location using the HTML Geolocation API

The HTML Geolocation API allows you to get the geographical position of a user. For privacy reasons, the user must approve location sharing before the browser can access their position.

The Geolocation API

The Geolocation API is accessed via the navigator.geolocation object. It provides methods to retrieve the user's current position and to watch for position changes.

🔒 Privacy First

For security reasons, the Geolocation API will only work on secure origins (HTTPS). The user must also explicitly grant permission to access their location.

Checking for Geolocation Support

Before using the Geolocation API, you should check if it's supported by the browser:

Feature Detection

if ("geolocation" in navigator) {
  // Geolocation is supported
  console.log("Geolocation is available");
} else {
  // Geolocation is not supported
  console.log("Geolocation is NOT available");
}

Getting Current Position

Use the getCurrentPosition() method to get the user's current location:

Basic Example

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

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

function showPosition(position) {
  document.getElementById("demo").innerHTML =
    "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      document.getElementById("demo").innerHTML =
        "User denied the request for Geolocation.";
      break;
    case error.POSITION_UNAVAILABLE:
      document.getElementById("demo").innerHTML =
        "Location information is unavailable.";
      break;
    case error.TIMEOUT:
      document.getElementById("demo").innerHTML =
        "The request to get user location timed out.";
      break;
    case error.UNKNOWN_ERROR:
      document.getElementById("demo").innerHTML =
        "An unknown error occurred.";
      break;
  }
}
</script>

Position Object Properties

The position object returned by the Geolocation API contains various properties:

Property Type Description
coords.latitude Number Latitude in decimal degrees
coords.longitude Number Longitude in decimal degrees
coords.accuracy Number Accuracy of position in meters
coords.altitude Number | null Altitude in meters above sea level
coords.altitudeAccuracy Number | null Accuracy of altitude in meters
coords.heading Number | null Direction of travel (degrees from north)
coords.speed Number | null Speed in meters per second
timestamp Number Time when position was acquired

Display All Position Properties

function showPosition(position) {
  var output = "Latitude: " + position.coords.latitude + "<br>";
  output += "Longitude: " + position.coords.longitude + "<br>";
  output += "Accuracy: " + position.coords.accuracy + " meters<br>";

  if (position.coords.altitude) {
    output += "Altitude: " + position.coords.altitude + " meters<br>";
  }

  if (position.coords.speed) {
    output += "Speed: " + position.coords.speed + " m/s<br>";
  }

  output += "Timestamp: " + new Date(position.timestamp);

  document.getElementById("demo").innerHTML = output;
}

Error Handling

The Geolocation API can fail for various reasons. Always handle errors properly:

Error Code Constant Description
1 PERMISSION_DENIED User denied the request for geolocation
2 POSITION_UNAVAILABLE Location information is unavailable
3 TIMEOUT Request to get user location timed out

Watching Position Changes

Use watchPosition() to continuously monitor the user's location:

Watch Position Example

<button onclick="startWatching()">Start Tracking</button>
<button onclick="stopWatching()">Stop Tracking</button>
<p id="position"></p>

<script>
var watchID;

function startWatching() {
  if (navigator.geolocation) {
    watchID = navigator.geolocation.watchPosition(
      updatePosition,
      showError,
      {enableHighAccuracy: true}
    );
  }
}

function stopWatching() {
  if (watchID) {
    navigator.geolocation.clearWatch(watchID);
    document.getElementById("position").innerHTML = "Tracking stopped";
  }
}

function updatePosition(position) {
  document.getElementById("position").innerHTML =
    "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude +
    "<br>Updated: " + new Date(position.timestamp).toLocaleTimeString();
}

function showError(error) {
  document.getElementById("position").innerHTML =
    "Error: " + error.message;
}
</script>

Important Methods

  • getCurrentPosition() - Get current position once
  • watchPosition() - Watch for position changes
  • clearWatch() - Stop watching position

Position Options

Both getCurrentPosition() and watchPosition() accept an optional third parameter with configuration options:

Option Type Default Description
enableHighAccuracy Boolean false Request higher accuracy (uses more power)
timeout Number Infinity Maximum time (ms) to wait for position
maximumAge Number 0 Accept cached position if newer than this (ms)

Using Position Options

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

navigator.geolocation.getCurrentPosition(
  showPosition,
  showError,
  options
);

Practical Examples

Display Location on Google Maps

<button onclick="showMap()">Show on Map</button>
<div id="map" style="width:100%;height:400px;"></div>

<script>
function showMap() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayMap, showError);
  }
}

function displayMap(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;

  // Create a Google Maps URL
  var mapUrl = "https://maps.google.com/maps?q=" + lat + "," + lng +
               "&z=15&output=embed";

  document.getElementById("map").innerHTML =
    '<iframe width="100%" height="100%" src="' + mapUrl + '"></iframe>';
}

function showError(error) {
  document.getElementById("map").innerHTML =
    "Unable to get location: " + error.message;
}
</script>

Calculate Distance Between Two Points

function calculateDistance(lat1, lon1, lat2, lon2) {
  // Haversine formula
  var R = 6371; // Earth's radius in kilometers
  var dLat = toRad(lat2 - lat1);
  var dLon = toRad(lon2 - lon1);

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
          Math.sin(dLon/2) * Math.sin(dLon/2);

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var distance = R * c;

  return distance;
}

function toRad(degrees) {
  return degrees * (Math.PI / 180);
}

// Example: Distance from New York to Los Angeles
var distance = calculateDistance(40.7128, -74.0060, 34.0522, -118.2437);
console.log("Distance: " + distance.toFixed(2) + " km");

Geolocation Best Practices

Best Practices

  1. Always Check for Support: Use feature detection before accessing geolocation
  2. Handle Errors Gracefully: Provide meaningful error messages to users
  3. Explain Why You Need Location: Tell users why you need their location
  4. Request Permission at Appropriate Time: Don't ask on page load
  5. Use HTTPS: Geolocation only works on secure connections
  6. Respect Privacy: Only request location when necessary
  7. Set Timeouts: Don't wait indefinitely for position
  8. Cache When Appropriate: Use maximumAge to reduce battery drain
  9. Provide Fallbacks: Allow manual location entry
  10. Stop Watching When Done: Use clearWatch() to save battery

⚠️ Important Notes

  • Geolocation requires user permission and HTTPS
  • High accuracy mode uses more battery power
  • Accuracy varies based on device and location method (GPS, WiFi, IP)
  • Some properties (altitude, speed, heading) may be null

Test Your Knowledge