Document Location SDK for iOS Guides Geofencing Geofences

Geofences

This feature is supported in iOS Location SDK V2.3.0 and later.

Before You Begin

Step 1: Import the Header Files

In the class that calls the geofencing feature, import the AMapFoundationKit.h and AMapLocationKit.h header files. For Swift, import these headers in your bridging header file.

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

Step 2: Configure the API Key

You must set a valid API Key before calling any location services or initializing any SDK classes.

If you are using Location SDK v2.x, you need to include the AMapLocationKit.framework and set the API Key as follows:

[AMapServices sharedServices].apiKey = @"Your API Key";

Create a Geofence

There is no limit on the number of geofences you can create. However, for optimal performance, create geofences based on your business needs and keep the total count reasonable.

The Location SDK supports four ways to create geofences:

- By AMAP POI (keyword or location-based)

- By administrative district

- By custom circle

- By custom polygon

1. Initialize the Geofence Manager

self.geoFenceManager = [[AMapGeoFenceManager alloc] init];
self.geoFenceManager.delegate = self;
self.geoFenceManager.activeAction = AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside | AMapGeoFenceActiveActionStayed;
self.geoFenceManager.allowsBackgroundLocationUpdates = YES;

Note: The activeAction property defines which fence trigger behaviors to monitor. The default is AMapGeoFenceActiveActionInside (user enters the fence). The example above monitors enter, exit, and stay (user remains inside the fence for more than 10 minutes) events.

2. Create a Geofence by AMAP POI

Two interfaces are available for creating POI-based geofences: by keyword, and by location-based search.

Create a Geofence by Keyword

- (void)addKeywordPOIRegionForMonitoringWithKeyword:(NSString *)keyword 
                                            POIType:(NSString *)type 
                                               city:(NSString *)city 
                                               size:(NSInteger)size 
                                           customID:(NSString *)customID;

Parameter Description

Name

Required

Meaning

Rule Description

keyword

Yes

POI keyword

Example: "Peking University"

type

Yes

POI type

Example: "Higher Education Institution"

city

Yes

City name where the POI is located

Example: "Beijing"

size

Yes

Number of POI results to return

Maximum number of POIs to create fences for

customID

No

Custom business ID associated with the fence

Optional identifier for your own business logic

Example

[self.geoFenceManager addKeywordPOIRegionForMonitoringWithKeyword:@"Peking University" 
                                                          POIType:@"Higher Education Institution" 
                                                             city:@"Beijing" 
                                                             size:20 
                                                         customID:@"poi_1"];

Create a Geofence by Location-Based POI Search

- (void)addAroundPOIRegionForMonitoringWithLocationPoint:(CLLocationCoordinate2D)locationPoint 
                                            aroundRadius:(NSInteger)aroundRadius 
                                                 keyword:(NSString *)keyword 
                                                 POIType:(NSString *)type 
                                                    size:(NSInteger)size 
                                                customID:(NSString *)customID;

Parameter Description

Name

Required

Meaning

Rule Description

locationPoint

Yes

Center point coordinates for the surrounding area search

Example: (39.908692, 116.397477)

aroundRadius

No

Search radius in meters

Range: 0–50000. This is the search radius, not the fence radius.

keyword

Yes

POI keyword

Example: "KFC"

type

Yes

POI type

Example: "050301"

size

Yes

Number of POI results to return

Maximum number of POIs to create fences for

customID

No

Custom business ID associated with the fence

Optional identifier for your own business logic

Example

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(39.908692, 116.397477); // Tian'anmen
[self.geoFenceManager addAroundPOIRegionForMonitoringWithLocationPoint:coordinate aroundRadius:10000 keyword:@"KFC" POIType:@"050301" size:20 customID:@"poi_2"];

3. Create a Geofence by Administrative District

Create a geofence based on an administrative district keyword.

- (void)addDistrictRegionForMonitoringWithDistrictName:(NSString *)districtName 
                                              customID:(NSString *)customID;

Parameter Description

Name

Required

Meaning

Rule Description

districtName

Yes

Administrative district keyword

Example: "Haidian District"

customID

No

Custom business ID associated with the fence

Optional identifier for your own business logic

Example

[self.geoFenceManager addDistrictRegionForMonitoringWithDistrictName:@"Haidian District" 
                                                            customID:@"district_1"];

4. Create a Custom Circular Geofence

Create a circular geofence by specifying a center point and a radius. This creates one fence at a time.

