Have you read http://www.w3schools.com/html/html5_geolocation.asp
What you want to do is check the errors to see if they allowed it or denied the request.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Answer from Bot on Stack OverflowHave you read http://www.w3schools.com/html/html5_geolocation.asp
What you want to do is check the errors to see if they allowed it or denied the request.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
The below code will allow you to check the permission status without invoking the navigator.geolocation permission request.
Browsers Supported: Chrome(43+), Firefox(46+), Edge and Opera.
Unsupported: Safari(mac, ios), Internet explorer, Android webview.
navigator.permissions && navigator.permissions.query({name: 'geolocation'})
.then(function(PermissionStatus) {
if (PermissionStatus.state == 'granted') {
//allowed
} else if (PermissionStatus.state == 'prompt') {
// prompt - not yet grated or denied
} else {
//denied
}
})
Here is the Reference Link.
Compatibility on other browsers is unknown. I haven't tested it myself but please feel to test yourself and comment below.
javascript - Function to determine if geo-location is enabled - Stack Overflow
javascript - Detect if user has enabled location services on domain - Stack Overflow
javascript - Is there a way to know if geolocation is enabled for the current domain? - Stack Overflow
Is it possiblel to detect when a user has disabled location services in their OS?
How can I get a user's location with JavaScript?
What is the difference between navigator.geolocation and IP geolocation?
Can I get a user's precise location without their permission?
If the user does not allow your app to use the Geolocation API the methods getCurrentPosition and watchPosition will return an PositionError object via the error callback:
void getCurrentPosition(successCallback,
errorCallback,
options);
long watchPosition(successCallback,
errorCallback,
options);
The PositionError looks like:
PositionError {
code;
message;
};
where the possibles values of code are:
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
And more specific:
- PERMISSION_DENIED (numeric value 1) The location acquisition process failed because the document does not have permission to use the Geolocation API.
The documentation here.
There is no check for permanent authorization.
The only thing you can do imho is try to "guess" if the user has authorized by estimate time.
For example:
more than 1,5 seconds to retrieve geolocation -> probably user got to click interface and give auth
less than 500ms -> pretty sure user already give auth
I just spent a good hour banging my head against a wall trying to work out why the callback in my navigator.geolocation.getCurrentPosition() method wasn't running. I was using Firefox and eventually thought to check in Chrome which immediatley notified me that I had location services disabled in my MacOs settings. (Doh!)
I had checked that location services were available using if ('geolocation' in navigator) but obviously this must not take into account whether a user has disabled location services directly in the OS of their device.
So my question is, how would I check this before offering this functinality on my page?
The user experiece in Chrome wouldn't be too bad, since it informs you straight away what the issue is, but the experience in Firefox would be awful for an end user because there was absolutely no feedback at all about what went wrong.
watchPosition and getCurrentPosition both accept a second callback which is invoked when there is an error. The error callback provides an argument for an error object. For permission denied, error.code would be error.PERMISSION_DENIED (numeric value 1).
Read more here: https://developer.mozilla.org/en/Using_geolocation
Example:
Copynavigator.geolocation.watchPosition(function(position) {
console.log("i'm tracking you!");
},
function(error) {
if (error.code == error.PERMISSION_DENIED)
console.log("you denied me :-(");
});
Run code snippetEdit code snippet Hide Results Copy to answer Expand
EDIT: As @Ian Devlin pointed out, it doesn't seem Firefox (4.0.1 at the time of this post) supports this behavior. It works as expected in Chrome and probably Safari etc.
Without prompting the user, you can use the new permission api this is available as such:
Copynavigator.permissions.query({ name: 'geolocation' })
.then(console.log)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Thanks to @GabrielePetrioli's comment. The code below uses navigator.permissions.queryPermissions Status Change Event
I am checking if permission was granted and updating the application by calling the function which updates location.
const [locationAccess, setLocationAccess] = useState(false);//user changes in browser
...
//check user location changes in navigator
navigator.permissions.query({ name: 'geolocation' }).then((permissionStatus) => {
permissionStatus.onchange = () => {
setLocationAccess(permissionStatus.state=="granted")
if (permissionStatus.state=="granted") {
attemptLocation();
}
};
});
Call http://locater.info/ from your browser and you should get the data
Quick question is there anyway to check IF location services is disabled or if location is not accessible or something similar?
Basically I want to open the location setting page whenever I open google maps (which I have done) but the problem is that it opens the settings even if location is already on and I want it to only open that page if location setting is disabled. Worst case I guess I can just use the โask before runningโ feature as a workaround
It isn't possible with the geolocation API but it is possible with the new permission API
This code is useful if you want to try to receive the coordinates but don't want to bother the user with a prompt dialog cuz the coordinates is not that important and may as well fallback to geoIP
function getCoords() {
return new Promise((resolve, reject) =>
navigator.permissions ?
// Permission API is implemented
navigator.permissions.query({
name: 'geolocation'
}).then(permission =>
// is geolocation granted?
permission.state === "granted"
? navigator.geolocation.getCurrentPosition(pos => resolve(pos.coords))
: resolve(null)
) :
// Permission API was not implemented
reject(new Error("Permission API is not supported"))
)
}
getCoords().then(coords => console.log(coords))
This will resolve to null if permission hasn't been granted, cast a error if some javascript code wasn't supported by the browser and resolve to the coordinates if it has been granted
I also encountered the same problem. And, after I search and experiment I finally found the answer.
You can add this JS code :
navigator.permissions.query({name:'geolocation'}).then(function(result) {
// Will return ['granted', 'prompt', 'denied']
console.log(result.state);
});
Then you can use your custom code as needed.
source : https://developer.mozilla.org/en-US/docs/Web/API/Navigator/permissions