The Geolocation API allows web applications to access a user's geographic location (with the user's permission). It can provide latitude, longitude, altitude (if available), speed, heading, and accuracy information.
π What is the Geolocation API?
The Geolocation API is a built-in browser API that retrieves the user's current location using GPS, Wi-Fi, mobile networks, or IP-based location services, depending on the device and browser capabilities.
π‘ Why Use the Geolocation API?
- π Find the user's current location
- πΊοΈ Display nearby places on a map
- π Ride-sharing and delivery applications
- π¦οΈ Show local weather information
- π§ Navigation and location-based services
π Checking Browser Support
Before using the API, verify that the browser supports Geolocation.
Check Support
if ("geolocation" in navigator) {
console.log("Geolocation is supported.");
} else {
console.log("Geolocation is not supported.");
}π Getting the Current Location
Use getCurrentPosition() to retrieve the user's current location once.
Get Current Position
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
}
);π Accessing Location Data
The location information is available through theposition.coords object.
Read Coordinates
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
console.log(position.coords.accuracy);
}
);π¦ Position Object
| Property | Description |
|---|---|
| latitude | User's latitude. |
| longitude | User's longitude. |
| accuracy | Estimated accuracy in meters. |
| altitude | Height above sea level (if available). |
| altitudeAccuracy | Accuracy of altitude. |
| heading | Direction of travel in degrees. |
| speed | Speed in meters per second. |
β Handling Errors
Provide an error callback to handle permission denials or other failures.
Error Callback
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
console.log(error.message);
}
);π¨ Error Codes
| Code | Description |
|---|---|
| 1 | Permission denied. |
| 2 | Position unavailable. |
| 3 | Request timed out. |
π Watching the User's Location
Use watchPosition() to receive location updates whenever the user's position changes.
Watch Position
const watchId =
navigator.geolocation.watchPosition(
(position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
);π Stop Watching
Stop receiving updates with clearWatch().
Clear Watch
navigator.geolocation.clearWatch(watchId);βοΈ Geolocation Options
You can customize how location data is retrieved using an options object.
Options Example
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(
success,
error,
options
);π Options Explained
| Option | Description |
|---|---|
| enableHighAccuracy | Requests more precise location (may use more battery). |
| timeout | Maximum time to wait before timing out. |
| maximumAge | Maximum acceptable age of a cached location. |
π Complete Example
HTML
<button id="btn">
Get Current Location
</button>
<p id="location"></p>JavaScript
const btn =
document.getElementById("btn");
const output =
document.getElementById("location");
btn.addEventListener("click", () => {
navigator.geolocation.getCurrentPosition(
(position) => {
output.textContent =
`Latitude: ${position.coords.latitude},
Longitude: ${position.coords.longitude}`;
},
() => {
output.textContent =
"Unable to retrieve location.";
}
);
});π getCurrentPosition() vs watchPosition()
| Feature | getCurrentPosition() | watchPosition() |
|---|---|---|
| Returns Location Once | β Yes | β No |
| Continuous Updates | β No | β Yes |
| Best For | One-time location | Navigation & tracking |
β οΈ Important Notes
- π The user must grant location permission.
- π Most browsers require a secure context (HTTPS) to use the Geolocation API.
- π± Accuracy depends on the device, signal quality, and available location providers.
- π High-accuracy mode may consume more battery.
Note
β Best Practices
- π Request location only when it is actually needed.
- β‘ Use getCurrentPosition() for one-time lookups.
- π§ Use watchPosition() only when continuous tracking is required.
- β Always handle errors and permission denials gracefully.
- π Disable location watching when it is no longer needed to conserve battery.
π― Summary
The Geolocation API enables web applications to access a user's location with permission. It provides methods like getCurrentPosition() for one-time location retrieval and watchPosition() for continuous tracking. It is commonly used in maps, navigation, weather, ride-sharing, and other location-aware applications.