当用户允许或拒绝访问“物理位置”时如何调用函数?

时间:2011-09-18 18:11:27

标签: javascript javascript-events geolocation

我的应用程序由jquery mobile提供支持并使用地理位置。

我的应用程序尝试获取用户的位置后,(Chrome)浏览器会提示用户:

  

Example.com想要跟踪您的物理位置[允许] [拒绝]

我的目标是:

  1. 如果用户单击“允许”,则调用功能1(使用位置 通过app)。
  2. 如果用户点击“拒绝”,则调用功能2(地址表单 显示)。
  3. 当用户点击“允许”或“拒绝”按钮时,如何将函数绑定到发生的事件(如果有)?

2 个答案:

答案 0 :(得分:15)

getCurrentPosition函数接受两个函数参数。哎呀,第一个是你允许时执行的,另一个是你否认时执行的!

Documentation

http://jsfiddle.net/pimvdb/QbRHg/

navigator.geolocation.getCurrentPosition(function(position) {
    alert('allow');
}, function() {
    alert('deny');
});

答案 1 :(得分:0)

Link to Docs

function handlePermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
  report(result.state);
  geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
  report(result.state);
  geoBtn.style.display = 'none';
  navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
  report(result.state);
  geoBtn.style.display = 'inline';
}
result.onchange = function() {
  report(result.state);}});}function report(state) {
 console.log('Permission ' + state);}

我希望这有效。