# Modules.Geofence

Provides a battery-efficient way to monitor a device's movement into or out of a geographic region.

Availability
3.1.3
3.1.3

# Overview

This feature requires a Pro or Enterprise subscription!

You use the Geofence module to define and monitor geofences in your application. A geofence is a circular region defined by a point (a latitude/longitude pair) and a radius, and represented by the Modules.Geofence.Region object. When a device moves into or out of a geofence being monitored, the module notifies your application of the event.

Enterprise customers can also define geofences on the server using the Appcelerator Cloud Services API. An application can query the server for any defined geofences and begin monitoring them. See the RegionMonitoring example in the module ZIP download.

# Getting Started

Once you have installed the module, use require() to access it from JavaScript:

var Geofence = require('ti.geofence');

# Location Permissions

Please ensure to request proper location permissions before attempting to use geofencing feautures. See Titanium.Geolocation.hasLocationPermissions and Titanium.Geolocation.requestLocationPermissions for details. Example:

if (!Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS)) {
    Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function (e) {
        if (!e.success) {
            alert('Location permissions declined!');
            return;
        }

        alert('Location permissions ready');
        // Initialize monitoring here
    });
}

# Creating and monitoring geofence regions

You use the Modules.Geofence.createRegion method to define a Modules.Geofence.Region object. A geofence is a circular area defined by a point (latitude and longitude) and a radius (in meters).

var newRegion = Geofence.createRegion({
    center: {
        latitude: 37.389601,
        longitude: -122.050169
    },
    radius: 500,
    identifier: 'Appcelerator'
});

To start monitoring a region, call the Modules.Geofence.startMonitoringForRegions method, passing it the region or regions you want to monitor.

Geofence.startMonitoringForRegions([region1, region2]);

To be notified when the device moves into or out of a geofence region, create an event listener for the Modules.Geofence.enterregions or Modules.Geofence.exitregions events, respectively. For example:

Geofence.addEventListener('enterregions', function (e) {
    e.regions.forEach(function (region) {
        // Display local notification
        showNotification({
            title: 'ENTER',
            body: 'enter - ' + region.identifier
        });
    });
});

The event object passed to the event handler contains a regions property that identifies the region(s) that were entered or exited. On iOS this property contains an array of Modules.Geofence.Region objects; on Android, it contains an array of generic objects that each contain a property called identifier. The value of this property corresponds to the one assigned to the Modules.Geofence.Region when it was created.

# Testing Geofence monitoring

You have a few options for testing geofence monitoring in your application. One approach is field testing: travel (drive, walk, etc.) between monitored regions while the application is running. You can also pass mock location data to the application running on a device or Simulator.

Note: The timing and frequency of location events may vary from one environment to another (device, OS version, network availability).

# Mock locations from the iOS Simulator

Once the application is running in the simulator, select Debug > Location in the Simulator and select a predefined location or route that you would like to be sent to the Simulator. You can also enter a custom location (latitude, longitude).

# Mock locations using Xcode

This method will work on both the iOS Simulator and on device.

  1. Launch your application once, then go to the build folder of your project and open the Xcode project found in build/iphone/.
  2. Run your project using Xcode.
  3. Once app is running, in Xcode debug area, click the Simulate Location icon to display a list of mock locations that can be sent to your application.
  4. Select one of these locations to send it to your app. Alternately, click on Add GPX File to Project... and select a GPX file with mock locations. A GPX file is provided in the example/MockLocationData folder in module download. The route starts at North De Anza Blvd and I-280 in Cupertino, CA and travels north on I-280.
  5. After adding a GPX file, go back and click on the mock locations arrow. The GPX file should now be in the list. Select the mock location to start using it.

# Mock locations on Android

Add the following to your tiapp.xml.

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

For more information, see Provide Mock Location Data (opens new window)

# Sample applications

The module ZIP file contains two Geofence sample applications (examples/Basic and examples/RegionMonitoring) and a GPX file (examples/MockLocationData) for mocking location data in Xcode.

# Properties

