HTML Geolocation
Previously, Web Storage remembered small key/value strings with localStorage and sessionStorage. This lesson leaves saving strings and introduces Geolocation: reading the device’s approximate latitude and longitude through navigator.geolocation — only after the user grants permission. Your HTML page still loads a script; that script asks for location. Scope stays practical — one-shot read, watch/clear, and polite denial — not map SDKs, analytics tracking products, or a backend geo database course.
Why geolocation in an HTML course
Beginners often build a “near me” button or show coordinates on screen. Geolocation is the common first browser API for that. After web storage’s “JS remembers strings,” this lesson’s split is different: HTML owns the page shell and the button; JS owns asking for coordinates for that origin. You only need getCurrentPosition, knowing watchPosition exists, and handling permission denied — enough to use location safely at intro level without diving into map tiles, geocoding, or continuous background tracking.
Direct answer
1) From JavaScript on your page, call navigator.geolocation.getCurrentPosition(success, error).
2) On success, read position.coords.latitude and position.coords.longitude.
3) Prefer a user click before you ask — browsers show a permission prompt.
4) Use watchPosition only when you need ongoing updates; stop with clearWatch(id).
5) There is no HTML <geolocation> tag — location is script-driven, like Web Storage.
6) If the user denies or the device has no fix, call your error path and keep the page useful. Never surprise users or collect location without a clear purpose.
📊 getCurrentPosition vs watchPosition
| Topic | getCurrentPosition | watchPosition |
|---|---|---|
| Typical use | One-shot “where am I now” | Ongoing updates while watching |
| Callback pattern | success once (plus optional error) | success may fire repeatedly |
| Stop watching | Not needed (single read) | clearWatch(watchId) |
| Beginner fit | Share-location button | Live tracking demos (careful) |
| Permission | Still required | Still required |
| This course depth | Intro focus | Short demo + clearWatch only |
Tiny getCurrentPosition demo
A button click can request the current position and print latitude/longitude. If the browser lacks the API or the user denies, show a calm message instead of crashing.
<button id="loc" type="button">Share location</button>
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
document.getElementById("loc").onclick = function () {
if (!navigator.geolocation) {
out.textContent = "No geolocation support";
return;
}
out.textContent = "Waiting for permission…";
navigator.geolocation.getCurrentPosition(
function (pos) {
out.textContent =
pos.coords.latitude + ", " + pos.coords.longitude;
},
function () {
out.textContent = "Permission denied or unavailable";
}
);
};
</script>
Reading the getCurrentPosition calls
navigator.geolocationis the browser entry point (may be missing on old or locked-down clients)getCurrentPosition(success, error)asks once; the browser may show a permission dialogpos.coords.latitude/longitudeare the usual numbers beginners print first- Feature-detect with
if (!navigator.geolocation)before calling - Error callback covers denial, timeout, and unavailable position — keep UI calm
- Prefer HTTPS (or localhost) in real demos; some browsers restrict insecure contexts
- Unlike Web Storage, nothing is “saved” here — you only read a snapshot when allowed
watchPosition for ongoing updates
watchPosition uses a similar success/error shape but can fire again as the device moves. Store the returned id and call clearWatch when you are done — do not leave watches running forever in intro demos.
<button id="start" type="button">Watch location</button>
<button id="stop" type="button">Stop watching</button>
<pre id="live"></pre>
<script>
const live = document.getElementById("live");
let watchId = null;
document.getElementById("start").onclick = function () {
if (!navigator.geolocation) {
live.textContent = "No geolocation support";
return;
}
if (watchId !== null) {
return;
}
live.textContent = "Watching…";
watchId = navigator.geolocation.watchPosition(
function (pos) {
live.textContent =
pos.coords.latitude + ", " + pos.coords.longitude;
},
function () {
live.textContent = "Permission denied or unavailable";
watchId = null;
}
);
};
document.getElementById("stop").onclick = function () {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
live.textContent = "Stopped watching";
}
};
</script>
Reading the watchPosition idea
- Same permission model as
getCurrentPosition - Success may run more than once while the watch is active
clearWatch(watchId)stops updates — always offer a stop for demos- Still not a map library; you only receive coordinates
- Still not Web Storage — coordinates are not automatically persisted as keys
- Choose get vs watch by how often you need a fix, not by which name sounds fancier
- Next optional lesson: drag and drop moves elements with pointer events — a different JS/HTML capability
Choosing when to ask
- User clicked “Share location” or “Find near me”: good time to call
getCurrentPosition - Page load with no context: usually bad — feels invasive
- Need continuous movement updates:
watchPosition+ visible stop control - Saving a theme preference: that was Web Storage (previous lesson), not geolocation
- Full map product / routing / geocoding: beyond this HTML intro — use later map tooling
- Tracking users silently for ads: out of scope and a privacy anti-pattern
Practice — ask politely for a fix
- Paste the getCurrentPosition demo; click the button; accept or deny the prompt.
- Confirm the
<pre>shows either coordinates or a calm denial message. - Paste the watchPosition demo; start watching; then click stop — confirm “Stopped watching.”
- (Optional) Deny permission and confirm the page still works without throwing.
- Write one sentence: Web Storage saves strings; Geolocation reads coordinates with permission.
- Serve over http(s) rather than relying only on
file://if the browser blocks the API. - Peek ahead: drag and drop lets users drag HTML elements — not location.
Easy mistakes
- Expecting an HTML
<geolocation>tag instead ofnavigator.geolocation - Calling geolocation on every page load without a user action or clear purpose
- Ignoring the error callback when permission is denied
- Confusing Geolocation with Web Storage (location ≠ saved key/value strings)
- Leaving
watchPositionrunning with noclearWatch - Assuming every device returns precise GPS outdoors (accuracy varies)
- Treating this intro as a full maps, tracking, or privacy-law curriculum
Summary
- Geolocation is a permissioned JavaScript API on
navigator.geolocation getCurrentPositionreads one fix;watchPosition+clearWatchhandle ongoing updates- HTML provides the UI; script asks only after a clear user action when possible
- Handle denial and missing support kindly
- Web Storage was remembered strings; this lesson is permitted coordinates
- Next: HTML drag and drop for moving elements with the pointer
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top