
回复
本文原创发布在华为开发者社区。
本示例利用 @ohos.geoLocationManager 通过位置服务获取当前设备所处的地理位置及经纬度,设置精准定位开关可获取精准位置。
定位前检查是否已经获取用户授权访问设备位置信息,如未获得授权,向用户申请需要的位置权限。
使用@ohos.geoLocationManager接口获取设备位置的经纬度,再将经纬度转换成实际位置。核心代码如下,源码参考
Index.ets
let locationChange = (err: BusinessError, location: geoLocationManager.Location) => {
// 获取经纬度
if (location.latitude === 0 && location.longitude === 0) {
return;
}
// 将经纬度转成实际位置
let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest = {
'locale': this.locale.toString().includes('zh') ? 'zh' : 'en',
'latitude': location.latitude,
'longitude': location.longitude,
'maxItems': 1
};
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then(data => {
if (data[0].placeName) {
this.message = this.message + data[0].placeName;
}
}).catch((err: Error) => {
Logger.error('GetAddressesFromLocation err ' + JSON.stringify(err));
});
};