Loading...

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
HTML Code
<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

  1. Serve the page (some browsers restrict file:// APIs)
  2. Click the button and accept/deny permission
  3. Confirm your UI handles both outcomes
  4. 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

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
3
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 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