简介
位置定位提供了GNSS定位、网络定位等多种功能。在实际开发场景中,经常会使用位置定位的功能,如城市定位功能、外卖与快递服务实时跟踪配送员位置、汽车实时导航等等。
常见开发场景如下所示:
- 使用精准定位确认具体位置
- 获取历史定位
- 实时获取当前位置
- 后台定位
申请定位权限
场景描述
应用在使用位置能力前,首先需要确认系统的位置开关为开启状态。如果系统位置能力没有开启,应用不能使用定位服务。
其次,设备的位置信息需要想用户申请对应的访问权限,用户授权后,应用才能使用定位服务。需要用户授权的用户如下所示。
- ohos.permission.LOCATION:用于获取精准位置,精准度在米级别。
- ohos.permission.APPROXIMATELY_LOCATION:用于获取模糊位置,精确度为5公里。
- ohos.permission.LOCATION_IN_BACKGROUND:用于应用切换到后台仍然需要获取定位信息的场景。
开发步骤
1.在module.json5中配置需要的权限。
{
// ...
"requestPermissions": [
{
"name": "ohos.permission.LOCATION",
"reason": "$string:location_permission",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.INTERNET",
"reason": "$string:internet_permission",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:fuzzy_location_permission",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.LOCATION_IN_BACKGROUND",
"reason": "$string:location_permission",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
]
// ...
}
2.详细申请定位权限的代码如下所示。关于权限的申请,详情可以参考向用户申请授权。
// 引入a