'Check if Geolocation was allowed and get Lat Lon

I'm building a small script that clients will install on their page. Geolocation is not necessary for it, however if it exists it would be nice to have. Is there a way for me to check if the clients page has requested geolocation information and if the user selected allow get the lat & lon without creating another prompt?



Solution 1:[1]

You can detect if the feature exists by examining the window object.

if ('geolocation' in navigator) {
     navigator.geolocation.getCurrentPosition(...);
}

This will cause a single user prompt to come up asking the user if they wish to share their location with your page.

If geolocation is not available in the browser, this will not run at all.


**EDIT** If you've already prompted the user on this *page load* for allowing geolocation access, it will NOT prompt you again. If the user navigates away and back to this page, it will re-prompt them.

You may make subsequent calls to the API without prompting during that page session.

Reference: MDN Geolocation -- Watching the current position

Solution 2:[2]

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

Solution 3:[3]

According to the API it is not possible to find out of the user has already permitted the current site to retrieve the user's location without causing a prompt if he hasn't. See Endless answer

I'd suggest you to allow users to pass an argument when embedding your script telling it if it should use geolocation features or not.

Solution 4:[4]

Whether or not you're prompted seems to depend on the browser and what 'privacy' settings it's got. Safari 6 has 3 settings: prompt once per site, prompt once per site per day, and deny. Chrome 23 has 3 settings: allow all, ask, and deny all. Sure would get good if there was a way to check if it's already allowed without bothering the user.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen Jennings
Solution 2 Fendi Septiawan
Solution 3 Community
Solution 4 OsamaBinLogin