单次定位用于在某个时刻获取一次当前位置(例如打开页面时显示「我的位置」、签到时记录定位等场景)。
本文档介绍单次定位的接口、请求参数、返回结果与典型示例。
class TencentLocationManager {
Future<TencentLocation> startSingleLocation(TencentLocationRequest request);
}
调用 startSingleLocation 返回的 Future 会在以下任一情况下结束:
成功获取到一次定位结果,正常返回 TencentLocation。
调用超时,抛出 TencentLocationError,错误码为 timeout。
定位流程中出现失败,抛出 TencentLocationError,错误码为 locationFailed 或更具体的错误码(详见 错误码)。
TencentLocationRequest 通过 TencentLocationRequest.create() 创建,使用链式 setter 设置通用字段,使用 .android(...) / .ios(...) 配置平台专属字段。
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
coordinateType |
CoordinateType |
gcj02 |
返回坐标系,可选 gcj02 / wgs84 |
requestLevel |
RequestLevel |
adminArea |
返回等级(详见下方) |
allowDirectionSensor |
bool |
false |
是否在结果中带上传感器方向 |
RequestLevel 决定返回结果的丰富程度:
| 值 | 内容 |
|---|---|
geo |
仅经纬度 + 海拔 + 精度 |
name |
在 geo 基础上附加位置名称与详细地址 |
adminArea |
在 name 基础上附加省 / 市 / 区等行政区划信息 |
poi |
在 adminArea 基础上附加周边 POI 列表 |
通过 .android((extension) => ...) 配置:
| 字段 | 默认值 | 说明 |
|---|---|---|
firstLocationTimeout |
15 秒 | Android 端单次定位的超时时长 |
firstLocationNeedAddress |
false |
单次定位是否一定要等到逆地址结果 |
locMode |
highAccuracy |
定位模式:高精度 / 仅网络 / 仅 GPS |
gnssSource |
gpsFirst |
GNSS 来源:GPS 优先 / 北斗优先 / 仅北斗 / RTK 优先 |
allowGps / allowBle / allowCache |
true / true / false |
是否允许 GPS / BLE / 缓存定位 |
indoorMode |
false |
是否启用室内定位模式 |
通过 .ios((extension) => ...) 配置:
| 字段 | 默认值 | 说明 |
|---|---|---|
singleLocationTimeout |
10 秒 | iOS 端单次定位的超时时长 |
desiredAccuracy |
best |
期望精度等级 |
activityType |
other |
活动类型,用于辅助系统定位策略 |
pausesLocationUpdatesAutomatically |
true |
是否允许系统在合适时机自动暂停定位 |
Future<void> requestSingleLocation() async {
final manager = TencentLocationManager();
try {
final request = TencentLocationRequest.create()
..setRequestLevel(RequestLevel.adminArea)
..setCoordinateType(CoordinateType.gcj02)
..android((android) {
android
..firstLocationTimeout = const Duration(seconds: 15)
..firstLocationNeedAddress = true;
})
..ios((ios) {
ios.singleLocationTimeout = const Duration(seconds: 10);
});
final location = await manager.startSingleLocation(request);
print('单次定位结果:'
'lat=${location.latitude}, lng=${location.longitude}, '
'address=${location.geoAddress?.address}');
} on TencentLocationError catch (error) {
print('单次定位失败:${error.code} ${error.message}');
} finally {
await manager.dispose();
}
}
TencentLocation 包含以下常用字段:
latitude / longitude:经纬度
altitude:海拔(米),仅 GNSS 有效
accuracy:水平精度(米)
bearing:方向角(度),仅 GNSS 有效
speed:速度(米 / 秒),仅 GNSS 有效
time:定位时刻的 Unix 毫秒时间戳
coordinateType:返回坐标系
source:定位来源(GPS / 网络 / 缓存等),可通过 .isGnss / .isNetwork 等扩展方法做跨端归类
geoAddress:逆地理结果(requestLevel >= name 时有值)
poiList:周边 POI 列表(requestLevel == poi 时有值)
字段在不同平台上的可用性请见 API Reference。
一次单次定位会自动发起一次原生定位请求,结束(成功 / 超时 / 失败)后不会保留任何监听。
多次连续调用单次定位时,每次都建议使用同一个 TencentLocationManager 实例并在不再使用时统一 dispose(),避免重复创建带来的资源开销。
同一个 TencentLocationManager 实例可以同时承载单次定位与连续定位,但不建议同时发起:在已经启动连续定位的实例上发起单次定位可能会与连续定位的回调流相互影响。
单次定位的超时时长不会影响连续定位。
有帮助
没帮助