• 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
19  A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
20
21- **GNSS positioning**
22
23  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.
24
25- **Base station positioning**
26
27  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.
28
29- **WLAN or Bluetooth positioning**
30
31  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.
32
33### Working Principles
34
35Location 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.
36
37### Constraints
38
39Your 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.
40
41Since 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.
42
43
44## Applying for Location Permissions
45
46### When to Use
47
48Before 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.
49
50The system provides the following location permissions:
51
52- ohos.permission.LOCATION: used to obtain location accurate to meters.
53
54- ohos.permission.APPROXIMATELY\_LOCATION: used to obtain location accurate to 5 kilometers.
55
56- ohos.permission.LOCATION\_IN\_BACKGROUND: used to obtain location while the application is running at the background.
57
58If your application needs to access the device location information, it must first apply for required permissions.
59
60**Table 1** Ways to apply for location permissions
61
62| Target API Level| Location Permission| Permission Application Result| Location Accuracy|
63| -------- | -------- | -------- | -------- |
64| Earlier than 9| ohos.permission.LOCATION | Successful| Location accurate to meters.|
65| 9 and later| ohos.permission.LOCATION | Failed| No location obtained.|
66| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Successful| Location accurate to 5 kilometers.|
67| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Successful| Location accurate to meters.|
68
69If 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.
70
71You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
72
73For details about the permissions required for each API of the location service, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
74
75### How to Develop
76
77You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
78
79
80## Obtaining Device Location Information
81
82### When to Use
83
84You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device.
85
86Real-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.
87
88### Available APIs
89
90The following table lists the APIs used to obtain the device location information. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
91
92**Table 2** APIs for obtaining device location information
93
94| API| Description|
95| -------- | -------- |
96| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void | Registers a listener for location changes with a location request initiated.|
97| off(type: 'locationChange', callback?: Callback<Location>): void | Unregisters the listener for location changes with the corresponding location request deleted.|
98| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void | Obtains the current location. This API uses an asynchronous callback to return the result. |
99| getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | Obtains the current location. This API uses a promise to return the result. |
100| getLastLocation(): Location | Obtains the last known device location.|
101
102### How to Develop
103
1041. 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).
105
1062. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
107
108   ```ts
109   import geoLocationManager from '@ohos.geoLocationManager';
110   ```
111
1123. 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>
113   **Method 1:**
114
115   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.
116
117   **Location service scenarios**
118
119   - NAVIGATION<br>
120   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.
121
122   - TRAJECTORY\_TRACKING<br>
123   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.
124
125   - CAR\_HAILING<br>
126   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.
127
128   - DAILY\_LIFE\_SERVICE<br>
129   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.
130
131   - NO\_POWER<br>
132     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.
133
134
135          ```ts
136              export enum LocationRequestScenario {
137                   UNSET = 0x300,
138                   NAVIGATION,
139                   TRAJECTORY_TRACKING,
140                   CAR_HAILING,
141                   DAILY_LIFE_SERVICE,
142                   NO_POWER,
143               }
144          ```
145
146
147Sample code for initializing **requestInfo** for navigation:
148
149   ```ts
150   let requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
151   ```
152
153**Method 2:**
154
155If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
156
157   **Location priority policies**
158
159   - ACCURACY<br>
160      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.
161
162   - FIRST\_FIX<br>
163      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.
164
165   - LOW\_POWER<br>
166      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.
167
168         ```ts
169             export enum LocationRequestPriority {
170                  UNSET = 0x200,
171                  ACCURACY,
172                  LOW_POWER,
173                  FIRST_FIX,
174              }
175         ```
176
177Sample code for initializing **requestInfo** for the location accuracy priority policy:
178
179   ```ts
180   let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
181   ```
182
1834. Instantiate the **Callback** object for the system to report location results.
184     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.
185
186   ```ts
187   let locationChange = (location) => {
188       console.log('locationChanger: data: ' + JSON.stringify(location));
189   };
190   ```
191
1925. Start obtaining the device location.
193
194   ```ts
195   geoLocationManager.on('locationChange', requestInfo, locationChange);
196   ```
197
1986. (Optional) Stop obtaining the device location.
199
200   If your application no longer needs the device location, stop obtaining the device location to avoid high power consumption.
201
202   ```ts
203   geoLocationManager.off('locationChange', locationChange);
204   ```
205
206   If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
207
208   ```ts
209   import geoLocationManager from '@ohos.geoLocationManager';
210   try {
211       let location = geoLocationManager.getLastLocation();
212   } catch (err) {
213       console.error("errCode:" + err.code + ",errMessage:" + err.message);
214   }
215   ```
216
217
218## Geocoding and Reverse Geocoding
219
220### When to Use
221
222Describing 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:
223
224- Geocoding: converts geographic descriptions into specific coordinates.
225
226- Reverse geocoding: converts coordinates into geographic descriptions.
227
228The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc.
229
230### Available APIs
231
232The 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).
233
234**Table 3** APIs for geocoding and reverse geocoding conversion
235
236| API| Description|
237| -------- | -------- |
238| isGeocoderAvailable(): boolean; | Obtains the (reverse) geocoding service status.|
239| 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. |
240| 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. |
241| 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. |
242| 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. |
243
244### How to Develop
245
246> **NOTE**
247>
248> 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.
249
2501. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
251
252   ```ts
253   import geoLocationManager from '@ohos.geoLocationManager';
254   ```
255
2562. Check whether the **geoCoder** service is available.
257
258   Call **isGeoServiceAvailable** to check whether the **geoCoder** service is available. If the service is available, go to step 3.
259
260   ```ts
261   import geoLocationManager from '@ohos.geoLocationManager';
262   try {
263       let isAvailable = geoLocationManager.isGeocoderAvailable();
264   } catch (err) {
265       console.error("errCode:" + err.code + ",errMessage:" + err.message);
266   }
267   ```
268
2693. Obtain the geocoding conversion result.
270   - Call **getAddressesFromLocation** to convert coordinates into geographical location information.
271
272      ```ts
273      let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
274      try {
275          geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
276              if (err) {
277                  console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
278              } else {
279                  console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
280              }
281          });
282      } catch (err) {
283          console.error("errCode:" + err.code + ",errMessage:" + err.message);
284      }
285      ```
286
287      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).
288   - Call **getAddressesFromLocationName** to convert geographic descriptions into coordinates.
289
290      ```ts
291      let geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
292      try {
293          geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
294              if (err) {
295                  console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
296              } else {
297                  console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
298              }
299          });
300      } catch (err) {
301          console.error("errCode:" + err.code + ",errMessage:" + err.message);
302      }
303      ```
304
305      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).
306
307      To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
308
309
310## Geofencing
311
312### When to Use
313
314A 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.
315
316Currently, only circular geofences are supported, and the geofencing function of the GNSS chip is required.
317
318A 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.
319
320### Available APIs
321
322The following table lists the APIs used for geofencing. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
323
324**Table 4** Geofencing APIs
325
326| API| Description|
327| -------- | -------- |
328| on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Registers a listener for status change events of the specified geofence.|
329| off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Unregisters the listener for status change events of the specified geofence.|
330
331### How to Develop
332
3331. Declare the **ohos.permission.APPROXIMATELY_LOCATION** permission. For details, see [Applying for Location Permissions](#applying-for-location-permissions).
334
3352. Import the [geoLocationManager](../reference/apis/js-apis-geoLocationManager.md) and [wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) modules.
336
337   ```ts
338   import geoLocationManager from '@ohos.geoLocationManager';
339   import wantAgent from '@ohos.app.ability.wantAgent';
340   ```
341
3423. Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object.
343
344   Scenario 1: Create a **WantAgentInfo** object for starting an ability.
345
346   ```ts
347   let wantAgentObj = null; // Save the created WantAgent object for completing the trigger operations at a later time.
348
349   // Set the operation type through operationType of the WantAgentInfo object.
350   let wantAgentInfo = {
351       wants: [
352           {
353               deviceId: '',
354               bundleName: 'com.example.myapplication',
355               abilityName: 'EntryAbility',
356               action: '',
357               entities: [],
358               uri: '',
359               parameters: {}
360           }
361       ],
362       operationType: wantAgent.OperationType.START_ABILITY,
363       requestCode: 0,
364       wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
365   };
366   ```
367
368   Scenario 2: Create a **WantAgentInfo** object for publishing [common events](../application-models/common-event-overview.md).
369
370   ```ts
371   let wantAgentObj = null; // Save the created WantAgent object for completing the trigger operations at a later time.
372
373   // Set the operation type through operationType of the WantAgentInfo object.
374   let wantAgentInfo = {
375       wants: [
376           {
377               action: "event_name", // Set the event name.
378               parameters: {},
379           }
380       ],
381       operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
382       requestCode: 0,
383       wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
384   }
385   ```
386
3874. Call [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to create a **WantAgent** object.
388
389   After obtaining the **WantAgent** object, call the geofencing API to add a geofence.
390
391   ```ts
392   // Create a WantAgent object.
393   wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
394       if (err) {
395         console.error('getWantAgent err=' + JSON.stringify(err));
396         return;
397       }
398       console.info('getWantAgent success');
399       wantAgentObj = data;
400       let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
401       try {
402           geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
403       } catch (err) {
404           console.error("errCode:" + err.code + ",errMessage:" + err.message);
405       }
406   });
407   ```
408
4095. Have the system automatically trigger the action defined for the **WantAgent** object when a device enters or exits the geofence.