Get the current position
Use getCurrentPosition() to request one location result, then handle success, failure, and options separately.
What you will learn
- What the three arguments mean
- How to handle permission and device errors
- How options affect the request
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
options
);
successCallback- Required. Receives a
Positionobject when the request succeeds. errorCallback- Optional. Receives a
GeolocationPositionErrorwhen the request fails. options- Optional settings such as high accuracy, timeout, and cached-result age.
Handle errors
function showError(error) {
if (error.code === error.PERMISSION_DENIED) {
console.log('Location permission was denied.');
} else {
console.log('The position could not be read.');
}
}
Location is sensitive information. Explain why your page needs it, request it at a useful moment, and do not treat a denied request as an exceptional user mistake.