
HTML
HTML Head
HTML Forms
HTML Graphics
HTML Media
HTML APIs
HTML Geolocation API
The Geolocation API provides a way to get a user’s physical location using JavaScript. It can detect coordinates like latitude, longitude, altitude, and more (depending on device support). This data can be used in various web applications.
Note: For privacy reasons, the user must allow the browser to share their location. Most browsers will ask for permission before returning any location data.
Get the User’s Location
To get the user’s position, the method used is:
navigator.geolocation: Accesses the geolocation object
getCurrentPosition(): Triggers the request
successFunction: Called if the location is successfully retrieved
Example: Get Current Position
It displays the user’s coordinates when the button is clicked (if permission is granted).
Handling Errors
If something goes wrong (e.g., the user denies permission), errors can be handled using a second argument in getCurrentPosition().
Here’s how to use it:
Geolocation Methods
getCurrentPosition(): Retrieves the current location once.
watchPosition(): Continuously tracks the user’s location as it changes.
clearWatch(): Stops the location tracking started with watchPosition().
watchPosition() is helpful for real-time tracking, like in fitness or delivery apps.
Geolocation Object Properties
The position.coords object contains:
- latitude – Distance north or south from the Earth’s equator
- longitude – Position east or west from the prime meridian
- accuracy – Estimated location accuracy in meters
- altitude – Height above sea level (if available)
- altitudeAccuracy – Accuracy level of the altitude value
- heading – Direction of movement in degrees (0–360)
- speed – Movement speed in meters per second
- timestamp – The time (in milliseconds) when the location was recorded
Note: Not all properties are supported or available on all devices. Some values like altitude, heading, or speed may return null depending on the device or browser capabilities.
The Geolocation API makes it easy to get the user’s position through JavaScript. It supports both one-time and real-time tracking, making it useful for maps, delivery systems, or any location-based web app.
