详细回答:需同时开启 GPS 和网络定位,并设置高精度模式。自定义一个LocationManager工具类,
定位优先级,默认PRIORITY_LOCATING_SPEED 高精度需要使用PRIORITY_ACCURACY
✅ 正确做法
import { geoLocationManager } from "@kit.LocationKit";
import { LogUtils } from "./LogUtils";
import showToast from "./ToastUtils";
import { hilog } from "@kit.PerformanceAnalysisKit";
/**
* @author J.query
* @date 2025/12/24 14:08
* @email j-query@foxmail.com
* Description:
*/
const TAG = "LocationManager"
export default class LocationManager {
/**
* 获取当前位置信息(包含地址)
* @returns 返回包含位置信息和地址的 `GeoLocationInfo` 对象
*/
static async getCurrentLocationWithAddress(): Promise<GeoLocationInfo> {
const request: geoLocationManager.SingleLocationRequest = {
// 定位优先级,默认PRIORITY_LOCATING_SPEED 高精度使用PRIORITY_ACCURACY
locatingPriority: geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,
locatingTimeoutMs: 5000, // 5秒更新
};
try {
// 获取当前位置的经纬度
const location = await geoLocationManager.getCurrentLocation(request);
LogUtils.debug(TAG, `getCurrentLocation: location=${JSON.stringify(location)}`);
// 根据经纬度获取地址信息
const address = await LocationManager.getAddressFromLocation({
latitude: location.latitude,
longitude: location.longitude,
});
// 返回完整的位置信息
return {
status: true,
address: address,
lng: location.longitude,
lat: location.latitude,
} as GeoLocationInfo;
} catch (error) {
LogUtils.error(TAG, `getCurrentLocationWithAddress failed: error=${JSON.stringify(error)}`);
showToast(`getCurrentLocationWithAddress failed: error=${JSON.stringify(error)}`)
// 返回失败的状态和错误信息
return {
status: false,
msg: error.message || '获取位置信息失败',
} as GeoLocationInfo;
}
}
/**
* 根据经纬度获取地址信息
* @param location 包含经纬度的 `LocationInter` 对象
* @returns 返回地址信息
*/
static async getAddressFromLocation(location: LocationInter): Promise<string> {
try {
const reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest = {
locale: getContext().resourceManager.getStringSync($r('app.string.language')),
latitude: location.latitude,
longitude: location.longitude,
maxItems: 1,
};
const data = await new Promise<geoLocationManager.GeoAddress[]>((resolve, reject) => {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
if (data && data.length > 0) {
const address = data[0]?.placeName || '';
hilog.info(0x0000, TAG, `The address is: ${address}`);
return address;
}
} catch (error) {
hilog.error(0x0000, TAG, `getAddressFromLocation failed, code: ${error.code}, message: ${error.message}`);
}
return ''; // 如果获取地址失败,返回空字符串
}
}
export interface GeoLocationInfo{
address:string;
lng:number;
lat:number;
status:boolean;
msg:string
}
export interface LocationInter {
latitude: number,
longitude: number
}
import LocationManager from './utils/LocationManager';
// 在需要获取位置的地方调用
async function getLocation() {
try {
const locationInfo = await LocationManager.getCurrentLocationWithAddress();
if (locationInfo.status) {
console.log('位置信息:', locationInfo.address);
console.log('经纬度:', locationInfo.lng, locationInfo.lat);
} else {
console.log('获取位置失败:', locationInfo.msg);
}
} catch (error) {
console.error('获取位置异常:', error);
}
}
⚠️ 避坑指南
🌍 室内 GPS 信号弱,需结合 WiFi 定位(系统自动处理)。
⏳ 首次定位可能长达 30 秒,应显示 Loading 提示。
📱 用户可能关闭位置服务,必要的位置权限打开
🎯 效果
室外定位精度达 5–10 米,满足导航级需求。