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?
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)
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With