JavaScript Geolocation API


The Geolocation API allows web applications to access the user's geographical location (latitude and longitude) with their permission. It is widely used in maps, weather apps, local services, and location-based content.



1. What is the Geolocation API?

  • Part of the HTML5 specification
  • Available in most modern browsers
  • Requires user permission to access location
  • Uses GPS, Wi-Fi, mobile towers, or IP address


Permission Alert

When you use the Geolocation API, the browser prompts the user to allow or deny access. Without permission, the location won't be retrieved.



2. Basic Syntax – navigator.geolocation.getCurrentPosition()

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
  • successCallback: Function called with position info
  • errorCallback (optional): Called if location fails
  • options (optional): Fine-tune accuracy and timeout


Example: Get 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").textContent = "Geolocation is not supported by this browser.";
  }
}

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

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.");
      break;
  }
}
</script>


3. Options (3rd Parameter)

You can pass a configuration object:

{enableHighAccuracy: true,   // Use GPS if available
timeout: 5000,              // Max time to wait (ms)
maximumAge: 0               // Do not use cached location
}


Real-World Use Cases

  • Show user’s location on a map (Google Maps, Leaflet)
  • Provide weather updates based on location
  • Suggest nearby restaurants, stores, or services
  • Track user's movement (e.g., delivery tracking)


Privacy Tips

  • Always ask for permission clearly.
  • Use HTTPS to avoid warnings or failures.
  • Only access location when necessary.