The Web Geolocation API allows your web application to access the user's physical location (latitude and longitude). This is incredibly useful for providing local services, mapping, or personalizing content based on where the visitor is.
Click the button below to detect your current physical location. Note: Your browser will ask for your explicit permission first.
The primary method is getCurrentPosition(). It takes a callback function
that runs when the coordinates are successfully retrieved.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
let lat = position.coords.latitude;
let long = position.coords.longitude;
console.log("Lat: " + lat + ", Long: " + long);
}
Geolocation is a sensitive feature. It can fail if the user rejects permission, if the signal is weak, or if the device doesn't have a GPS. You can handle these errors using a second callback function.
navigator.geolocation.getCurrentPosition(success, error);
function error(err) {
switch(err.code) {
case err.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case err.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
}
}
If you need to track a moving user in real-time (like a navigation app), use
watchPosition(). It returns a value every time the user's location changes.
// Start watching
let watchId = navigator.geolocation.watchPosition(showPosition);
// Stop watching
navigator.geolocation.clearWatch(watchId);
| Property | Description |
|---|---|
coords.latitude |
The decimal degree latitude |
coords.longitude |
The decimal degree longitude |
coords.accuracy |
Accuracy of the position in meters |
coords.speed |
Speed in meters per second (null if N/A) |
timestamp |
The date/time the location was found |