Geolocation API
This lesson explains Geolocation API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.
HTML5 Geolocation API Overview
The HTML5 Geolocation API allows web applications to request the user's
geographic location with permission. It can return latitude, longitude,
accuracy, altitude, speed, and heading information depending on the
device, browser, and available location sensors.
Geolocation is commonly used in maps, delivery apps, store locators,
weather apps, ride-sharing apps, location-based search, travel apps,
emergency tools, and personalized local experiences. Because location is
sensitive information, browsers require user permission and usually
require HTTPS in production.
| Feature | Description |
| API Name | Geolocation API |
| Main Object | navigator.geolocation |
| Current Location Method | getCurrentPosition() |
| Tracking Method | watchPosition() |
| Stop Tracking Method | clearWatch() |
| Security | Requires user permission and HTTPS in production. |
Get Current Location
// HTML5 Geolocation API
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
console.log("Accuracy:", position.coords.accuracy);
},
(error) => {
console.error("Location error:", error.message);
}
);
} else {
console.log("Geolocation is not supported.");
}
The getCurrentPosition() method asks the browser for the
user's current location. If the user grants permission, the success
callback receives a Position object.
Geolocation Methods
| Method | Description | Example Syntax |
getCurrentPosition() | Gets the user's current location once. | navigator.geolocation.getCurrentPosition(success, error) |
watchPosition() | Continuously watches location changes. | navigator.geolocation.watchPosition(success, error) |
clearWatch() | Stops a location watch. | navigator.geolocation.clearWatch(watchId) |
Position and Coordinates Properties
A successful geolocation request returns a Position object.
The most commonly used values are available inside
position.coords.
| Property | Description | Example Value |
coords.latitude | Latitude in decimal degrees. | 33.1972 |
coords.longitude | Longitude in decimal degrees. | -96.6398 |
coords.accuracy | Estimated accuracy in meters. | 25 |
coords.altitude | Altitude above sea level, if available. | 180 |
coords.altitudeAccuracy | Altitude accuracy in meters, if available. | 12 |
coords.heading | Direction of travel in degrees, if available. | 90 |
coords.speed | Speed in meters per second, if available. | 4.5 |
timestamp | Time when the position was captured. | 1717000000000 |
Geolocation Options
Geolocation requests can include options to control accuracy, timeout, and
cached location behavior.
const options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(
handleSuccess,
handleError,
options
);
| Option | Description | Common Value |
enableHighAccuracy | Requests more accurate location data. | true or false |
timeout | Maximum time to wait for location. | 10000 |
maximumAge | Maximum age of cached location in milliseconds. | 0 |
Handle Geolocation Errors
function handleError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log("User denied location permission.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("Location request timed out.");
break;
default:
console.log("Unknown location error.");
}
}
Always handle permission denial, unavailable location data, and timeout
errors so the application can continue working gracefully.
Watch User Location
const watchId =
navigator.geolocation.watchPosition(
(position) => {
console.log("Updated Latitude:", position.coords.latitude);
console.log("Updated Longitude:", position.coords.longitude);
},
handleError,
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 5000
}
);
// Stop watching later
navigator.geolocation.clearWatch(watchId);
Use watchPosition() for apps that need continuous location
updates, such as navigation, delivery tracking, walking routes, or
fitness apps. Always stop tracking when it is no longer needed.
Open Location in Google Maps
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude =
position.coords.latitude;
const longitude =
position.coords.longitude;
const mapUrl =
"https://www.google.com/maps?q=" +
latitude +
"," +
longitude;
window.open(mapUrl, "_blank");
},
handleError
);
This example creates a Google Maps URL using the user's latitude and
longitude. It is useful for location sharing, directions, and map-based
workflows.
Calculate Distance Between Two Coordinates
function getDistanceInKm(
lat1,
lon1,
lat2,
lon2
) {
const earthRadius = 6371;
const dLat =
(lat2 - lat1) * Math.PI / 180;
const dLon =
(lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat / 2) *
Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) *
Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c =
2 * Math.atan2(
Math.sqrt(a),
Math.sqrt(1 - a)
);
return earthRadius * c;
}
const distance =
getDistanceInKm(
33.1972,
-96.6398,
32.7767,
-96.7970
);
console.log(distance);
This example uses the Haversine formula to estimate distance between two
coordinates. It is useful for store locators, delivery radius checks, and
nearby search features.
Check Permission Status
async function checkLocationPermission() {
if (!("permissions" in navigator)) {
return "unsupported";
}
const permission =
await navigator.permissions.query(
{ name: "geolocation" }
);
return permission.state;
}
checkLocationPermission()
.then((state) => {
console.log("Location permission:", state);
});
The Permissions API can check whether geolocation is granted, denied, or
still waiting for the user prompt. Browser behavior may vary, so always
handle normal geolocation errors too.
Common Geolocation API Use Cases
| Use Case | How Geolocation Helps |
| Store Locator | Find nearby stores, branches, restaurants, or services. |
| Weather App | Show local weather based on current location. |
| Delivery Tracking | Track drivers, customers, or delivery routes. |
| Ride Sharing | Find pickup and drop-off coordinates. |
| Maps and Navigation | Center maps and calculate routes. |
| Local Search | Personalize search results by location. |
| Fitness Apps | Track walking, running, or cycling paths. |
| Travel Apps | Show nearby attractions, hotels, and restaurants. |
Privacy and Security Best Practices
- Request location only when the user starts a location-based action.
- Explain why location access is needed before requesting permission.
- Use HTTPS for production websites.
- Do not track location continuously unless it is required.
- Stop location tracking using
clearWatch() when finished. - Store only the minimum location data needed.
- Avoid sharing precise location with third parties unnecessarily.
- Provide a manual location entry option as a fallback.
Geolocation API Best Practices
- Use feature detection before calling geolocation methods.
- Always provide error callbacks.
- Handle permission denial gracefully.
- Use
enableHighAccuracy only when needed because it may use more battery. - Use sensible
timeout and maximumAge values. - Provide manual address or ZIP code input as a fallback.
- Do not request location on page load unless absolutely necessary.
- Clearly communicate loading, success, and error states.
Common Geolocation API Mistakes
- Requesting location immediately when the page loads.
- Not explaining why location access is needed.
- Ignoring permission denial errors.
- Using high accuracy for every request unnecessarily.
- Forgetting to stop
watchPosition(). - Assuming location data is always accurate.
- Not providing a fallback for unsupported browsers.
- Storing precise location data without a clear reason.
Geolocation API vs IP-Based Location
| Feature | Geolocation API | IP-Based Location |
| User Permission | Required | Usually not required |
| Accuracy | Higher, especially on mobile devices | Lower, often city or region level |
| Best For | Maps, tracking, nearby services | Country, region, language, basic personalization |
| Privacy Impact | High | Medium |
| Requires Browser API | Yes | No, usually server-side |
Key Takeaways
- The Geolocation API requests the user's location with permission.
- Use
navigator.geolocation.getCurrentPosition() for one-time location. - Use
watchPosition() for continuous tracking. - Use
clearWatch() to stop tracking. - Always handle permission denial, timeout, and unavailable location errors.
- Respect privacy and request only the minimum location data needed.
Important Note
Location data is highly sensitive. Request geolocation only when it
clearly benefits the user, explain the reason, provide a manual fallback,
and avoid storing precise coordinates unless your application truly needs
them.