HTML Geolocation
The HTML Geolocation API helps find where a user is located.
Locate the User's Position
The HTML Geolocation API helps obtain the user's geographic location.
Because of privacy concerns, the location isn't accessible unless the user gives permission..
Using HTML Geolocation
The getCurrentPosition()
function is employed to give back the user's location.
The following example provides the user's position's latitude and longitude:
Example explained:
- Check if Geolocation is supported
- If available, use the getCurrentPosition() function. If not, show a message to the user.
- When the getCurrentPosition() method works, it gives back a set of coordinates to the function you've chosen (showPosition).
- The showPosition() function displays the Latitude and Longitude.
The given example is a straightforward Geolocation script without any error handling.
Handling Errors and Rejections
The getCurrentPosition()
method has a second parameter that manages errors. It defines a function to execute if there's a problem getting the user's location:
Location-specific Information
This page has shown how to display a user's location on a map.
Geolocation is also handy for sharing location-specific information, such as:
- Current and accurate local details.
- Displaying nearby points of interest to the user.
- Step-by-step guidance using GPS.
The getCurrentPosition() Method - Return Data
When you use the getCurrentPosition()
method successfully, it gives you an object. This object always has information about latitude, longitude, and accuracy. If there's more information available, you'll also get other properties in the object.
Property | Returns |
---|---|
coords.latitude | The latitude is given as a decimal number (always provided). |
coords.longitude | The longitude is provided as a decimal number, and this value is always returned. |
coords.accuracy | Position accuracy (always provided) |
coords.altitude | The height in meters above the average ocean level (given if accessible). |
coords.altitudeAccuracy | Altitude accuracy of location (provided when accessible) |
coords.heading | The heading in degrees clockwise from North (provided if accessible). |
coords.speed | The rate of motion in meters per second (given if accessible). |
timestamp | If possible, the response includes the date and time it was provided. |
Geolocation Object - Other interesting Methods
The Geolocation object also offers additional interesting methods:
watchPosition()
- function gives you the user's current location and keeps updating it as they move, similar to how a car's GPS works.clearWatch()
- Stops thewatchPosition()
method.
Here's an instance of using the watchPosition()
method. To try this out, you'll require a precise GPS device such as a smartphone.