HTML Geolocation
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The Geolocation API is used to retrieve the user's location, so that it can for example be used to display their position using a mapping API. This article explains the basics of how to use it.
The Geolocation is use to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.
Different ways to access location
The developer can now access this location information in a couple of different ways:
1. Geolocation.getCurrentPosition(): Retrieves the device's current location.
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
2. Geolocation.watchPosition(): Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location.
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Note: clearWatch() method to stop watching the user's location.
Error Handling
The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a GeolocationPositionError object instance as its first parameter.
Syntax:
getCurrentPosition(successCallback, errorCallback, options)
watchPosition(successCallback, errorCallback, options)
How to use:
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,errorHandle);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function errorHandle() {
x.innerHTML = "Something went wrong please try again"
}
</script>