Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Stefan Avatar asked Apr 09 '12 18:04

Stefan


People also ask

How do I know if geolocation is compatible?

Check if Geolocation is supported. If supported, run the getCurrentPosition() method. If not, display a message to the user. If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)

How do you get geolocation without permission?

You can go for an external service like https://www.geolocation-db.com. They provide a geolocation service based on IP addresses where you don't need user permission.

How do I get geolocation on my browser?

The Geolocation API is accessed via a call to navigator. geolocation ; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).


1 Answers

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

like image 57
Endless Avatar answered Oct 13 '22 12:10

Endless