Read the original article:How to get user location
Context
In a HarmonyOS application, you may need to fetch the user's current GPS location—for example, to show nearby places, track user movement, or personalize content based on their position.
Description
This function demonstrates how to retrieve the user's current location using LocationKit in HarmonyOS. It sends a one-time request for location with a speed-first priority and a 10-second timeout.
Solution
// module.json5
{
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:location_permission",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
// EntryAbility.ets
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, "TAG", `EntryAbility onCreate`);
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(this.context,
['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
.then((data) => {
hilog.info(0x0000, TAG, `data: ${JSON.stringify(data)}`);
})
.catch((err: BusinessError) => {
hilog.error(0x0000, TAG, `err: ${JSON.stringify(err)}`);
})
} catch (err) {
hilog.error(0x0000, TAG, `catch err->${JSON.stringify(err)}`);
}
}
import { geoLocationManager } from '@kit.LocationKit';
import type { BusinessError } from '@kit.BasicServicesKit';
export function getCurrentLocation(): Promise<LocationModel> {
const request: geoLocationManager.SingleLocationRequest = {
locatingPriority: geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,
locatingTimeoutMs: 10000
};
return geoLocationManager.getCurrentLocation(request)
.then((result: geoLocationManager.Location): LocationModel => {
return {
lat: result.latitude,
lon: result.longitude
} as LocationModel;
})
.catch((error: BusinessError) => {
throw (error instanceof Error ? error : new Error(JSON.stringify(error)));
});
}
Key Takeaways
- Use
geoLocationManager.getCurrentLocation()for one-time GPS queries. - Set
locatingPriorityto choose between speed, accuracy, or battery optimization. - Always handle errors properly to avoid app crashes and improve user experience.
- Wrap results in a domain model (
LocationModel) for cleaner integration in ViewModels.
Additonal Resources
https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/location-kit-V13
Top comments (0)