我正在尝试使用地理围栏开发基于位置的提醒应用。当我只使用某个地方时,它的工作非常完美。但是当我添加两个位置时,它只适用于第一个添加的位置。不会出现错误或异常。但第二个位置根本没有出现。我找不到理由。
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();
});
}
}
});
答案 0 :(得分:1)
你没有添加两个围栏。实际上,您只是想覆盖现有的:
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);
}