Home > C#, WinRT > Using the new Geofencing APIs in Windows 8.1 Store apps

Using the new Geofencing APIs in Windows 8.1 Store apps

17/09/2013

The new Geofencing APIs that ship with Windows 8.1 allow apps to be notified when the user enters or leaves a specified Geolocation area. This feature leads to interesting scenarios: we can imagine an app that provides information as soon as the user approaches to a monument, or that shows offers valid for the entrance to a museum nearby, or even the menu of a restaurant, bus timetables, etc.

The API itself is pretty straightforward. First of all, we need to define a so called Geofence:

private void CreateGeofence(double latitude, double longitude, double radius)
{
    var id = string.Format("Posisition: {0}, {1}", latitude, longitude);
    
    // Sets the center of the Geofence.
    var position = new BasicGeoposition
        {
            Latitude = latitude,
            Longitude = longitude
        };

    // The Geofence is a circular area centered at (latitude, longitude) point, with the
    // radius in meter.
    var geocircle = new Geocircle(position, radius);

    // Sets the events that we want to handle: in this case, the entrace and the exit
    // from an area of intereset.
    var mask = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;

    // Specifies for how much time the user must have entered/exited the area before 
    // receiving the notification.
    var dwellTime = TimeSpan.FromSeconds(5);

    // Creates the Geofence and adds it to the GeofenceMonitor.
    var geofence = new Geofence(id, geocircle, mask, false, dwellTime);
    GeofenceMonitor.Current.Geofences.Add(geofence);
}

The most important instruction are the last two, in which we create the Geofence and we add it to the GeofenceMonitor, the object that is responsible of maintaining information about areas of interest and notifying the user when he enters or leaves one of them.

The definition of a Geofence instance requires some parameters:

  • A unique identifier;
  • A Geocircle that represents the circle of the area, which is in turn defined by a BasicGeoposition with given latitude and longitude and a radius in meters;
  • An enumeration that specifies how we want to be notified, i.e. if we want to be notified only when we enter or leave the area, or in both cases (as in our example);
  • A boolean for the singleUse parameter, with which we can indicate whether we want to receive notifications each time we enter or leave the geofence (false), or if we are interested in only the first time (true);
  • A TimeSpan that indicates how long we must have entered / exited before receiving the notification.

Those just shown are the most important parameters, but Geofence class provides other property to customize its behavior. As always, more details are available on MSDN documentation.

Now, our app must be configured to receive notifications about the entrance or the exit from areas of interest. To do so, we need the following code:

GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;

private async void OnGeofenceStateChanged(GeofenceMonitor sender, object e)
{
    var reports = sender.ReadReports();

    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        foreach (var report in reports)
        {
            var state = report.NewState;
            var geofence = report.Geofence;

            if (state == GeofenceState.Entered)
            {
                // User has entered the area.
                var dialog = new MessageDialog(geofence.Id, "Entrance");
                await dialog.ShowAsync();

            }
            else if (state == GeofenceState.Exited)
            {
                // User has exited from the area.
                var dialog = new MessageDialog(geofence.Id, "Exit");
                await dialog.ShowAsync();
            }
        }
    });
}

The GeofenceStateChanged event is raised when the state of one or more Geofence objects in the Geofences collection of the GeofenceMonitor has changed. In our case, it means that the user has entered or left one of the monitored areas.

When we received a notification, we use the ReadReports method, that returns the list of Geofences whose state has changed: in fact, at the same time, the user could enter or leave more than one area.

For each Geofence, we check its state (Entered or Exited) and then we show a dialog with the corresponding ID we have set in the CreateGeofence method. A real app will tipically show different content based on the location, i.e. it will provide location-aware information.

It is important to remember that Geofences added to the GeofenceMonitor are automatically saved, and they remain active for all the executions of our app. If we want to remove a Geofence, we must use the Remove method, or Clear to delete them all.

We can use Windows Simulator to test Geofencing: with it, we can simulate a specific position to verify when the user approaches to it. A sample Windows 8.1 Store app is available for download:

screenshot_09162013_230313

To use this app, we must have the Bing Maps BETA SDK for Windows 8.1 Store apps, that we can install using the Extensions and Updates command from the Tools menu of Visual Studio 2013. We also need to obtain a Bing Maps Key.

Maps

Categories: C#, WinRT
%d bloggers like this: