The HTML Geolocation API allows users to share their location with web applications. This is widely used for mapping, finding nearby points of interest, and navigation.
To protect user privacy, the location is never available without the user's explicit approval. Additionally, this API is only available on secure contexts (HTTPS).
The API is accessed through the navigator.geolocation object. The most common method is getCurrentPosition(), which retrieves the user's latitude and longitude.
<button onclick="getLocation()"> Get Coordinates </button>
<p id="demo"> </p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function success(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<b>Longitude: " + position.coords.longitude;
}
function error() {
x.innerHTML = "Unable to retrieve your lo
}
</script>
The getCurrentPosition() method accepts a second function to handle errors. Using a switch statement allows you to provide specific feedback based on the failure reason.
<script>
function error(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
</script>
On success, the API returns a Coordinates object. Some properties are always available, while others depend on the device's hardware (like GPS).
| Property | Description |
|---|---|
| coords.latitude | The latitude as a decimal (Always). |
| coords.longitude | The longitude as a decimal (Always). |
| coords.accuracy | The accuracy level of the position (Always). |
| coords.altitude | Altitude in meters above sea level (If available). |
| coords.speed | The speed in meters per second (If available). |
| timestamp | The date/time of the response. |
For apps that require movement tracking (like turn-by-turn navigation), use watchPosition(). It updates the location automatically as the user moves.
watchPosition():Returns the current position and continues to return updated data.
clearWatch():Stops the watchPosition() method.
<script>
var watchID = navigator.geolocation.watchPosition(success, error);
// To stop tracking later:
// navigator.geolocation.clearWatch(watchID);
</script>
| API | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| Geolocation | 5.0 | 12.0 | 3.5 | 5.0 | 10.6 |