The HTML Geolocation API retrieves the geographical position of a user’s device, but this information is only accessible if the user grants permission due to privacy considerations.
Note that geolocation is most accurate on devices equipped with GPS, such as smartphones. |
The numbers in the table indicate the earliest browser version that fully supports the Geolocation feature.
Note that starting from Chrome 50, the Geolocation API will only function on secure contexts like HTTPS. Requests to retrieve a user’s location will not work on non-secure origins such as HTTP. |
The getCurrentPosition() method retrieves the user’s position.
The example below demonstrates how to retrieve and display the latitude and longitude of the user’s position:
<script> const x = document.getElementById(“demo”); function getLocation() { function showPosition(position) { |
Explanation of the example:
This example is a basic Geolocation script without error handling.
The second parameter of the getCurrentPosition() method is used to specify a function that runs if there is an error while attempting to retrieve the user’s location.
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; } } |
This page has demonstrated how to display a user’s position on a map.
Geolocation is also valuable for location-specific applications such as:
The getCurrentPosition() method returns an object on success, which always includes the latitude, longitude, and accuracy properties. Additional properties are returned if available.
Property |
Returns |
coords.latitude |
The latitude, always provided as a decimal number |
coords.longitude |
The longitude, always returned as a decimal number |
coords.accuracy |
The accuracy of the position, always provided |
coords.altitude |
The altitude above mean sea level in meters, returned if available |
coords.altitudeAccuracy |
The accuracy of the altitude of the position, returned if available |
coords.heading |
The heading in degrees clockwise from North, returned if available |
coords.speed |
The speed in meters per second, returned if available |
timestamp |
The date and time of the response, returned if available |
Additionally, the Geolocation object includes other useful methods:
The following example demonstrates the watchPosition() method. To test it, you’ll require a precise GPS device, such as a smartphone:
<script> const x = document.getElementById(“demo”); function getLocation() { |