Geolocation API
The Geolocation API lets web apps access the user's geographic location with their permission.
The Geolocation API lets web apps access the user's geographic location with their permission.
<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>
Geolocation requires HTTPS — it will not work on plain HTTP.