【问题标题】:How to prompt location sharing permission in browser using JavaScript?如何使用 JavaScript 在浏览器中提示位置共享权限?
【发布时间】:2023-04-09 01:29:02
【问题描述】:

如何使用 JavaScript 向用户提示位置共享权限。例如,每当我们访问谷歌地图时,浏览器都会自动询问共享位置。我的目标是提示用户允许共享位置。当我在 AngularJS 中使用跟踪模块时,虽然我需要提示用户在谷歌浏览器中获得许可。 谢谢

【问题讨论】:

标签: javascript angularjs web


【解决方案1】:

您可以像这样使用该功能。调用这个函数会弹出弹窗。

navigator.geolocation.getCurrentPosition(function(position) {
  yourFunction(position.coords.latitude, position.coords.longitude);
});

当位置可用时,yourFunction 将被执行。

【讨论】:

  • 这将为我提供位置,因为我需要共享位置的权限。
  • 单独使用此代码将使浏览器显示常见的弹出窗口,询问是否允许共享位置。
【解决方案2】:

一些额外的信息,你可以使用这个API在浏览器中查看地理位置共享的权限状态:https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API/Using_the_Permissions_API

此 API 返回一个 PermissionStatus 对象,其中包含“state”属性,即访问地理位置的权限状态

function handlePermission() {
  navigator.permissions.query({name:'geolocation'}).then(function(result) {
    if (result.state == 'granted') {
      report(result.state);
    } else if (result.state == 'prompt') {
      report(result.state);
      navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
    } else if (result.state == 'denied') {
      report(result.state);
    }
    result.onchange = function() {
      report(result.state);
    }
  });
}

function report(state) {
  console.log('Permission ' + state);
}

handlePermission();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多