Example 1 — Get Current Position
navigator.geolocation.getCurrentPosition(function (pos) {
console.log(pos.coords.latitude, pos.coords.longitude);
}); How It Works
The browser shows a permission dialog the first time your site requests location.

The Geolocation API allows web applications to retrieve the geographical location of a user’s device. This feature enables location-based services and functionalities, such as displaying nearby places, customizing content based on location, and providing location-based recommendations.
The API provides location data using GPS, Wi-Fi, cell towers, or IP-based methods—whichever the device supports. You access it through JavaScript’s navigator.geolocation object, not through an HTML tag.
Location API.
One-time read.
Live updates.
Lat & lng.
3 error codes.
User consent.
Geolocation refers to the process of determining the physical location of a device. The Geolocation API in HTML5 provides a way to access this information programmatically, allowing web applications to use location data for various purposes, such as mapping and location-based services.
“HTML Geolocation” really means using geolocation from a web page. The API is JavaScript on navigator.geolocation—there is no <geolocation> element.
The Geolocation API determines a user’s location using various methods, including:
The browser chooses the best available source and returns a Position object with coordinates and an accuracy value in meters.
To use the Geolocation API, you need to call the navigator.geolocation object, which provides methods for retrieving location data. The main methods are getCurrentPosition and watchPosition.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options); Position object on success.PositionError object on failure.enableHighAccuracy, timeout, and maximumAge.function successCallback(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log('Latitude: ' + latitude + ', Longitude: ' + longitude);
}
function errorCallback(error) {
console.error('Error occurred:', error.message);
}
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
enableHighAccuracy: true
}); var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options); navigator.geolocation.clearWatch(watchId); Call clearWatch when you no longer need updates—continuous watching uses more battery.
The Position object contains information about the user’s location, including:
coords.latitude — latitude of the user’s location.coords.longitude — longitude of the user’s location.coords.altitude — altitude (if available, may be null).coords.accuracy — accuracy of the location data in meters.Additional properties such as coords.speed, coords.heading, and timestamp may be available on supported devices.
The PositionError object provides information about errors encountered while retrieving the location. Common error codes include:
Handle errors to provide appropriate feedback to users:
function errorCallback(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.error('User denied the request for geolocation.');
break;
case error.POSITION_UNAVAILABLE:
console.error('Location information is unavailable.');
break;
case error.TIMEOUT:
console.error('The request to get user location timed out.');
break;
default:
console.error('An unknown error occurred.');
break;
}
} Accessing geolocation data requires user permission. Browsers typically prompt users to allow or deny access. It’s important to respect user privacy and use location data responsibly. Inform users why location access is required and how it will be used.
Only request location after a user action (such as clicking “Find near me”)—never on page load without context. Sites must be served over HTTPS (or localhost) for geolocation to work in modern browsers.
| Task | Code |
|---|---|
| One-time location | navigator.geolocation.getCurrentPosition(ok, err) |
| Live tracking | var id = navigator.geolocation.watchPosition(ok, err) |
| Stop tracking | navigator.geolocation.clearWatch(id) |
| Read latitude | position.coords.latitude |
| High accuracy | { enableHighAccuracy: true } |
| Feature detect | if (navigator.geolocation) { ... } |
Five short examples from a basic read to a full page. Try It Yourself demos use plain HTML with no CSS. Allow location when the browser prompts you.
navigator.geolocation.getCurrentPosition(function (pos) {
console.log(pos.coords.latitude, pos.coords.longitude);
}); The browser shows a permission dialog the first time your site requests location.
navigator.geolocation.getCurrentPosition(ok, err, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 60000
}); maximumAge lets the browser return a recent cached fix instead of waiting for a fresh GPS lock.
var watchId = navigator.geolocation.watchPosition(function (pos) {
console.log('Updated:', pos.coords.latitude);
});
// Later:
navigator.geolocation.clearWatch(watchId); Ideal for turn-by-turn navigation or live map markers. Always call clearWatch when done.
navigator.geolocation.getCurrentPosition(
function (pos) { /* success */ },
function (err) {
if (err.code === 1) alert('Please allow location access.');
else if (err.code === 3) alert('Timed out — try again.');
}
); Show friendly UI when the user blocks location—offer a manual fallback.
Simple page that gets the current location and displays it when the user clicks a button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geolocation Example</title>
</head>
<body>
<h1>Geolocation Example</h1>
<button id="get-location">Get Location</button>
<p id="location"></p>
<script>
document.getElementById('get-location').onclick = function () {
navigator.geolocation.getCurrentPosition(
function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
document.getElementById('location').textContent =
'Latitude: ' + lat + ', Longitude: ' + lng;
},
function (error) {
document.getElementById('location').textContent =
'Error: ' + error.message;
}
);
};
</script>
</body>
</html> Matches the reference tutorial pattern: user gesture → permission → display coordinates.
navigator.geolocation is supported in all modern browsers. It requires a secure context (HTTPS or localhost).
navigator.geolocation is supported in all modern browsers. It requires a secure context (HTTPS or localhost).
Bottom line: Widely available on mobile and desktop. Always feature-detect with if (navigator.geolocation) and handle denied permissions gracefully.
The Geolocation API provides a robust way to incorporate location-based features into web applications. By understanding how to request and handle location data, you can create dynamic and responsive experiences tailored to the user’s location.
Always ensure to handle user permissions and data with care to maintain trust and provide valuable functionalities. Next, learn one-way server push with Server-Sent Events.
JS API.
EntryUser must allow.
PrivacyLat & lng.
DataLive updates.
TrackingRequired.
SecureYou can pass coordinates to map services without storing them. For example, open Google Maps with https://www.google.com/maps?q= plus latitude and longitude—no API key needed for a simple link.
Click Get Location, allow the browser prompt, and see your latitude and longitude—plain HTML, no CSS.
5 people found this page helpful