• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Location Service Development
2
3## Overview
4
5People 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.
6
7With the location awareness capability offered by OpenHarmony, 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.
8
9Your 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.
10
11### Service Introduction
12
13Location awareness helps determine where a mobile device locates. The location subsystem identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services.
14
15These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
16
17- **Coordinate**
18  A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
19
20- **GNSS positioning**
21  GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
22
23- **Base station positioning**
24  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.
25
26- **WLAN or Bluetooth positioning**
27  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 high 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.
28
29### Working Principles
30
31Location 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 information to the application on a real-time basis.
32
33### Constraints
34
35Your application can use the location function only after the user has granted the required permission and turned on the location function. If the location function is off, the system will not provide the location service for any application.
36
37Since 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.
38
39
40## Applying for Location Permissions
41
42### When to Use
43
44Before 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 the permission from the user.
45
46The system provides the following location permissions:
47
48- ohos.permission.LOCATION: used to obtain location accurate to meters.
49
50- ohos.permission.APPROXIMATELY\_LOCATION: used to obtain location accurate to 5 kilometers.
51
52- ohos.permission.LOCATION\_IN\_BACKGROUND: used to obtain location while the application is running at the background.
53
54If your application needs to access the device location information, it must first apply for required permissions.
55
56**Table 1** Ways to apply for location permissions
57
58| Target API Level| Location Permission| Permission Application Result| Location Accuracy|
59| -------- | -------- | -------- | -------- |
60| Earlier than 9| ohos.permission.LOCATION | Successful| Location accurate to meters.|
61| 9 and later| ohos.permission.LOCATION | Failed| No location obtained.|
62| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Successful| Location accurate to 5 kilometers.|
63| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Successful| Location accurate to meters.|
64
65If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
66
67You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
68
69For details about the permissions required for each API of the location service, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
70
71### How to Develop
72
73You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
74
75## Obtaining Device Location Information
76
77### When to Use
78
79You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device.
80
81Real-time location of the device is recommended for location-sensitive services. 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.
82
83### Available APIs
84
85The following table lists the APIs used to obtain the device location information. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
86
87**Table 2** APIs for obtaining device location information
88
89| API| Description|
90| -------- | -------- |
91| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void | Registers a listener for location changes with a location request initiated.|
92| off(type: 'locationChange', callback?: Callback<Location>): void | Unregisters the listener for location changes with the corresponding location request deleted.|
93| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void | Obtains the current location. This API uses an asynchronous callback to return the result. |
94| getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | Obtains the current location. This API uses a promise to return the result. |
95| getLastLocation(): Location | Obtains the last known device location.|
96
97### How to Develop
98
991. Before using basic location capabilities, check whether your application has been granted the permission to access device location information. If not, your application first needs to apply for the required permission. For details, see [Applying for Location Permissions](#applying-for-location-permissions).
100
1012. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
102
103   ```ts
104   import geoLocationManager from '@ohos.geoLocationManager';
105   ```
106
1073. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
108   **Method 1:**
109
110   To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The location service scenarios currently supported are described as follows.
111
112   **Location service scenarios**
113
114   - NAVIGATION<br>
115   Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. <br>In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. <br>To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users. <br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.
116
117   - TRAJECTORY\_TRACKING<br>
118   Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. <br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.
119
120   - CAR\_HAILING<br>
121   Applicable when your application needs to obtain the current location of a user who is hailing a taxi. <br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.
122
123   - DAILY\_LIFE\_SERVICE<br>
124   Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food. <br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.
125
126   - NO\_POWER<br>
127   Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location. <br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.
128
129
130   ```ts
131       export enum LocationRequestScenario {
132            UNSET = 0x300,
133            NAVIGATION,
134            TRAJECTORY_TRACKING,
135            CAR_HAILING,
136            DAILY_LIFE_SERVICE,
137            NO_POWER,
138        }
139   ```
140
141
142   Sample code for initializing **requestInfo** for navigation:
143
144   ```ts
145   let requestInfo:geoLocationManager.LocationRequest = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
146   ```
147
148   **Method 2:**
149
150   If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
151
152   **Location priority policies**
153
154   - ACCURACY<br>
155      This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
156
157   - FIRST\_FIX<br>
158      This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
159
160   - LOW\_POWER<br>
161      This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
162
163   ```ts
164       export enum LocationRequestPriority {
165            UNSET = 0x200,
166            ACCURACY,
167            LOW_POWER,
168            FIRST_FIX,
169        }
170   ```
171
172   Sample code for initializing **requestInfo** for the location accuracy priority policy:
173
174   ```ts
175   let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
176   ```
177
1784. Instantiate the **Callback** object for the system to report location results.
179     Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic.
180
181   ```ts
182   let locationChange = (location:geoLocationManager.Location):void => {
183       console.log('locationChanger: data: ' + JSON.stringify(location));
184   };
185   ```
186
1875. Start obtaining the device location.
188
189   ```ts
190   geoLocationManager.on('locationChange', requestInfo, locationChange);
191   ```
192
1936. (Optional) Stop obtaining the device location.
194
195   If your application no longer needs the device location, stop obtaining the device location to avoid high power consumption.
196
197   ```ts
198   geoLocationManager.off('locationChange', locationChange);
199   ```
200
201   If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
202
203   ```ts
204   import geoLocationManager from '@ohos.geoLocationManager';
205   import BusinessError from "@ohos.base";
206   try {
207       let location = geoLocationManager.getLastLocation();
208   } catch (err) {
209       console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
210   }
211   ```
212
213
214## Geocoding and Reverse Geocoding
215
216### When to Use
217
218Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. To address this issue, the system provides your application the geocoding and reverse geocoding capabilities:
219
220- Geocoding: converts geographic descriptions into specific coordinates.
221
222- Reverse geocoding: converts coordinates into geographic descriptions.
223
224The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc.
225
226### Available APIs
227
228The following table lists the APIs used for mutual conversion between coordinates and geographic descriptions. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
229
230**Table 3** APIs for geocoding and reverse geocoding conversion
231
232| API| Description|
233| -------- | -------- |
234| isGeocoderAvailable(): boolean; | Obtains the (reverse) geocoding service status.|
235| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts coordinates into geographic descriptions through reverse geocoding. This API uses an asynchronous callback to return the result. |
236| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts coordinates into geographic descriptions through reverse geocoding. This API uses a promise to return the result. |
237| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts geographic descriptions into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
238| getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic descriptions into coordinates through geocoding. This API uses a promise to return the result. |
239
240### How to Develop
241
242> **NOTE**<br>
243> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
244
2451. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
246
247   ```ts
248   import geoLocationManager from '@ohos.geoLocationManager';
249   ```
250
2512. Check whether the **geoCoder** service is available.
252   - Call **isGeoServiceAvailable** to check whether the **geoCoder** service is available. If the service is available, go to step 3.
253
254      ```ts
255      import geoLocationManager from '@ohos.geoLocationManager';
256      import BusinessError from "@ohos.base";
257      try {
258          let isAvailable = geoLocationManager.isGeocoderAvailable();
259      } catch (err) {
260          console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
261      }
262      ```
263
2643. Obtain the geocoding conversion result.
265   - Call **getAddressesFromLocation** to convert coordinates into geographical location information.
266
267      ```ts
268      let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
269      try {
270          geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
271              if (err) {
272                  console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
273              } else {
274                  console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
275              }
276          });
277      } catch (err) {
278          console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
279      }
280      ```
281
282      The application can access the **GeoAddress** list that matches the specified coordinates for the corresponding geographic descriptions. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
283   - Call **getAddressesFromLocationName** to convert geographic descriptions into coordinates.
284
285      ```ts
286      let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
287      try {
288          geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
289              if (err) {
290                  console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
291              } else {
292                  console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
293              }
294          });
295      } catch (err) {
296          console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
297      }
298      ```
299
300      The application can access the **GeoAddress** list that matches the specified geographic descriptions for the corresponding coordinates. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
301
302      To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
303
304
305## Geofencing
306
307### When to Use
308
309A geofence is a group of virtual bounds defining an area on the map. When a user device enters or leaves a geofence, or stays in a geofence, your app on the user device can automatically receive notifications and alarms.
310
311Currently, only circular geofences are supported, and the geofencing function of the GNSS chip is required.
312
313A typical application of geofencing is to create a geofence around an enterprise for targeted advertising. In different areas, you can provide differentiated promotions for mobile devices.
314
315### Available APIs
316
317The following table lists the APIs used for geofencing. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
318
319**Table 4** Geofencing APIs
320
321| API| Description|
322| -------- | -------- |
323| on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Registers a listener for status change events of the specified geofence.|
324| off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Unregisters the listener for status change events of the specified geofence.|
325
326### How to Develop
327
3281. Declare the **ohos.permission.APPROXIMATELY_LOCATION** permission. For details, see [Applying for Location Permissions](#applying-for-location-permissions).
329
3302. Import the [geoLocationManager](../reference/apis/js-apis-geoLocationManager.md), [wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md), and [BusinessError](../reference/apis/js-apis-base.md) modules.
331
332   ```ts
333   import geoLocationManager from '@ohos.geoLocationManager';
334   import wantAgent, {WantAgent as _wantAgent} from '@ohos.app.ability.wantAgent';
335   import BusinessError from "@ohos.base";
336   ```
337
3383. Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object.
339
340   Scenario 1: Create a **WantAgentInfo** object for starting an ability.
341
342   ```ts
343   let wantAgentObj:_wantAgent|null = null; // Save the created WantAgent object for completing the trigger operations at a later time.
344
345   // Set the operation type through operationType of the WantAgentInfo object.
346   let wantAgentInfo:wantAgent.WantAgentInfo = {
347       wants: [
348           {
349               deviceId: '',
350               bundleName: 'com.example.myapplication',
351               abilityName: 'EntryAbility',
352               action: '',
353               entities: [],
354               uri: '',
355               parameters: {}
356           }
357       ],
358       operationType: wantAgent.OperationType.START_ABILITY,
359       requestCode: 0,
360       wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
361   };
362   ```
363
364   Scenario 2: Create a **WantAgentInfo** object for publishing [common events](../application-models/common-event-overview.md).
365
366   ```ts
367   let wantAgentObj:_wantAgent|null = null; // Save the created WantAgent object for completing the trigger operations at a later time.
368
369   // Set the operation type through operationType of the WantAgentInfo object.
370   let wantAgentInfo:wantAgent.WantAgentInfo = {
371       wants: [
372           {
373               action: "event_name", // Set the event name.
374               parameters: {},
375           }
376       ],
377       operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
378       requestCode: 0,
379       wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
380   }
381   ```
382
3834. Call [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to create a **WantAgent** object.
384
385After obtaining the **WantAgent** object, call the geofencing API to add a geofence.
386
387   ```ts
388   // Create a WantAgent object.
389   wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
390       if (err) {
391         console.error('getWantAgent err=' + JSON.stringify(err));
392         return;
393       }
394       console.info('getWantAgent success');
395       wantAgentObj = data;
396       let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
397       try {
398           geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
399       } catch (err) {
400           console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
401       }
402   });
403   ```
404
4055. Have the system automatically trigger the action defined for the **WantAgent** object when a device enters or exits the geofence.
406