Explain Geolocation API in HTML5
The HTML Geolocation API is used to get the geographical position of a user.
Since this can compromise privacy, the position is not available unless the user approves it.
Geolocation Object - Methods
- getCurrentPosition() - Returns the current position of the user.
- watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
- clearWatch() - Stops the watchPosition() method.
Return Data
- coords.latitude - The latitude as a decimal number. (always returned)
- coords.longitude - The longitude as a decimal number. (always returned)
- coords.accuracy - The accuracy of position. (always returned)
- coords.altitude - The altitude in meters above the mean sea level. (returned if available)
- coords.altitudeAccuracy - The altitude accuracy of position. (returned if available)
- coords.heading - The heading as degrees clockwise from North. (returned if available)
- coords.speed - The speed in meters per second. (returned if available)
- timestamp - The date/time of the response. (returned if available)
Handling Errors and Rejections
function showError(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;
}
}
Example
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
</script>