HTML Geolocation
The Geolocation API lets a page ask the browser for the visitor's location, with their permission.
What It Is Used For
- Showing the nearest branch of a shop or bank
- Filling in the delivery address on a food app
- Showing the local weather
- Tracking a run or a bike ride
The browser always asks the user first. Nobody's location is shared without them clicking "Allow".
Rules Before You Start
| Rule | Why |
|---|---|
The page must use https (or localhost while testing) | Location is private data |
| The user must allow it | A permission box appears the first time |
| Ask only after a click | A pop-up on page load looks suspicious, and many users click "Block" |
| Always handle errors | The user can say no, or the device may not find a signal |
Getting the Position
navigator.geolocation.getCurrentPosition() asks for the location once. You give it two functions: one for success and one for errors.
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="findMe()">Find my location</button>
<p id="out">Click the button.</p>
<script>
function findMe() {
const out = document.getElementById("out");
if (!("geolocation" in navigator)) {
out.innerHTML = "Sorry, this browser does not support geolocation.";
return;
}
out.innerHTML = "Looking for you...";
navigator.geolocation.getCurrentPosition(success, failure);
}
function success(position) {
const lat = position.coords.latitude.toFixed(4);
const lon = position.coords.longitude.toFixed(4);
document.getElementById("out").innerHTML =
"Latitude: " + lat + "<br>Longitude: " + lon;
}
function failure(error) {
document.getElementById("out").innerHTML = "Could not get location: " + error.message;
}
</script>
</body>
</html>Try it Yourself »If Ayesha runs this on her phone in Karachi and clicks Allow, she sees something like:
Latitude: 24.9056 Longitude: 67.0822
The Try it editor runs code in a locked-down frame that is not allowed to ask for location, so there you will see the error message. That is useful too: it shows the error handling working. Put the page on an https website (or open it from a local server) to see real numbers.
What the Position Contains
| Property | Meaning |
|---|---|
coords.latitude | North-south position in degrees |
coords.longitude | East-west position in degrees |
coords.accuracy | How exact it is, in metres |
coords.altitude | Height above sea level (often null) |
coords.speed | Speed in metres per second (often null) |
timestamp | When the position was measured |
Handling Errors
The error object has a code that tells you what went wrong:
| Code | Name | Meaning |
|---|---|---|
| 1 | PERMISSION_DENIED | The user clicked Block |
| 2 | POSITION_UNAVAILABLE | The device could not find its position |
| 3 | TIMEOUT | It took too long |
Example
function failure(error) {
let text;
if (error.code === error.PERMISSION_DENIED) {
text = "You blocked location. Please type your area instead.";
} else if (error.code === error.TIMEOUT) {
text = "This is taking too long. Please try again.";
} else {
text = "Your location could not be found.";
}
document.getElementById("out").innerHTML = text;
}Always give the user another way, such as typing their city or area.
Options
A third argument sets options:
Example
navigator.geolocation.getCurrentPosition(success, failure, {
enableHighAccuracy: true, // use GPS if possible (slower, uses more battery)
timeout: 10000, // give up after 10 seconds
maximumAge: 60000 // a position up to 1 minute old is fine
});Showing the Location on a Map
A simple way to show the result is a link to a map service with the coordinates in the address:
Example
function success(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const url = "https://www.google.com/maps?q=" + lat + "," + lon;
document.getElementById("out").innerHTML =
'<a href="' + url + '" target="_blank">Open my location on the map</a>';
}Following a Moving User
watchPosition() calls your function again every time the position changes. It returns an id, which you pass to clearWatch() to stop.
Example
const watchId = navigator.geolocation.watchPosition(success, failure);
// later, for example when the ride ends:
navigator.geolocation.clearWatch(watchId);Watching the position all the time uses a lot of battery. Stop it as soon as you no longer need it.
Respect Privacy
Tell users why you need their location, use it only for that, and do not save it without asking. In many countries, location is treated as personal data by law.
Exercise
Exercise
Which method asks for the visitor's location one time?
