• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Geofencing (ArkTS)
2
3## Scenario
4
5A 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.
6
7Currently, only circular fences are supported. In addition, the geo-fencing function of the GNSS chip is required. Events of entering or leaving the fence can be accurately identified only in open outdoor areas.
8
9A 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.
10
11## Available APIs
12
13Geo-fencing uses the following interfaces. For details, see [Location Kit](../../reference/apis-location-kit/js-apis-geoLocationManager.md).
14
15| API| Description|
16| -------- | -------- |
17| [addGnssGeofence(fenceRequest: GnssGeofenceRequest): Promise<number>](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanageraddgnssgeofence12) | Adds a GNSS geofence and subscribes to geofence transition events. This API uses a promise to return the result.|
18| [removeGnssGeofence(geofenceId: number): Promise<void>](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanagerremovegnssgeofence12) | Removes a GNSS geofence and unsubscribes from geofence transition events. This API uses a promise to return the result.|
19
20## How to Develop
21
221. Declare the **ohos.permission.APPROXIMATELY_LOCATION** permission. For details, see [Applying for Location Permissions](#location-permission-guidelines.md).
23
242. Import the **geoLocationManager**, **wantAgent**, and **BusinessError** modules.
25
26   ```ts
27   import { geoLocationManager } from '@kit.LocationKit';
28   import { BusinessError } from '@kit.BasicServicesKit';
29   import { notificationManager } from '@kit.NotificationKit';
30   ```
31
323. Create a geofence.
33
34   ```ts
35   // Set the action type through operationType of WantAgentInfo.
36   let geofence: geoLocationManager.Geofence = {
37       "latitude": 34.12, "longitude": 124.11, "radius": 10000.0, "expiration": 10000.0
38   }
39   ```
40
414. Specify the types of geofence transition events to listen for. Geofence entry and exit events are used as an example.
42
43   ```ts
44   let transitionStatusList: Array<geoLocationManager.GeofenceTransitionEvent> = [
45       geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_ENTER,
46       geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_EXIT,
47   ];
48   ```
49
504. Create a notification object for **GEOFENCE_TRANSITION_EVENT_ENTER** and **GEOFENCE_TRANSITION_EVENT_EXIT**.
51
52   ```ts
53   // GEOFENCE_TRANSITION_EVENT_ENTER event
54   let notificationRequest1: notificationManager.NotificationRequest = {
55       id: 1,
56       content: {
57         notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
58         normal: {
59         title: "Geofence Notification",
60           text: "Geofence Entry",
61           additionalText: ""
62         }
63        }
64   };
65   // Create a notification object for GEOFENCE_TRANSITION_EVENT_EXIT.
66   let notificationRequest2: notificationManager.NotificationRequest = {
67     id: 2,
68     content: {
69       notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
70       normal: {
71         title: "Geofence Notification",
72         text: 'Geofence Exit',
73         additionalText: ""
74       }
75     }
76   };
77   ```
78
795. Add a geofence.
80
81   ```ts
82   // Save the created notification objects to Array in the same sequence as in transitionStatusList.
83   let notificationRequestList: Array<notificationManager.NotificationRequest> =
84     [notificationRequest1, notificationRequest2];
85   // Construct a gnssGeofenceRequest object.
86   let gnssGeofenceRequest: geoLocationManager.GnssGeofenceRequest = {
87     // Geofence attributes, including the circle center and radius.
88     geofence: geofence,
89     // Specify the types of geofence transition events to listen for.
90     monitorTransitionEvents: transitionStatusList,
91     // Specify the notification objects for geofence transition events. This parameter is optional.
92     notifications: notificationRequestList,
93     // Specify the callback used to receive geofence transition events.
94     geofenceTransitionCallback: (err : BusinessError, transition : geoLocationManager.GeofenceTransition) => {
95       if (err) {
96         console.error('geofenceTransitionCallback: err=' + JSON.stringify(err));
97       }
98       if (transition) {
99         console.info("GeofenceTransition: %{public}s", JSON.stringify(transition));
100     }
101     }
102   }
103   try {
104     // Add a geofence.
105     geoLocationManager.addGnssGeofence(gnssGeofenceRequest).then((id) => {
106       // Obtain the geofence ID after the geofence is successfully added.
107       console.info("addGnssGeofence success, fence id: " + id);
108       let fenceId = id;
109     }).catch((err: BusinessError) => {
110       console.error("addGnssGeofence failed, promise errCode:" + (err as BusinessError).code +
111         ",errMessage:" + (err as BusinessError).message);
112     });
113   } catch(error) {
114       console.error("addGnssGeofence failed, err:" + JSON.stringify(error));
115   }
116   ```
117
1185. Delete a geofence.
119
120   ```ts
121   // fenceId is obtained after geoLocationManager.addGnssGeofence is successfully executed.
122   let fenceId = 1;
123   try {
124     geoLocationManager.removeGnssGeofence(fenceId).then(() => {
125       console.info("removeGnssGeofence success fenceId:" + fenceId);
126     }).catch((error : BusinessError) => {
127       console.error("removeGnssGeofence: error=" + JSON.stringify(error));
128     });
129   } catch(error) {
130     console.error("removeGnssGeofence: error=" + JSON.stringify(error));
131   }
132   ```
133