如何为 WP 应用程序添加多个地理围栏
本文关键字:添加 WP 应用程序 | 更新日期: 2023-09-27 18:36:42
我正在尝试使用地理围栏开发一个基于位置的提醒应用程序。当我只使用一个定位器时,它工作得很好。但是当我添加两个位置时,它仅适用于第一个添加的位置。不显示任何错误或异常。但是第二个位置根本没有出现。我找不到原因。
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);
}