HTML Geolocation
The HTML Geolocation API lets a web page ask the browser for the user's physical location — latitude and longitude coordinates. This powers features like "find stores near me," local weather, maps, and location-based services. The browser always asks the user for permission before sharing location data.
How Geolocation Works
Visual Diagram — Geolocation Request Flow
1. Web page calls geolocation API
|
↓
2. Browser shows permission popup to user:
"website.com wants to know your location"
[Allow] [Block]
|
┌────┴────┐
↓ ↓
Allow Block
| |
↓ ↓
3. Browser Returns error
detects (permission denied)
location
|
↓
4. Returns coordinates to your JavaScript:
latitude: 28.6139
longitude: 77.2090
|
↓
5. Page uses coordinates
(show map, find nearby places, etc.)
Detecting Geolocation Support
Not all browsers and devices support geolocation. Always check for support before calling the API.
<script>
if ("geolocation" in navigator) {
console.log("Geolocation is supported");
// safe to use the API
} else {
console.log("Geolocation is not supported by this browser");
}
</script>
Getting the Current Position
The getCurrentPosition() method requests the user's location once. It takes a success callback and an optional error callback.
<button onclick="getLocation()">Get My Location</button>
<p id="result"></p>
<script>
function getLocation() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
} else {
document.getElementById("result").textContent = "Geolocation not supported.";
}
}
function onSuccess(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById("result").textContent =
"Latitude: " + lat + " | Longitude: " + lon;
}
function onError(error) {
document.getElementById("result").textContent =
"Error: " + error.message;
}
</script>
The Position Object
The success callback receives a position object. It contains a coords property with the location data.
position.coords.latitude → latitude in decimal degrees position.coords.longitude → longitude in decimal degrees position.coords.accuracy → accuracy in meters position.coords.altitude → altitude in meters (if available) position.coords.altitudeAccuracy → altitude accuracy in meters position.coords.heading → direction of travel (degrees from north) position.coords.speed → speed in meters per second position.timestamp → time when position was acquired
Visual Diagram — Coordinates on Earth
90°N (North Pole)
|
|
-180°W ────────────── 0° ─────────────── 180°E
(Prime Meridian runs through London)
|
|
90°S (South Pole)
Delhi coordinates:
Latitude: 28.6139° N (north of equator)
Longitude: 77.2090° E (east of Prime Meridian)
Mumbai coordinates:
Latitude: 19.0760° N
Longitude: 72.8777° E
Error Handling
The error callback receives an error object with a code and a message.
function onError(error) {
switch(error.code) {
case 1:
// PERMISSION_DENIED — user clicked Block
console.log("User denied location access");
break;
case 2:
// POSITION_UNAVAILABLE — device cannot determine location
console.log("Location information unavailable");
break;
case 3:
// TIMEOUT — took too long to get location
console.log("Location request timed out");
break;
}
}
Geolocation Options
You can pass an options object as the third argument to getCurrentPosition() to control accuracy and timeout behavior.
const options = {
enableHighAccuracy: true, // use GPS if available (slower, more battery)
timeout: 10000, // give up after 10 seconds (in milliseconds)
maximumAge: 60000 // accept a cached position up to 60 seconds old
};
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
Visual Diagram — Accuracy Tradeoff
enableHighAccuracy: false (default) ┌───────────────────────────────────┐ │ City-level accuracy (~1–3 km) │ Fast, low battery use │ Uses WiFi/cellular network │ └───────────────────────────────────┘ enableHighAccuracy: true ┌──────────────────────┐ │ GPS accuracy (~10m) │ Slower, more battery │ Uses device GPS │ └──────────────────────┘
Watching Position — Continuous Updates
The watchPosition() method keeps watching the user's location and calls the success callback every time the position changes. This is useful for navigation and tracking applications.
<script>
let watchId;
function startWatching() {
watchId = navigator.geolocation.watchPosition(
function(position) {
console.log("Updated position:",
position.coords.latitude,
position.coords.longitude);
},
function(error) {
console.log("Error:", error.message);
}
);
}
function stopWatching() {
navigator.geolocation.clearWatch(watchId);
console.log("Stopped watching position");
}
</script>
<button onclick="startWatching()">Start Tracking</button>
<button onclick="stopWatching()">Stop Tracking</button>
Always call clearWatch() when you no longer need position updates — continuous GPS usage drains the device battery quickly.
Displaying Location on Google Maps
The most common use of geolocation is to show the user's position on a map.
<div id="map" style="width:100%; height:400px;"></div>
<!-- Google Maps API script (requires an API key from Google) -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<script>
navigator.geolocation.getCurrentPosition(function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: lat, lng: lon },
zoom: 15
});
new google.maps.Marker({
position: { lat: lat, lng: lon },
map: map,
title: "You are here"
});
});
</script>
Practical Use Cases
Use Case How Geolocation Helps ---------------------- ------------------------------------------ Store locator Find shops near user's coordinates Weather app Load weather for user's city automatically Food delivery Auto-fill delivery address Navigation Show directions from current position Check-in feature Verify user is at a physical location Nearest ATM / hospital Search a database using lat/lon Ride-sharing apps Pick up from user's exact location
Security and Privacy Rules
Browsers enforce strict rules around geolocation to protect user privacy.
HTTPS required — Geolocation only works on pages served over HTTPS. It does not work on plain HTTP pages (except on localhost for development).
User must grant permission — The browser always shows a permission prompt. Your JavaScript cannot get location data without explicit user approval.
Permission can be revoked — Users can change their permission decision at any time in browser settings. Your code must handle the case where permission is denied even on a second visit.
One-time vs persistent permission — Some browsers ask for permission once and remember the choice. Others ask every session.
Always tell users why your page needs their location before the browser's permission prompt appears. A clear explanation increases the likelihood that users grant permission.
