People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by HarmonyOS, mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
Location Kit provides location services using multiple positioning technologies, such as Global Navigation Satellite System (GNSS) positioning, cellular positioning, and WLAN/Bluetooth positioning. Cellular positioning and WLAN/Bluetooth positioning are collectively referred to as network positioning technologies hereinafter. With these positioning technologies, the location of a user device can be accurately determined whether the device is indoors or outdoors.
In addition to basic location services, Location Kit provides features and APIs for geofencing, geocoding, reverse geocoding, country codes, and more.
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
GNSS positioning determines the location of a mobile device by using the positioning algorithms offered by the device chip to process location data from GNSS, for example, GPS, GLONASS, BeiDou, and Galileo. The specific positioning system used during the process depends on the hardware capabilities of the device.
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A higher density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location result to the application on a real-time basis.
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
Before using system basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain permission from the user.
The system provides the following location permissions:
ohos.permission.LOCATION: used to obtain location accurate to meters.
ohos.permission.APPROXIMATELY_LOCATION: used to obtain location accurate to 5 kilometers.
ohos.permission.LOCATION_IN_BACKGROUND: used to obtain location while the application is switched to run at the background.
If your application needs to access the device location information, it must first apply for required permissions.
Table 1 Description of location permissions
| target API level | Location Permission | Permission Application Result | Location Accuracy |
|---|---|---|---|
| Earlier than 9 | ohos.permission.LOCATION | Success | Location accurate to meters. |
| 9 and later | ohos.permission.LOCATION | Failed | No location obtained. |
| 9 and later | ohos.permission.APPROXIMATELY_LOCATION | Success | Location accurate to 5 kilometers. |
| 9 and later | ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION | Success | Location accurate to meters. |
To access the device location information when running in the background, an application needs to request the ohos.permission.LOCATION_IN_BACKGROUND permission or a continuous task of the background mode. In this way, the system continues to report device location information after your application moves to the background.
A user can grant the** ohos.permission.LOCATION_IN_BACKGROUND** permission for an application on the setting page. For details, see ohos.permission.LOCATION_IN_BACKGROUND.
For details about how to apply for a continuous task, see Continuous Task (ArkTS).
You can declare the required permissions in the application configuration file. For details, see Requesting User Authorization.
You can call location-related APIs to obtain the real-time location or latest known location of a mobile device.
For location-sensitive services, it is recommended that your application obtain the real-time location of the device. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device.
The following table lists the APIs for obtaining the location information. For details, see @ohos.geoLocationManager (Geolocation Manager).
Table 2 APIs for obtaining device location information
| Name | Description |
|---|---|
| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void | Registers a listener for location changes with a location request initiated. |
| off(type: 'locationChange', callback?: Callback<Location>): void | Unregisters the listener for location changes with the corresponding location request deleted. |
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(): Location | Obtains the last known device location. |
Before using system basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application first needs to apply for the required permission. For details, see Applying for Location Permissions.
Import the geoLocationManager module by which you can implement all APIs related to the basic location capabilities.
import geoLocationManager from '@ohos.geoLocationManager';
Obtain a single location, which is mainly used in scenarios such as viewing the current location, signing in/out, and service recommendation.
Method 1:
Obtain the latest location from the system cache. If the system does not have cached locations, an error code is returned. You are advised to preferentially use this API to reduce the system power consumption. If your application is sensitive to the location freshness, you can obtain the location from the cache and compare the timestamp in the location with the current time. If the freshness does not meet the expectation, use method 2 to obtain the location.
import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
let location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} Method 2:
Obtain the current location. First, instantiate a CurrentLocationRequest object to specify the type of location service to be provided to the application and how frequently location results are reported. If fast and accurate location results are required, you are advised to set LocationRequestPriority to FIRST_FIX. This priority uses GNSS positioning, cellular positioning, and WLAN/Bluetooth positioning simultaneously to obtain location results in both indoor and outdoor scenarios. When multiple positioning technologies provide location results, the system returns the result with higher accuracy to the application. However, using multiple positioning technologies simultaneously consumes more hardware resources and power. If high location accuracy is not required, you are advised to set the priority to LOW_POWER. This priority mainly uses cellular positioning and WLAN/Bluetooth positioning and can provide location services in both indoor and outdoor scenarios. Because positioning relies on the distribution of nearby cellular base stations and visible WLAN and Bluetooth devices, location accuracy may vary significantly. However, this priority can effectively reduce device power consumption.
Due to factors such as the device environment, device state, and system power management policies, the time required to obtain a location result may vary significantly. You are advised to set a timeout of 10 seconds for a single location request.
The following example shows how to make a location request with FIRST_FIX selected as the priority.
import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo: geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'timeoutMs': 10000};
let locationChange = (err:BusinessError.BusinessError, location:geoLocationManager.Location):void => {
if (err) {
console.error('getCurrentLocation: err=' + JSON.stringify(err));
}
if (location) {
console.log('getCurrentLocation: location=' + JSON.stringify(location));
}
};
try {
geoLocationManager.getCurrentLocation(requestInfo, locationChange);
} catch (err) {
console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} Continuous positioning is mainly used in scenarios such as navigation, movement track, and travel.
First, instantiate a LocationRequest object to specify the type of location service to be provided to the application and how frequently location results are reported. You are advised to set LocationRequestPriority to FIRST_FIX. This priority uses GNSS positioning, cellular positioning, and WLAN/Bluetooth positioning simultaneously to obtain location results in both indoor and outdoor scenarios. When multiple positioning technologies provide location results, the system returns the result with higher accuracy to the application.
The following example shows how to make a location request with FIRST_FIX selected as the priority.
import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo: geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'timeInterval': 1};
let locationChange = (location:geoLocationManager.Location):void => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
try {
geoLocationManager.on('locationChange', requestInfo, locationChange);
} catch (err) {
console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} If your application no longer needs the device location, stop obtaining the device location to avoid high power consumption.
geoLocationManager.off('locationChange', locationChange);