目录

On-Device GNSS Geofence Development

Currently, on-device geofencing supports only circular geofences and relies on the geofencing capability of the GNSS chip. Therefore, entry and exit events can be accurately detected only in open outdoor areas.

For example, you can use geofencing to define a geofenced area around an enterprise. When a user enters the area, a targeted notification can be delivered to the user's mobile device.

Available APIs

Geofencing uses the following interfaces. For details, see Location Kit.

API Function
addGnssGeofence(fenceRequest: GnssGeofenceRequest): Promise<number> Adds a GNSS geofence and subscribes to geofence events. This API returns the result asynchronously through a promise.
removeGnssGeofence(geofenceId: number): Promise<void> Removes a GNSS geofence and unsubscribes from geofence events. This API returns the result asynchronously through a promise.

Development Procedure

  1. Declare the ohos.permission.APPROXIMATELY_LOCATION permission. For details, see Applying for Location Permissions.

  2. Import the geoLocationManager, wantAgent, and BusinessError modules.

    import { geoLocationManager } from '@kit.LocationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { notificationManager } from '@kit.NotificationKit';
  3. Create a geofence.

    // Set the action type through operationType of WantAgentInfo.
    let geofence: geoLocationManager.Geofence = {
        "latitude": 34.12, "longitude": 124.11, "radius": 10000.0, "expiration": 10000.0
    }
  4. Specify the types of geofence transition events to listen for. Geofence entry and exit events are used as an example.

    let transitionStatusList: Array<geoLocationManager.GeofenceTransitionEvent> = [
        geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_ENTER,
        geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_EXIT,
    ];
  5. Create a notification object for GEOFENCE_TRANSITION_EVENT_ENTER and GEOFENCE_TRANSITION_EVENT_EXIT.

    // GEOFENCE_TRANSITION_EVENT_ENTER event
    let notificationRequest1: notificationManager.NotificationRequest = {
        id: 1,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
          title: "Geofence Notification",
            text: "Geofence Entry",
            additionalText: ""
          }
         }
    };
    // Create a notification object for the GEOFENCE_TRANSITION_EVENT_EXIT event.
    let notificationRequest2: notificationManager.NotificationRequest = {
      id: 2,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: "Geofence Notification",
          text: 'Geofence Exit',
          additionalText: ""
        }
      }
    };
  6. Add a geofence.

    // Save the created notification objects to Array in the same sequence as in transitionStatusList.
    let notificationRequestList: Array<notificationManager.NotificationRequest> =
      [notificationRequest1, notificationRequest2];
    // Construct a gnssGeofenceRequest object.
    let gnssGeofenceRequest: geoLocationManager.GnssGeofenceRequest = {
      // Geofence attributes, including the circle center and radius.
      geofence: geofence,
      // Specify the types of geofence transition events to listen for.
      monitorTransitionEvents: transitionStatusList,
      // Specify the notification objects for geofence transition events. This parameter is optional.
      notifications: notificationRequestList,
      // Specify the callback used to receive geofence transition events.
      geofenceTransitionCallback: (err : BusinessError, transition : geoLocationManager.GeofenceTransition) => {
        if (err) {
          console.error('geofenceTransitionCallback: err=' + JSON.stringify(err));
        }
        if (transition) {
          console.info("GeofenceTransition: %{public}s", JSON.stringify(transition));
      }
      }
    }
    try {
      // Add a geofence.
      geoLocationManager.addGnssGeofence(gnssGeofenceRequest).then((id) => {
        // Obtain the geofence ID after the geofence is successfully added.
        console.info("addGnssGeofence success, fence id: " + id);
        let fenceId = id;
      }).catch((err: BusinessError) => {
        console.error("addGnssGeofence failed, promise errCode:" + (err as BusinessError).code +
          ",errMessage:" + (err as BusinessError).message);
      });
    } catch(error) {
        console.error("addGnssGeofence failed, err:" + JSON.stringify(error));
    }
  7. Delete a geofence.

    // fenceId is obtained after geoLocationManager.addGnssGeofence is successfully executed.
    let fenceId = 1;
    try {
      geoLocationManager.removeGnssGeofence(fenceId).then(() => {
        console.info("removeGnssGeofence success fenceId:" + fenceId);
      }).catch((error : BusinessError) => {
        console.error("removeGnssGeofence: error=" + JSON.stringify(error));
      });
    } catch(error) {
      console.error("removeGnssGeofence: error=" + JSON.stringify(error));
    }