Web中如何创建定位授权弹窗?

Web中如何创建定位授权弹窗

阅读 181
1 个回答

在Web组件中使用定位能力可参考指南管理位置权限及以下示例代码。

// xxx.ets 
import { webview } from '@kit.ArkWeb'; 
 
@Entry 
@Component 
struct WebComponent { 
  controller: webview.WebviewController = new webview.WebviewController(); 
 
  build() { 
    Column() { 
      Web({ src: $rawfile('getLocation.html'), controller: this.controller }) 
        .geolocationAccess(true) 
        .onGeolocationShow((event) => { // 地理位置权限申请通知 
          AlertDialog.show({ 
            title: '位置权限请求', 
            message: '是否允许获取位置信息', 
            primaryButton: { 
              value: 'cancel', 
              action: () => { 
                if (event) { 
                  event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求 
                } 
              } 
            }, 
            secondaryButton: { 
              value: 'ok', 
              action: () => { 
                if (event) { 
                  event.geolocation.invoke(event.origin, true, false); // 允许此站点地理位置权限请求 
                } 
              } 
            }, 
            cancel: () => { 
              if (event) { 
                event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求 
              } 
            } 
          }) 
        }) 
    } 
  } 
}

在“src/main/resources/rawfile”路径下创建文件getLocation.html:

<!DOCTYPE html> 
<html> 
<body> 
<p id="locationInfo">位置信息</p> 
<button onclick="getLocation()">获取位置</button> 
<script> 
var locationInfo=document.getElementById("locationInfo"); 
function getLocation(){ 
  if (navigator.geolocation) { 
    <!-- 前端页面访问设备地理位置 --> 
    navigator.geolocation.getCurrentPosition(showPosition); 
  } 
} 
function showPosition(position){ 
  locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; 
} 
</script> 
</body> 
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进