# monitoredRegions READONLY

Availability
3.1.3
monitoredRegions :Array<Modules.Geofence.Region>

An array of the regions currently being monitored for the current application.

Example:

var regions = Geofence.monitoredRegions;

# Methods

# createRegion

Availability
3.1.3
3.1.3
createRegion(object) Modules.Geofence.Region

Creates a geofence Modules.Geofence.Region.

Example:

var region = Geofence.createRegion({
    center: {
        latitude: 37.38960100,
        longitude: -122.05016900
    },
    radius: 30,
    identifier: 'Appcelerator'
});

Parameters

Name Type Description
object Dictionary<Modules.Geofence.Region>

Object with properties of the Modules.Geofence.Region object.

Returns


# isGooglePlayServicesAvailable DEPRECATED

Availability
3.1.3
isGooglePlayServicesAvailable() Boolean

DEPRECATED SINCE 3.0.0

Use isGooglePlayServicesAvailable in Titanium SDK 7.0.0 and later.

Returns a number value indicating the availability of Google Play Services which are required to monitor regions.

Possible values include SUCCESS, SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, and SERVICE_INVALID. Example:

var Playservices = require('ti.playservices');
var hasGooglePlayServices = Playservices.isGooglePlayServicesAvailable();

Returns

Type
Boolean

# regionMonitoringAvailable

Availability
3.1.3
regionMonitoringAvailable() Boolean

Returns a boolean that indicates if region monitoring is supported on the current device.

Example:

var canMonitor = Geofence.regionMonitoringAvailable();

Returns

Type
Boolean

# requestStateForRegion

Availability
7.1.0
requestStateForRegion() void

Asynchronously retrieve the cached state of the specified region.

The state is returned to the delegate via the regionstate event.

Returns

Type
void

# startMonitoringForRegions

Availability
3.1.3
3.1.3
startMonitoringForRegions(Region) void

Starts monitoring the Modules.Geofence.Region passed as a parameter.

Takes either an array of Modules.Geofence.Region objects or a single Modules.Geofence.Region object as an argument.

On Android, if the device is located in a Modules.Geofence.Region that has just started being monitored, an enterregions event is generated. On iOS, this scenario will not generate an enterregions event; instead, call the containsCoordinate method on the newly Region object to check if the device is located within it.

Each platform limits the number of regions that can be monitored at one time. On iOS this limit is 20 regions, and 100 regions on Android. The following example creates a new Region object and then starts monitoring it.

var region1 = Geofence.createRegion({
    center: {
        latitude: 37.389601,
        longitude: -122.050169
    },
    radius: 500,
    identifier: 'Appcelerator'
});
Geofence.startMonitoringForRegions(region1);

Parameters

Name Type Description
Region Array<Modules.Geofence.Region> | Modules.Geofence.Region

Either an array of Modules.Geofence.Region objects or a single Modules.Geofence.Region object.

Returns

Type
void

# stopMonitoringAllRegions

Availability
3.1.3
3.1.3
stopMonitoringAllRegions() void

Stops monitoring all of the regions that are currently being monitored.

This method is asynchronous on Android. The removeregions event will fire on completion.

Example:

Geofence.stopMonitoringAllRegions();

Returns

Type
void

# stopMonitoringForRegions

Availability
3.1.3
3.1.3
stopMonitoringForRegions(Region) void

Stops monitoring the specified region or regions.

Takes either an array of Modules.Geofence.Region objects or a single Modules.Geofence.Region object as an argument.

This method is asynchronous on Android. The removeregions event will fire on completion.

Geofence.stopMonitoringForRegions([region, region1]);

Parameters

Name Type Description
Region Array<Modules.Geofence.Region> | Modules.Geofence.Region

Either an array of Modules.Geofence.Region objects or a single Modules.Geofence.Region object.

Returns

Type
void

# Events

# error

Availability
3.1.3
3.1.3

Fired when there is an error, or monitoring failed for a region.

Properties

Name Type Description
error String

A string that describes the error.

