HTML Geolocation
Maps and “near me” features may need the user’s location. Browsers expose Geolocation to JavaScript — only after permission.
Direct answer
Use navigator.geolocation.getCurrentPosition(success, error). There is no <geolocation> tag. Always explain why you ask, handle denial gracefully, and avoid surprising users.
Ask for position (requires permission)
html<button id="loc" type="button">Share location</button>
<pre id="out"></pre>
<script>
document.getElementById("loc").onclick = function () {
if (!navigator.geolocation) {
document.getElementById("out").textContent = "No geolocation support";
return;
}
navigator.geolocation.getCurrentPosition(function (pos) {
document.getElementById("out").textContent =
pos.coords.latitude + ", " + pos.coords.longitude;
}, function () {
document.getElementById("out").textContent = "Permission denied or unavailable";
});
};
</script>
Try it
- Serve the page (some browsers restrict file:// APIs)
- Click the button and accept/deny permission
- Confirm your UI handles both outcomes
- Never collect location without a clear purpose
Easy mistakes
- Calling geolocation on page load without context
- Ignoring errors when permission is denied
- Assuming every device will share precise GPS
Summary
- Geolocation is a permissioned JS API
- HTML provides the UI; script reads coordinates
- Handle denial kindly
- Privacy first
🧠 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