SyntaxStudy
Sign Up
HTML Intermediate 4 min read

Geolocation API

Geolocation API

The Geolocation API lets web apps access the user's geographic location with their permission.

Example
<button onclick="locate()">Get Location</button>
<p id="loc"></p>
<script>
function locate() {
  if (!navigator.geolocation) {
    document.getElementById("loc").textContent = "Not supported";
    return;
  }
  navigator.geolocation.getCurrentPosition(
    pos => {
      const { latitude, longitude, accuracy } = pos.coords;
      document.getElementById("loc").textContent =
        `${latitude.toFixed(4)}, ${longitude.toFixed(4)} (±${accuracy}m)`;
    },
    err => document.getElementById("loc").textContent = "Error: " + err.message
  );
}
</script>
Pro Tip

Geolocation requires HTTPS — it will not work on plain HTTP.