• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 管理位置权限
2
3
4Web组件提供位置权限管理能力。开发者可以通过[onGeolocationShow()](../reference/apis-arkweb/ts-basic-components-web.md#ongeolocationshow)接口对某个网站进行位置权限管理。Web组件根据接口响应结果,决定是否赋予前端页面权限。
5
6- 使用获取设备位置功能前请在module.json5中添加位置相关权限,权限的添加方法请参考[在配置文件中声明权限](../security/AccessToken/declare-permissions.md)。
7
8   ```
9   "requestPermissions":[
10      {
11        "name" : "ohos.permission.LOCATION"
12      },
13      {
14        "name" : "ohos.permission.APPROXIMATELY_LOCATION"
15      },
16      {
17        "name" : "ohos.permission.LOCATION_IN_BACKGROUND"
18      }
19    ]
20   ```
21
22在下面的示例中,用户点击前端页面"获取位置"按钮,Web组件通过弹窗的形式通知应用侧位置权限请求消息。
23
24
25- 前端页面代码。
26
27  ```html
28  <!DOCTYPE html>
29  <html>
30  <body>
31  <p id="locationInfo">位置信息</p>
32  <button onclick="getLocation()">获取位置</button>
33  <script>
34  var locationInfo=document.getElementById("locationInfo");
35  function getLocation(){
36    if (navigator.geolocation) {
37      <!-- 前端页面访问设备地理位置 -->
38      navigator.geolocation.getCurrentPosition(showPosition);
39    }
40  }
41  function showPosition(position){
42    locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
43  }
44  </script>
45  </body>
46  </html>
47  ```
48
49
50- 应用代码。
51
52  ```ts
53  // xxx.ets
54  import { webview } from '@kit.ArkWeb';
55  import { BusinessError } from '@kit.BasicServicesKit';
56  import { abilityAccessCtrl, common } from '@kit.AbilityKit';
57
58  let atManager = abilityAccessCtrl.createAtManager();
59
60  @Entry
61  @Component
62  struct WebComponent {
63    controller: webview.WebviewController = new webview.WebviewController();
64    uiContext: UIContext = this.getUIContext();
65
66    aboutToAppear(): void {
67      let context : Context | undefined = this.uiContext.getHostContext() as common.UIAbilityContext;
68      // 向用户请求位置权限设置。
69      atManager.requestPermissionsFromUser(context, ["ohos.permission.APPROXIMATELY_LOCATION"]).then((data) => {
70        console.info('data:' + JSON.stringify(data));
71        console.info('data permissions:' + data.permissions);
72        console.info('data authResults:' + data.authResults);
73      }).catch((error: BusinessError) => {
74        console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`);
75      })
76    }
77
78    build() {
79      Column() {
80        Web({ src: $rawfile('getLocation.html'), controller: this.controller })
81          .geolocationAccess(true)
82          .onGeolocationShow((event) => { // 地理位置权限申请通知
83            this.uiContext.showAlertDialog({
84              title: '位置权限请求',
85              message: '是否允许获取位置信息',
86              primaryButton: {
87                value: 'cancel',
88                action: () => {
89                  if (event) {
90                    event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
91                  }
92                }
93              },
94              secondaryButton: {
95                value: 'ok',
96                action: () => {
97                  if (event) {
98                    event.geolocation.invoke(event.origin, true, false); // 允许此站点地理位置权限请求
99                  }
100                }
101              },
102              cancel: () => {
103                if (event) {
104                  event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
105                }
106              }
107            })
108          })
109      }
110    }
111  }
112  ```
113