Web API Geolocation enables the users to use the E-commerce websites that do the same for getting the location of the user to deliver products, News Web apps need the user's location to serve the news relevant and based on the user's location. Many apps, nowadays, request the user to access the location of the device. Websites make use of this Geolocation Web API which provides certain methods and properties that we can use in our web application and get the location details of the user like latitude, longitude, altitude, and velocity of the device.
Concept and Usage
Navigator is the global object containing services that we can use and get the user and browser environment details like OS details, network details, and location details.
Concepts
| Descriptions
|
---|
navigator.geolocation | The navigator.geolocation property facilitates to be provided by the navigator global object. Here, navigator.geolocation returns us a Geolocation object, which we will use this object to call the Geolocation Web API methods to retrieve the location of a user.
|
Geolocation.getCurrentPosition() | It has a return value undefined. In the Geolocation.getCurrentPosition method there are three parameters these are success, error, and options.
|
Geolocation.watchPosition() | In the Geolocation.watchPosition method there are three parameters success, error, and options. It Returns the current position of the device and sets a callback function which will be called every time the device changes its position and returns an ID.
|
GeolocationPosition | GeoLocationPosition represents the properties for determining the location of the device as well as the timestamp of the location retrieved.
|
GeolocationPositionError | This provides us the properties to get the Information about the error raised while getting the location of the device.
|
Interfaces in Geolocation Web API
GeolocationCoordinates Interface
This interface represents the properties to get the location details like altitude, speed, latitude, longitude, direction, and details about the accuracy of the returned data.
Interfaces
| Descriptions
|
---|
latitude | GeolocationCoordinates.latitude returns a double value representing the latitude of the current device. |
longitude | GeolocationCoordinates.longitude returns a double value representing the longitude of the current device. |
altitude | GeolocationCoordinates.altitude returns a double value representing the height of the device from the sea level. If the underlying machine cannot provide it, it returns null. |
speed | GeolocationCoordinates.speed returns the current velocity with which the device is traveling, If the underlying machine cannot provide it, it returns null. |
heading | GeolocationCoordinates.heading returns the direction towards which the device is traveling, the measurements are considered taking true north as the reference. If the speed of the device is zero, then it returns NaN. If the underlying machine cannot provide this functionality, then it returns null. |
accuracy | GeolocationCoordinates.accuracy returns a double value which represents the accuracy of latitude and longitude in meters. |
altitudeAccuracy | GeolocationCoordinates.altitudeAccuracy returns a double value which represents the accuracy of the altitude of the device in meters. If the underlying machine cannot provide this functionality, then it returns null. |
GeoLocationPosition Interface
GeoLocationPosition Interface represents the properties for determining the location of the device as well as the timestamp of the location retrieved.
Interfaces
| Descriptions
|
---|
coords | In the property coords, GeolocationPosition.coords represents the GeolocationCoordinates object containing details like speed, accuracy, latitude, longitude, altitude, etc. It returns the object containing GeolocationCoordinates properties. |
timestamp | In the property timestamp, GeolocationPosition.timestamp returns the time stamp in milliseconds at which the location was retrieved. |
GeolocationPositionError Interface
This Interface provides us the properties to get the Information about the error raised while getting the location of the device.
Interfaces
| Descriptions
|
---|
code | In the property code, GeolocationPositionError.code returns an unsigned short integer which specifies the error code where error code '1' specifies the error raised during location request due to permission policies, error code '2' specifies the error raised due to some internal error in the process of acquiring location, and error code '3' specifies the error raised when the information is still not received to the browser before the timeout specified. |
message | In the property message, the GeolocationPositionError.message returns the description of an error that occurred in the form of a string. |
GeoLocation Interface
This Interface provides the methods to obtain the location of the device as well as to get the location dynamically as the device changes it's position.
Interfaces
| Descriptions
|
---|
getCurrentPosition() | The navigator.geolocation.getCurrentPosition(success_function, error_handler, options) Returns the GeoLocationPosition object as data. |
getWatchPosition() | It will return the current position of the device (GeolocationPosition Object) and set a callback function which will be called every time the device changes its position and returns an ID. |
clearWatch() | It clears the callback function that we have registered using getWatchPosition(). It takes an ID as the input and clears the watch function associated with that ID. |
Example 1: In this example, the browser will execute the callback function that needs to be executed when the location request is successful.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Geo Location Web API</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<button onclick="getlocation()">
Get Location Details
</button>
<p id="location_details"></p>
<script>
function getlocation() {
var geo_loc_obj = navigator.geolocation;
var geo_position_object = geo_loc_obj
.getCurrentPosition(displaylocation, error_handler, options);
}
const options = {
enableHighAccuracy: true,
timeout: 1000,
maximumAge: 0,
};
function displaylocation(geo_position_object) {
var latitude =
geo_position_object.coords.latitude;
var longitude =
geo_position_object.coords.longitude;
var accuracy =
geo_position_object.coords.accuracy;
var altitude =
geo_position_object.coords.altitude;
var speed =
geo_position_object.coords.speed;
var altitudeAccuracy =
geo_position_object.altitudeAccuracy;
var heading =
geo_position_object.heading;
document.getElementById("location_details")
.innerHTML = "Latitude : " + latitude + "<br>" +
"Longitude : " + longitude + "<br>" +
"Accuracy : " + accuracy + "<br>" +
"Altitude : " + altitude + "<br>" +
"Speed : " + speed + "<br>" +
"Altitude Accuracy : " + altitudeAccuracy + "<br>" +
"Heading : " + heading + "<br>"
}
function error_handler(geo_position_error_obj) {
const error_messg =
geo_position_error_obj.message;
const error_code =
geo_position_error_obj.code;
console.log(
"Location access failed. " +
"The error code and descriptions are:")
console.log("error_code " + error_code);
console.log("error_message " + error_messg);
}
</script>
</body>
</html>
Output :
Demonstration of Successful Geolocation Retrieval.
Example 2: In this example, when a user rejects the location request the browser will execute the callback function that needs to be executed when the location request fails due to some reason, here we get the output as "1" and the description of the error message as "user rejected the request".
HTML
<!DOCTYPE html>
<html>
<head>
<title>Geo Location Web API</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<button onclick="getlocation()">
Get Location Details
</button>
<p id="location_details"></p>
<script>
function getlocation() {
var geo_loc_obj = navigator.geolocation;
var geo_position_object = geo_loc_obj
.getCurrentPosition(
displaylocation, error_handler, options);
}
const options = {
enableHighAccuracy: true,
timeout: 1000,
maximumAge: 0,
};
function displaylocation(geo_position_object) {
var latitude =
geo_position_object.coords.latitude;
var longitude =
geo_position_object.coords.longitude;
var accuracy =
geo_position_object.coords.accuracy;
var altitude =
geo_position_object.coords.altitude;
var speed =
geo_position_object.coords.speed;
var altitudeAccuracy =
geo_position_object.altitudeAccuracy;
var heading =
geo_position_object.heading;
document.getElementById("location_details")
.innerHTML = "Latitude : " + latitude + "<br>" +
"Longitude : " + longitude + "<br>" +
"Accuracy : " + accuracy + "<br>" +
"Altitude : " + altitude + "<br>" +
"Speed : " + speed + "<br>" +
"Altitude Accuracy : " + altitudeAccuracy + "<br>" +
"Heading : " + heading + "<br>"
}
function error_handler(geo_position_error_obj) {
const error_messg =
geo_position_error_obj.message;
const error_code =
geo_position_error_obj.code;
console.log(
"Location access failed. "+
"The error code and descriptions are:")
console.log("error_code " + error_code);
console.log("error_message " + error_messg);
}
</script>
</body>
</html>
Output:
Demonstration of Location Retrieval Failure due to the user rejecting the request.Browser Support
- Google Chrome 5.0 & above
- Microsoft Edge 12.0 & above
- Mozilla Firefox 3.5 & above
- Opera 10.6 & above
- Safari 5.0 & above
Similar Reads
HTML Geolocation
The HTML Geolocation is used to get the geographical position of a user. Due to privacy concerns, this position requires user approval. Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, and restaurants,
5 min read
HTML Geolocation clearWatch() Method
In this article, we will learn the HTML geolocation clearWatch() method and its implementation. The clearWatch() method is used to cancel the currently running watchPosition() call and removes the location or errors generated as a result of the previous call. Syntax: navigator.geolocation.clearWatch
2 min read
Cypress - location() Method
The location() method allows you to access the window.location object of the current page. With this method, you can assert or manipulate the URL's components, such as checking if the user is on the correct page, verifying query parameters, or ensuring that the URL changes as expected when navigatin
4 min read
HTML DOM Location assign( ) Method
The Location assign() method is used for loading a new document. It can also be used for loading a new document but the difference between these two methods is that the replace() method removes the URL of the current document from the document history and therefore it is not possible to navigate bac
1 min read
HTTP headers | Location
The HTTP Location header is a response header that is used under 2 circumstances to ask a browser to redirect a URL (status code 3xx) or provide information about the location of a newly created resource (status code of 201). Its usage is often confused with another HTTP Header which is HTTP Content
2 min read
Geolocator in Flutter
It is extremely common in apps like payment, maps, and e-commerce to access the location of users. Location accessing is also vastly used in item tracking. In this article, we will be looking at the following - Get the permissionAccess the last location of the deviceAccess the current locationAccess
3 min read
How to get city name by using geolocation ?
In this article, we will learn how to get the city name of the user using reverse geocoding. We will be using a 3rd party API service provider(Location IQ) to help us to convert the latitude and longitude we receive into an address. Steps: Get user coordinates. Get city name. Note: A LocationIQ acco
2 min read
PHP | timezone_location_get() Function
The timezone_location_get() function is an inbuilt function in PHP which is used to return the location information for the given timezone. The date time object is sent as a parameter to the timezone_location_get() function and it returns location information related to the timezone on success or Fa
2 min read
AngularJS $location Service
The $location in AngularJS basically uses a window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS. There are various methods in the $location s
4 min read
Web Window API | Window locationbar property
In Web API Window.locationbar property returns the object of locationbar, for which we can check the visibility. Syntax: objectReference = window.locationbar Example: Check the visibility. <!DOCTYPE html> <html> <head> <title> Window locationbar property </title> <st
1 min read