# Plan geofences for your app

Select nearby locations with app-defined metadata, match your own location IDs, and limit geofences to a time window in .NET.

Source: https://appportal.io/docs/sdks/dotnet/geofencing

The .NET preview can select geofences from a catalog using distance, your custom metadata, and
time windows. Your app defines the attributes and rules; AppPortal does not need to interpret
them or add fields to its schema.

**This is a planning prototype.** It returns the fences your app should monitor. Your app handles
native registration, permissions, background scheduling, notifications, and check-in.
The planner is unavailable in Flutter, Swift, and Kotlin.

## Prepare the catalog

The planner is available to [SDK source](https://appportal.io/docs/sdks/compatibility) evaluators.
The 3.0.384 NuGet release has no Location package. For a source evaluation, reference
the project for your app host:

| App host | SDK project | Add to your existing startup |
| --- | --- | --- |
| Native Android / Apple UI or managed .NET | `AppPortal.Location` | `.UseLocation()` on the AppPortal builder, before `.Start()` |
| .NET MAUI | `AppPortal.Location.Maui` | Add `.UseLocation()` to the native root before `.Start()`, then `builder.UseAppPortalLocation()` |
| Uno Platform | `AppPortal.Location.Uno` | Add `.UseLocation()` to the native root before `.Start()`, then `this.UseAppPortalLocation()` |

Import `AppPortal` and `AppPortal.Location`. These adapters share the existing runtime. MAUI
registers `IAppPortalLocation`; in other hosts using service-collection DI, add
`services.AddAppPortalLocation()` with `Microsoft.Extensions.DependencyInjection` in scope.
The examples use the equivalent `AppPortalLocation` static facade.
Create your places and fences through the [Location workflow](https://appportal.io/docs/sdks/location), then sync:

```csharp
using AppPortal.Location;

var catalog = await AppPortalLocation.SyncGeofencesAsync();
if (catalog is null)
    return;
```

A synced geofence includes its own metadata, `PlaceId`, and `GroupKey`. For this prototype,
supply place and group metadata from your app's catalog; sync does not include those attributes.

| Metadata scope | Dictionary key | Example app-owned values |
| --- | --- | --- |
| Place / location | AppPortal `PlaceId` | `locationId = west-12`, `amenity.parking = true` |
| Group | `GroupKey` | `purpose = nearby` or `purpose = check-in` |
| Geofence | Already on the synced record | Any fence-specific attributes |

Use separate dictionaries named `places` and `groups`, each with type
`IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>>`. Missing metadata is empty.
The SDK preserves keys and values without merging scopes or interpreting customer identifiers.

## Select nearby locations by their attributes

Snapshot the user's position and preferences before planning. This example selects fences in
the `nearby` group only when nearby suggestions are enabled and the location has the requested
amenity. The metadata keys and values belong to this example app:

```csharp
var nearbySuggestionsEnabled = true; // Snapshot from your app.
var requiredAmenity = "parking";
var userPosition = new Coordinate(47.61, -122.33);

var nearby = await AppPortalLocation.CreateGeofencePlanAsync(catalog, new()
{
    Near = userPosition,
    RadiusMeters = 25_000,
    Limit = 20, // Example budget; obtain the actual capacity from your OS adapter.
    PlaceMetadata = places,
    GroupMetadata = groups,
    Filter = candidate => nearbySuggestionsEnabled
        && candidate.GroupMetadata.TryGetValue("purpose", out var purpose)
        && purpose == "nearby"
        && candidate.PlaceMetadata.TryGetValue($"amenity.{requiredAmenity}", out var enabled)
        && enabled == "true"
});
```

Distance is measured to the **geofence center**, not its edge or driving distance. The planner
sorts eligible fences by distance and applies `Limit` after filtering and time checks.
Fetch enough catalog candidates before planning: a server sync limit could otherwise remove
eligible locations before your predicate sees them.

Your app decides what an eligible entry event should do, such as showing a nearby location.
Rebuild the plan when the user changes preferences so the monitor set reflects the new selection.

## Match your location ID and set a time window

For a scheduled visit, match your system's location ID in **place metadata**, then attach the
allowed check-in window. This example uses the same catalog and dictionaries, with a visit
15 minutes from now. In your app, use the scheduled time from your backend. The window opens
30 minutes early and expires 60 minutes after the scheduled start:

```csharp
var now = DateTimeOffset.UtcNow;
var visitLocationId = "west-12";
var visitStartsAt = now.AddMinutes(15); // Replace with the scheduled visit's start.

var checkIn = await AppPortalLocation.CreateGeofencePlanAsync(catalog, new()
{
    PlaceMetadata = places,
    GroupMetadata = groups,
    Filter = candidate => candidate.GroupMetadata.TryGetValue("purpose", out var purpose)
        && purpose == "check-in"
        && candidate.PlaceMetadata.TryGetValue("locationId", out var locationId)
        && locationId == visitLocationId,
    ActivationWindow = _ => new GeofenceActivationWindow(
        StartsAt: visitStartsAt.AddMinutes(-30),
        EndsAt: visitStartsAt.AddMinutes(60))
});

var active = checkIn?.GetActiveGeofences(now);
var nextChange = checkIn?.GetNextEvaluationAt(now);
```

This plan has no distance constraint, so being far away today does not exclude a future visit.
Windows use absolute instants, include the start, and exclude the end. A future window remains
in the plan without consuming an active monitoring slot.

## Apply the plan as app state changes

Use the active selection as the complete desired monitor set, removing fences no longer present.
An empty plan means monitor nothing; a **null** plan means planning failed, was cancelled, or the
client was unavailable. Do not treat null as a successful refresh.

Arrange reevaluation at `nextChange`, on app resume, and before handling a delayed OS entry event.
Rebuild when the user moves, signs out, changes a scheduled visit, or updates their preferences.
Discard an older asynchronous result if newer app state has replaced its inputs.

Predicates run once during planning, on a background thread on multithreaded .NET runtimes.
Use stable snapshots and avoid reading UI state from callbacks. Browser planning is unsupported
in this prototype and returns null. Planning does not upload metadata or scheduling state.