errorcode Number
regions Array<Dictionary> | Array<Modules.Geofence.Region>

The regions for which monitoring failed. On iOS, this property contains an array of Modules.Geofence.Region objects representing the regions for which monitoring failed. On Android, this property contains an array of generic objects, each of which has an identifier property that corresponds to the region(s) that were entered.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# enterregions

Availability
3.1.3
3.1.3

Fired when the device enters a monitored region.

Properties

Name Type Description
regions Array<Dictionary> | Array<Modules.Geofence.Region>

The region(s) that were entered. On iOS, this property contains an array of Modules.Geofence.Region objects representing the regions that were entered. On Android, this property contains an array of generic objects, each of which has an identifier property that corresponds to the region(s) that were entered.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# exitregions

Availability
3.1.3
3.1.3

Fired when the device exits a monitored region.

Properties

Name Type Description
regions Array<Dictionary> | Array<Modules.Geofence.Region>

The region(s) that were exited. On iOS, this property contains an array of Modules.Geofence.Region objects representing the regions that were exited. On Android, this property contains an array of generic objects, each of which has an identifier property that corresponds to the region(s) that were exited.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# monitorregions

Availability
3.1.3
3.1.3

Fired when startMonitoringForRegions and monitoring has successfully started for those regions.

Properties

Name Type Description
regions Array<Dictionary> | Array<Modules.Geofence.Region>

The region(s) for which monitoring has started. On iOS, this property contains an array of Modules.Geofence.Region objects representing the regions for which monitoring has started. On Android, there is no property for you to check.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# regionstate

Availability
3.1.3
3.1.3

Fired when requestStateForRegion requested a state or there is a state transition for a monitored region.

Properties

Name Type Description
region Modules.Geofence.Region

The region that triggered the state change.

state Number

The updated region state. One of REGION_STATE_*.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# removeregions

Availability
3.1.3

Fired on Android when regions are removed using stopMonitoringForRegions or stopMonitoringAllRegions and monitoring has successfully stopped for those regions.

Properties

Name Type Description
regions Array<Dictionary> | Array<Modules.Geofence.Region>

The region(s) for which monitoring has stopped. On iOS, this property contains an array of Modules.Geofence.Region objects representing the regions for which monitoring has stopped. On Android, this property contains an array of generic objects, each of which has an identifier property that corresponds to the region(s) for which monitoring has stopped.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.

# Constants

# LOCATION_STATUS_ERROR

Availability
3.1.3
LOCATION_STATUS_ERROR :Number

Possible value of the errorcode property in the error event object indicating an unspecified error occurred.


# LOCATION_STATUS_GEOFENCE_NOT_AVAILABLE

Availability
3.1.3
LOCATION_STATUS_GEOFENCE_NOT_AVAILABLE :Number

Possible value of the errorcode property in the error event object indicating the geofence service is not available now.


# LOCATION_STATUS_GEOFENCE_TOO_MANY_GEOFENCES

Availability
3.1.3
LOCATION_STATUS_GEOFENCE_TOO_MANY_GEOFENCES :Number

Possible value of the errorcode property in the error event object indicating your application has registered more than 100 geofences.


# LOCATION_STATUS_GEOFENCE_TOO_MANY_PENDING_INTENTS

Availability
3.1.3
LOCATION_STATUS_GEOFENCE_TOO_MANY_PENDING_INTENTS :Number

Possible value of the errorcode property in the error event object.


# REGION_STATE_INSIDE

Availability
7.1.0
REGION_STATE_INSIDE :Number

Possible value of the state property in the regionstate event object.

The location is inside the given region.


# REGION_STATE_OUTSIDE

Availability
7.1.0
REGION_STATE_OUTSIDE :Number

Possible value of the state property in the regionstate event object.

The location is outside of the given region.


# REGION_STATE_UNKNOWN

Availability
7.1.0
REGION_STATE_UNKNOWN :Number

Possible value of the state property in the regionstate event object.

It is unknown whether the location is inside or outside of the region.