1# 管理位置权限 2 3 4Web组件提供位置权限管理能力。开发者可以通过[onGeolocationShow()](../reference/arkui-ts/ts-basic-components-web.md#ongeolocationshow)接口对某个网站进行位置权限管理。Web组件根据接口响应结果,决定是否赋予前端页面权限。获取设备位置,需要开发者配置[ohos.permission.LOCATION](../security/accesstoken-guidelines.md)权限,并同时在设备上打开应用的位置权限和控制中心的位置信息。 5 6 7在下面的示例中,用户点击前端页面"获取位置"按钮,Web组件通过弹窗的形式通知应用侧位置权限请求消息。 8 9 10- 前端页面代码。 11 12 ```html 13 <!DOCTYPE html> 14 <html> 15 <body> 16 <p id="locationInfo">位置信息</p> 17 <button onclick="getLocation()">获取位置</button> 18 <script> 19 var locationInfo=document.getElementById("locationInfo"); 20 function getLocation(){ 21 if (navigator.geolocation) { 22 <!-- 前端页面访问设备地理位置 --> 23 navigator.geolocation.getCurrentPosition(showPosition); 24 } 25 } 26 function showPosition(position){ 27 locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; 28 } 29 </script> 30 </body> 31 </html> 32 ``` 33 34 35- 应用代码。 36 37 ```ts 38 // xxx.ets 39 import web_webview from '@ohos.web.webview'; 40 import common from '@ohos.app.ability.common'; 41 import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; 42 import geoLocationManager from '@ohos.geoLocationManager'; 43 44 let context = getContext(this) as common.UIAbilityContext; 45 let atManager = abilityAccessCtrl.createAtManager(); 46 47 try{ 48 atManager.requestPermissionsFromUser(context, ["ohos.permission.APPROXIMATELY_LOCATION"], (err, data) => { 49 let requestInfo: geoLocationManager.LocationRequest = { 50 'priority': 0x203, 51 'scenario': 0x300, 52 'maxAccuracy': 0 53 }; 54 let locationChange = (location: geoLocationManager.Location):void => { 55 if(location){ 56 console.log('locationChanger: location=' + JSON.stringify(location)); 57 } 58 }; 59 try{ 60 geoLocationManager.on('locationChange', requestInfo, locationChange); 61 geoLocationManager.off('locationChange', locationChange); 62 } catch (err) { 63 console.error("errCode:" + err.code + ", errMessage:" + err.message); 64 } 65 }) 66 } catch (err) { 67 console.error("err:", err); 68 } 69 70 @Entry 71 @Component 72 struct WebComponent { 73 controller: web_webview.WebviewController = new web_webview.WebviewController(); 74 build() { 75 Column() { 76 Web({ src:$rawfile('getLocation.html'), controller:this.controller }) 77 .geolocationAccess(true) 78 .onGeolocationShow((event) => { // 地理位置权限申请通知 79 AlertDialog.show({ 80 title: '位置权限请求', 81 message: '是否允许获取位置信息', 82 primaryButton: { 83 value: 'cancel', 84 action: () => { 85 if (event) { 86 event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求 87 } 88 } 89 }, 90 secondaryButton: { 91 value: 'ok', 92 action: () => { 93 if (event) { 94 event.geolocation.invoke(event.origin, true, false); // 允许此站点地理位置权限请求 95 } 96 } 97 }, 98 cancel: () => { 99 if (event) { 100 event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求 101 } 102 } 103 }) 104 }) 105 } 106 } 107 } 108 ``` 109