On this page10 sections
Lecture 043: Geolocation API
| Category | 8: Web APIs |
| Lecture | 043 of 048 |
| Estimated video length | 10 min |
| Target | HTML5 · any modern browser |
| Level | Beginner |
A Web API is a feature the browser gives JavaScript. The Geolocation API asks "where is this device?" With the visitor's permission, it returns a latitude and longitude, which are used for maps, "stores near me" and weather.
Learning Objectives
- Explain what a Web API is
- Get the visitor's position with
navigator.geolocation.getCurrentPosition() - Handle permission refusals and errors
- Track movement with
watchPosition()
1. Permission First
The browser always asks the visitor before sharing their location, and it only works on
secure pages (https://, or a file opened from your own computer). If they say no, your
code gets an error, so always handle it.
These examples can't run inside this page's preview box, because previews are sandboxed for safety and location is blocked there. Copy the code into a file such as
location.htmland open it in your browser.
2. Getting the Position
<button type="button" onclick="locate()">Where am I?</button>
<p id="out"></p>
<script>
function locate() {
const out = document.getElementById('out');
if (!('geolocation' in navigator)) {
out.textContent = 'Geolocation is not supported by this browser.';
return;
}
out.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
const { latitude, longitude, accuracy } = position.coords;
document.getElementById('out').textContent =
`Latitude ${latitude.toFixed(4)}, longitude ${longitude.toFixed(4)} (within ${Math.round(accuracy)} m)`;
}
function showError(error) {
const messages = {
1: 'You refused to share your location.',
2: 'Your position is unavailable.',
3: 'Finding your position took too long.',
};
document.getElementById('out').textContent = messages[error.code] || 'Unknown error.';
}
</script>getCurrentPosition takes a success function and an error function. It doesn't
return the answer straight away, because finding the position takes time.
3. What You Get Back
| Property | Meaning |
|---|---|
coords.latitude / coords.longitude | Position in degrees |
coords.accuracy | How accurate, in metres |
coords.altitude | Height above sea level (if available) |
coords.speed / coords.heading | Speed and direction (if moving) |
timestamp | When the position was measured |
4. Showing It on a Map
Open the coordinates in Google Maps:
<script>
function showPosition(position) {
const { latitude, longitude } = position.coords;
const url = `https://www.google.com/maps?q=${latitude},${longitude}`;
document.getElementById('out').innerHTML = `<a href="${url}" target="_blank" rel="noopener">Open my location on a map</a>`;
}
</script>5. Tracking Movement
watchPosition calls your function every time the position changes, which is useful for
running or delivery apps. Stop it with clearWatch.
<script>
const watchId = navigator.geolocation.watchPosition(showPosition, showError, { enableHighAccuracy: true });
// later…
navigator.geolocation.clearWatch(watchId);
</script>Common Beginner Mistakes
1. Not handling errors. Many visitors say no. Always pass an error function.
2. Asking as soon as the page loads. Ask when the visitor presses a button, so they understand why.
3. Testing on plain http://. Geolocation needs https:// (or a local file).
Practice Questions
- What is a Web API?
- Which object holds the Geolocation API?
- What two functions does
getCurrentPositiontake? - Which property tells you how accurate the position is?
- Which method keeps reporting new positions?
- Why is it better to ask for the location after a button click?
Practice Answers
- A feature the browser provides to JavaScript, such as location, storage or drag and drop.
navigator.geolocation- A success function and an error function.
coords.accuracywatchPosition()- Visitors understand why you're asking, so they're more likely to agree.
Key Takeaways
- Geolocation needs the visitor's permission and a secure page.
getCurrentPosition(success, error)givescoords.latitudeandcoords.longitude.- Always handle errors;
watchPositiontracks movement.