Create a new Windows Phone 8.1 app. Add the Location capability in the Package.appxmanifest. We obviously need location capabilities for this
First thing we need is a reference to the current GeofenceMonitor.
GeofenceMonitor _monitor = GeofenceMonitor.Current;
Setting the Geofence location and hooking up the event happens in the constructor
First we hook up the GeofenceStateChanged event, we’ll look at the eventhandler in a minute. Then we create a BasicGeoPosition which holds the coordinates for, in our case, building 9 of the Microsoft campus in Redmond. Then we create a Geofence. The Geofence constructor takes two parameters, a string that functions as ID so it should be unique, and an IGeoShape. Other overloads for Geofence allow us to specify if we want to trigger the event whenever we enter or leave the geofence area.
For the ID we use a string, for the IGeoShape we use a GeoCircle. Other build-in possibilities are
- Geoboundingbox
- Geocircle
- Geopath
- Geopoint
private void MonitorOnGeofenceStateChanged(GeofenceMonitor sender, object args) { var fences = sender.ReadReports(); foreach (var report in fences) { if (report.Geofence.Id != "building9") continue; switch (report.NewState) { case GeofenceState.Entered: Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { MessageDialog dialog = new MessageDialog("Welcome to building 9"); await dialog.ShowAsync(); }); break; case GeofenceState.Exited: Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
Before we can show a message we’ll need to know what geofence triggered the event. We do that by calling ReadReports on the GeofenceMonitor. This method will return a ReadOnlyList containing GeofenceStateChangedReports. Iterating over those reports we can check the ID of the geofence and take action when the expected geofence is triggered. In this case we want to show a welcome message when someone arrives and a leaving message when someone leaves. Let’s try it out!
Launch the app in the emulator (unless you’re physically at building 9, then you can use a WP8.1 device ), open the emulator tools and set the location to building 9. You’ll have to wait some seconds before the message pops up, this is to prevent triggers being fired when just passing through a geofence location. You can manipulate this delay by using an overload of the Geofence constructor and setting the DwellTime parameter (TimeSpan).