Quiz Entry - updated: 2026.07.05
How do you get the user's current position with the Geolocation API?
Call navigator.geolocation.getCurrentPosition(successCallback), which asynchronously invokes your function with a position object once the user grants permission.
function getLocation() {
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
}
getLocation();
Key points:
- Asynchronous - doesn't return immediately, calls callback when ready
- Requires permission - browser prompts user
- HTTPS required - won't work on insecure origins (except localhost)
The position object contains:
coords.latitude- Latitude in degreescoords.longitude- Longitude in degreescoords.accuracy- Accuracy in meterscoords.altitude- Altitude (if available)
Go deeper:
MDN — getCurrentPosition() — full signature including the optional third
optionsargument (enableHighAccuracy,timeout,maximumAge).