The if (navigator.geolocation)
method doesn't work here as navigator.geolocation
is an empty object, regardless of whether a position can be obtained. You can console.log(navigator.geolocation)
to verify this.
Instead, use the error callback parameter of navigator.geolocation.watchPosition
:
function getLocation() {
navigator.geolocation.watchPosition(showPosition, throwError);
}
function throwError(err) {
switch (err.code) {
case 1: x.innerHTML = "Permission denied."; break;
case 2: x.innerHTML = "Position unavailable."; break;
case 3: x.innerHTML = "Request timed out."; break;
default: x.innerHTML = "Unknown error.";
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition
https://developer.mozilla.org/en-US/docs/Web/API/PositionError
Also, there are some significant browser quirks to be aware of.
If you are testing your site on your local filesystem, Chrome blocks geolocation requests:
HTML 5 Geo Location Prompt in Chrome
And Firefox still won't handle the error callback correctly (scroll down to see workarounds): Is there a way to check if geolocation has been DECLINED with Javascript?