HTML Geolocation API

Access the geographical coordinates of the user with their consent.

The HTML Geolocation API is used to get the geographical position of a user. For privacy reasons, the position is not available unless the user approves it.

Use navigator.geolocation.getCurrentPosition() to retrieve latitude and longitude.

Key Takeaways: HTML Geolocation API

Mastering HTML Geolocation API helps you write clean and reliable HTML code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

HTML Geolocation API Code Example

HTML
<button onclick="getLocation()">Get Location</button>
<p id="demo"></p>
<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((pos) => {
      document.getElementById("demo").innerText = "Latitude: " + pos.coords.latitude;
    });
  }
}
</script>
Output
Retrieves user GPS latitude upon click
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services