如何为 WP 应用程序添加多个地理围栏?

How to add multiple geofences for WP app?

我正在尝试使用地理围栏开发基于位置的提醒应用程序。当我只使用一个位置时,它工作得很好。但是当我添加两个位置时,它只适用于第一个添加的位置。没有错误或异常出现。但是第二个位置根本没有出现。我找不到原因。

    BasicGeoposition pos1 = new BasicGeoposition { Latitude = 6.931522, Longitude = 79.842005 };
    BasicGeoposition pos2 = new BasicGeoposition { Latitude = 6.978166, Longitude = 79.927376 };

        Geofence fence1 = new Geofence("loc", new Geocircle(pos1, 100));
        Geofence fence2 = new Geofence("loc", new Geocircle(pos2, 100));

        try
        {
            monitor.Geofences.Add(fence1);
            monitor.Geofences.Add(fence2);
        }

这就是我创建位置并添加到地理围栏的方式。然后循环调用;

var reports = sender.ReadReports();
        await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
        {
            foreach (GeofenceStateChangeReport changeReport in reports)
            {
                if (changeReport.NewState == GeofenceState.Entered)
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                        {
                            MessageDialog dialog = new MessageDialog("u re in the location");
                            await dialog.ShowAsync();
                        });
                }
                if (changeReport.NewState == GeofenceState.Exited)
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                        {
                            MessageDialog dialog = new MessageDialog("u exited from the location");
                            await dialog.ShowAsync();
                        });

                }
            }
        });

您没有添加两个栅栏。事实上,您只是想覆盖现有的:

Geofence fence1 = new Geofence("loc", new Geocircle(pos1, 100));
Geofence fence2 = new Geofence("loc", new Geocircle(pos2, 100));

loc 是您为围栏提供的密钥 - 这个密钥应该是唯一的 (http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geofencing.geofence.aspx#constructors)。尝试:

Geofence fence1 = new Geofence("loc1", new Geocircle(pos1, 100));
Geofence fence2 = new Geofence("loc2", new Geocircle(pos2, 100));  

我建议您将添加新栅栏封装到一个方法中,因为您还应该检查现有栅栏:

private void addGeoFence(Geopoint gp, String name, double radius)
{
    // Always remove the old fence if there is any
    var oldFence = GeofenceMonitor.Current.Geofences.Where(gf => gf.Id == name).FirstOrDefault();
    if (oldFence != null)
        GeofenceMonitor.Current.Geofences.Remove(oldFence);
    Geocircle gc = new Geocircle(gp.Position, radius);
    // Listen for all events:
    MonitoredGeofenceStates mask = 0;
    mask |= MonitoredGeofenceStates.Entered;
    mask |= MonitoredGeofenceStates.Exited;
    mask |= MonitoredGeofenceStates.Removed;
    // Construct and add the fence with a dwelltime of 5 seconds.
    Geofence newFence = new Geofence(new string(name.ToCharArray()), gc, mask, false, TimeSpan.FromSeconds(5), DateTimeOffset.Now, new TimeSpan(0));
    GeofenceMonitor.Current.Geofences.Add(newFence);
}