检查Geolocation是否被允许并获得Lat Lon [英] Check if Geolocation was allowed and get Lat Lon
问题描述
我正在构建一个客户端将在其页面上安装的小脚本。地理位置不是必需的,但如果它存在,那将是很好的。有没有办法让我检查客户页面是否已请求地理位置信息,如果用户选择允许获取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?
推荐答案
使用地理定位API是不可能的,但可以使用新的权限API
It isn't possible with the geolocation API but it is possible with the new permission API
如果您想尝试接收坐标但又不想通过提示对话框打扰用户,此代码非常有用,因为坐标不是很重要,可能是退回到geoIP
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))
如果未授予权限,如果浏览器不支持某些javascript代码则转换错误,如果已被授予,则解析为坐标
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
这篇关于检查Geolocation是否被允许并获得Lat Lon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!