Language: HTML | XAML

Quickstart: Setting up a geofence (XAML)

Applies to Windows and Windows Phone

This topic will guide you through the steps of setting up a Geofence in your Windows Runtime app using C++, C#, or Visual Basic.

Roadmap: How does this topic relate to others? See:

Introduction

There are a number of steps to take when setting up your Geofence. Besides defining the region of interest, you also need to make sure you have the proper location permissions. Finally, you need to set up an event handler in case the user changes those permissions while your app is running.

Check for location permissions

First, you may want to add code to your app during initialization to get the location. On Windows, the first time your app uses the API to get the current location, the system will prompt the user for location permission. If your app doesn't have permission from the user, then alert the user. Note that you can still set up a Geofence without location permissions but you won’t receive any notifications until the permissions have been enabled.


async private void Initialize()
{
    try 
    {
        // Get a geolocator object 
        geolocator = new Geolocator();

        // Get cancellation token
        cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;

        await geolocator.GetGeopositionAsync().AsTask(token);
 
        // other initialization for your app could go here
                                                                
    } 
    catch (UnauthorizedAccessException) 
    { 
        if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus) 
        { 
            rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage); 
        } 
        else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus) 
        { 
            rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage); 
        } 
        else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus) 
        { 
            rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage); 
        } 
    }
    catch (TaskCanceledException)
    {
        // task cancelled
    }
    catch (Exception)
    {
        if (geolocator.LocationStatus == PositionStatus.Disabled)
        {
            // On Windows Phone, this exception will be thrown when you call 
            // GetGeopositionAsync if the user has disabled locaton in Settings.
            rootPage.NotifyUser("Location has been disabled in Settings.");
        }

    } 
    finally
    {
        cts = null;
    }

}




  • Applies to Windows Phone

Note  On Windows Phone, you determine if the user has disabled location in Settings by checking the LocationStatus property. If the value is Disabled, then location is disabled. You can check this property anytime. You don't need to wait for an exception to be thrown when trying to access location.

Listen for location permission changes

Next, you want to be sure to register for permission change events, in case the user decides to turn the location permissions off for some reason. First add the event handlers to your initialization method:


DeviceAccessInformation accessInfo;
accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
accessInfo.AccessChanged += OnAccessChanged;



Then handle the permissions change to let the user know that geofencing will no longer work if location permissions are turned off:


public async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {

        if (DeviceAccessStatus.DeniedByUser == args.Status)
        {
            rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
        }
        else if (DeviceAccessStatus.DeniedBySystem == args.Status)
        {
            rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
        }
        else if (DeviceAccessStatus.Unspecified == args.Status)
        {
            rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
        }
        else if (DeviceAccessStatus.Allowed == args.Status)
        {
            // clear status
            rootPage.NotifyUser("", NotifyType.StatusMessage);
        }
        else
        {
            rootPage.NotifyUser("Unknown device access information status", NotifyType.StatusMessage);
        }
    });
}




  • Applies to Windows Phone

Note  On Windows Phone:

  • The CurrentStatus property does not indicate whether location is disabled on the device.
  • The AccessChanged event is never raised.
These APIs will compile if you are sharing code between a Windows and a Windows Phone app, but they are useful only on Windows.

Create the geofence

Now you are ready to define and set up a geofence. Some of the values that can be set for a geofence are:

  • An Id to identify it.
  • The circular region of interest, defined by the Geoshape.
  • The MonitoredStates, which indicate what geofence events you want to receive notifications for - entering the defined region, leaving the defined region, or removal of the geofence.
  • A SingleUse flag, which will remove the geofence once all the states the geofence is being monitored for have been met.
  • A DwellTime, which indicates how long the user must be in or out of the defined area before the enter/exit events are triggered.
  • The StartTime, which indicates when to start monitoring the geofence.
  • The Duration to monitor the geofence for.

private void CreateGeofence()
{
    Geofence geofence = null;

    string fenceKey = new string(Id.Text.ToCharArray());

    BasicGeoposition position;
    position.Latitude = Double.Parse(Latitude.Text);
    position.Longitude = Double.Parse(Longitude.Text);
    position.Altitude = 0.0;
    double radius = Double.Parse(Radius.Text);

    // the geofence is a circular region
    Geocircle geocircle = new Geocircle(position, radius);

    bool singleUse = (bool)SingleUse.IsChecked;

    // want to listen for enter geofence, exit geofence and remove geofence events
    // you can select a subset of these event states
    MonitoredGeofenceStates mask = 0;

    mask |= MonitoredGeofenceStates.Entered;
    mask |= MonitoredGeofenceStates.Exited;
    mask |= MonitoredGeofenceStates.Removed;

    // setting up how long you need to be in geofence for enter event to fire
    TimeSpan dwellTime;

    if ("" != DwellTime.Text)
    {
        dwellTime = new TimeSpan(ParseTimeSpan(DwellTime.Text, defaultDwellTimeSeconds));
    }
    else
    {
        dwellTime = new TimeSpan(ParseTimeSpan("0", defaultDwellTimeSeconds));
    }

    // setting up how long the geofence should be active
    TimeSpan duration;

    if ("" != Duration.Text)
    {
        duration = new TimeSpan(ParseTimeSpan(Duration.Text, 0));
    }
    else
    {
        duration = new TimeSpan(ParseTimeSpan("0", 0));
    }

    // setting up the start time of the geofence
    DateTimeOffset startTime;

    if ("" != StartTime.Text)
    {
        startTime = DateTimeOffset.Parse(StartTime.Text); 
    }
    else
    {
        // if you don't set start time in C# the start time defaults to 1/1/1601
        calendar.SetToNow();

        startTime = calendar.GetDateTime();
    }

    geofence = new Geofence(fenceKey, geocircle, mask, singleUse, dwellTime, startTime, duration);
    GeofenceMonitor.Current.Geofences.Add(geofence);

}



Related topics

Roadmaps
Roadmap for Windows Runtime apps using C# and Visual Basic
Roadmap for Windows Runtime apps using C++
Designing UX for apps
Tasks
Quickstart: Handling geofence notifications in the foreground
Quickstart: Listening for geofence events in the background
Quickstart: Handling geofence notifications from a background task
Reference
Geoshape
Geofence
Geolocator
Other resources
Guidelines for geofencing

 

 

Show:
© 2014 Microsoft