-
Hajipur, Bihar, 844101
The HTML Geolocation API allows your website to request the user’s current location. It can detect latitude, longitude and in some cases speed, accuracy and altitude. This feature is widely used in map applications, delivery tracking, ride-booking, weather updates and check-in systems. The browser always asks for permission before sharing location, so it is safe and privacy-controlled. In this chapter, you will learn how the Geolocation API works, how to request location, how to handle errors and how to watch continuous location updates.
The Geolocation API is a browser-based interface that allows JavaScript to access the device’s GPS or network-based location data. HTML itself does not track location, but JavaScript uses the browser’s built-in API through the navigator.geolocation object.
Get user’s current location
Track live movement
Show map positions
Use for delivery, rides and check-in
Works on phones, laptops and tablets
Because the browser manages permissions, the user is always in control.
Before using the API, check if the browser supports it. This prevents errors on older browsers.
<script>
if ("geolocation" in navigator) {
console.log("Geolocation supported");
} else {
console.log("Geolocation not supported");
}
</script>
If supported, you can safely request location.
The most common method is getCurrentPosition(). It fetches the location only once.
<button onclick="getLocation()">Get Location</button>
<p id="output"></p>
<script>
function getLocation() {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(pos) {
document.getElementById("output").textContent =
"Latitude: " + pos.coords.latitude +
" | Longitude: " + pos.coords.longitude;
}
function showError(err) {
document.getElementById("output").textContent = err.message;
}
</script>
When the user clicks the button, the browser shows a permission popup. If the user allows it, you get coordinates.
The pos object contains several useful properties:
latitude
longitude
accuracy – meters
altitude – optional
speed – optional
heading – direction in degrees
pos.coords.latitude
pos.coords.longitude
pos.coords.accuracy
Accuracy tells you how close the reading is to the real location.
The Geolocation API produces different error messages. Handling them helps you guide the user.
1 → Permission denied
2 → Position unavailable
3 → Timeout
function showError(error) {
if (error.code === 1) {
alert("Please enable location permissions.");
} else if (error.code === 2) {
alert("Location unavailable.");
} else if (error.code === 3) {
alert("Request timed out.");
}
}
This improves the user experience.
Sometimes you need continuous location tracking, such as for delivery apps, running trackers or live navigation. For this, use watchPosition().
<button onclick="startTracking()">Start Tracking</button>
<p id="live"></p>
<script>
let watchId;
function startTracking() {
watchId = navigator.geolocation.watchPosition(updateLive);
}
function updateLive(pos) {
document.getElementById("live").textContent =
"Live Latitude: " + pos.coords.latitude +
" | Live Longitude: " + pos.coords.longitude;
}
</script>
This keeps updating coordinates as the user moves.
Tracking continues until you stop it manually. Use clearWatch().
<button onclick="stopTracking()">Stop Tracking</button>
<script>
function stopTracking() {
navigator.geolocation.clearWatch(watchId);
}
</script>
Stopping tracking reduces battery usage and prevents unnecessary updates.
You can pass options to improve accuracy. High accuracy uses GPS directly, which gives better results but may use more battery.
navigator.geolocation.getCurrentPosition(showPosition, showError, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
enableHighAccuracy: true → better GPS
timeout → max waiting time
maximumAge → avoid using old cached data
You can show the coordinates on Google Maps using a basic link.
<script>
function showPosition(pos) {
let lat = pos.coords.latitude;
let lon = pos.coords.longitude;
window.open(
"https://www.google.com/maps?q=" + lat + "," + lon,
"_blank"
);
}
</script>
This opens the exact location in a new tab.
You can load Google Maps inside an iframe with coordinates.
<iframe id="map" width="300" height="300"></iframe>
<script>
function showPosition(pos) {
let lat = pos.coords.latitude;
let lon = pos.coords.longitude;
document.getElementById("map").src =
"https://maps.google.com/maps?q=" + lat + "," + lon + "&z=15&output=embed";
}
</script>
Your page shows an interactive map with the user’s position.
Track delivery partners moving on the map.
Drivers and users share their live location.
Show weather based on current location.
Employees check-in from fixed locations.
Locate nearby events or stalls.
Record running or cycling paths using live tracking.
The Geolocation API is the foundation of these real-world features.
Browsers take strict steps to protect location data.
User must always grant permission
HTTPS is required on most browsers
Permission can be blocked anytime
Apps must clearly explain why location is needed
This makes the API safe for users.
Here is a simple UI that displays location in text and shows it on a map.
<button onclick="locate()">Show My Location</button>
<p id="details"></p>
<iframe id="map" width="300" height="300"></iframe>
<script>
function locate() {
navigator.geolocation.getCurrentPosition(success, showError);
}
function success(pos) {
let lat = pos.coords.latitude;
let lon = pos.coords.longitude;
document.getElementById("details").textContent =
"Latitude: " + lat + " | Longitude: " + lon;
document.getElementById("map").src =
"https://maps.google.com/maps?q=" + lat + "," + lon + "&z=15&output=embed";
}
function showError(err) {
document.getElementById("details").textContent = err.message;
}
</script>
This combines everything you learned in this chapter.
The Geolocation API allows websites to request and track user location safely. You learned how to check browser support, get current position, handle errors, track live movement, improve accuracy and display coordinates on Google Maps. With these tools, you can build features like delivery tracking, ride apps, check-ins and weather systems. Geolocation is one of the most useful browser APIs in modern web development.
Q1. Use navigator.geolocation.getCurrentPosition() to show latitude and longitude.
Q2. Add a button that fetches location on click.
Q3. Display an error message if the user denies location permission.
Q4. Use watchPosition() to track real-time movement.
Q5. Display a live Google Maps link using the coordinates.
Q6. Show coordinates only when accessed over HTTPS.
Q7. Log errors for debugging using showError() function.
Q8. Update a <div> with coordinates every 5 seconds using watchPosition.
Q9. Create a fallback message for unsupported browsers.
Q10. Use clearWatch() to stop location tracking with a "Stop" button.