The JavaScript Geolocation API allows a website to access the user's geographic location (latitude and longitude) through the browser. It is commonly used for location-based services such as maps, weather apps, and showing nearby stores or events.
Geolocation runs in the browser (client-side) and requires explicit user permission before sharing any location data.
navigator.geolocation: The main object used to access geolocation features.getCurrentPosition(): Retrieves the user's current position once.position object.error object with a code and message.enableHighAccuracy, timeout, and maximumAge to fine-tune how geolocation works.The basic flow when using the Geolocation API is:
if (navigator.geolocation).navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options).position.coords.latitude and position.coords.longitude.options object to control accuracy, timeouts, and caching.The position object contains a coords property with details like latitude, longitude, accuracy, altitude (if available), and more.
getCurrentPosition() UsageThis example checks for support and then logs the user's latitude and longitude to the console.
// Check if the browser supports the Geolocation API
if (navigator.geolocation) {
// Request the current position (async)
navigator.geolocation.getCurrentPosition(
// Success callback: runs when location is retrieved
function (position) {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
},
// Error callback: runs if something goes wrong
function (error) {
console.error("Error code:", error.code, "Message:", error.message);
}
);
} else {
// Fallback when Geolocation is not available
console.log("Geolocation is not supported by this browser.");
}
Here we pass an options object to request high accuracy, set a timeout, and control how old cached positions can be.
// Configuration options for the Geolocation request
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
// Request the current position with success, error callbacks and options
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log("Latitude:", pos.coords.latitude);
console.log("Longitude:", pos.coords.longitude);
},
(err) => {
console.error("Error:", err.message);
},
options
);
In most real projects, instead of just logging to the console, you would show the coordinates on the page, pass them to a map service (like Google Maps), or send them to a server for location-based features.
The example below shows a simple interface where the user clicks a button to get their location. The script then displays the latitude and longitude, or an error message, on the screen.
navigator.geolocation exists before using it.enableHighAccuracy only when necessary because it can use more battery and take longer.timeout and maximumAge values to avoid hanging requests.enableHighAccuracy and timeout values and observe the behavior.