- (void)addCircleRegionForMonitoringWithCenter:(CLLocationCoordinate2D)center radius:(CLLocationDistance)radius customID:(NSString *)customID;

Parameter Description

Name

Required

Meaning

Rule Description

center

Yes

Center point coordinates of the fence

Latitude and longitude

radius

Yes

Radius of the fence in meters

Must be greater than 0

customID

No

Custom business ID associated with the fence

Optional identifier for your own business logic

Example

CLLocationCoordinate2D center = CLLocationCoordinate2DMake(39.908692, 116.397477);
[self.geoFenceManager addCircleRegionForMonitoringWithCenter:center 
                                                      radius:500 
                                                    customID:@"circle_1"];

5. Create a Custom Polygonal Geofence

Create a closed polygonal geofence from a set of coordinate points. Points are connected in order, with the last point connecting back to the first. This creates one fence at a time.

- (void)addPolygonRegionForMonitoringWithCoordinates:(CLLocationCoordinate2D *)coordinates 
                                               count:(NSInteger)count 
                                            customID:(NSString *)customID;

Parameter Description

Name

Required

Meaning

Rule Description

coordinates

Yes

Array of coordinate points defining the polygon

Minimum of 3 points. The memory for coordinates is copied internally; the caller is responsible for freeing the original memory.

count

Yes

Number of coordinate points

Must match the number of elements in the coordinates array

customID

No

Custom business ID associated with the fence

Optional identifier for your own business logic

Example

NSInteger count = 4;
CLLocationCoordinate2D *coorArr = malloc(sizeof(CLLocationCoordinate2D) * count);
coorArr[0] = CLLocationCoordinate2DMake(39.933921, 116.372927);     // Ping'anli Station
coorArr[1] = CLLocationCoordinate2DMake(39.907261, 116.376532);     // Xidan Station
coorArr[2] = CLLocationCoordinate2DMake(39.900611, 116.418161);     // Chongwenmen Station
coorArr[3] = CLLocationCoordinate2DMake(39.941949, 116.435497);     // Dongzhimen Station
[self.geoFenceManager addPolygonRegionForMonitoringWithCoordinates:coorArr count:count customID:@"polygon_1"];
    
free(coorArr);
coorArr = NULL;

Start Location Monitoring

Once a geofence is created successfully, location monitoring starts automatically — no additional setup is required. The SDK handles this internally.

Location Strategy: To optimize battery life, the SDK reduces the location update frequency when the user is far from any geofence, and increases it as the user approaches a geofence. This ensures accurate fence detection while minimizing power consumption.

Important: On iOS 9 and later, if you want the app to continue monitoring fence triggers in the background, set allowsBackgroundLocationUpdates to YES (or true in Swift). When this property is enabled, you must also enable the Location updates capability under Background Modes in your Xcode project settings. Failure to do so will cause an exception.

Handle Callbacks

Geofence creation results and status change events are delivered through the AMapGeoFenceManagerDelegate protocol.

self.geoFenceManager.delegate = self;

1. Geofence Creation Callback

Use this callback to check whether the geofence was created successfully and to inspect the created fence details.

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions customID:(NSString *)customID error:(NSError *)error {
    if (error) {
        NSLog(@"Geofence creation failed: %@", error);
    } else {
        NSLog(@"Geofence created successfully");
    }
}

2. Geofence Status Change Callback

Use this callback to detect when the user's relationship to a geofence changes, or when location monitoring fails.

The fence status represents the user's relationship to the fence, which can be: unknown, inside, outside, or stayed. A callback is triggered when both of the following conditions are met:

1. The fence status changes from A to B.

2. Status B is within the set of behaviors being monitored (as defined by activeAction).

If activeAction is changed during monitoring, all fences that match the new monitoring scope will trigger the callback again, even if their status has not changed.

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region customID:(NSString *)customID error:(NSError *)error {
    if (error) {
        NSLog(@"status changed error %@",error);
    }else{
        NSLog(@"status changed success %@",[region description]);
    }
}

Remove a Geofence

When a geofence is no longer needed, call one of the following methods to remove it.

- (void)removeTheGeoFenceRegion:(AMapGeoFenceRegion *)region;        // Remove a specific geofence
- (void)removeGeoFenceRegionsWithCustomID:(NSString *)customID;      // Remove all geofences with the specified custom ID
- (void)removeAllGeoFenceRegions;                                     // Remove all geofences