GeoCoordinateWatcher仅偶尔运行一次

时间:2019-04-03 02:12:47

标签: c# wpf location

以下代码尝试获取正在运行该代码的计算机的位置:

GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
if (watcher.TryStart(false, TimeSpan.FromMilliseconds(3000)))
{
    GeoCoordinate coord = watcher.Position.Location;
    if (!coord.IsUnknown)
    {
        Printer.Print(String.Format("Current Lat: {0}, Current Long: {1}", coord.Latitude, coord.Longitude));
    }
    else // Path taken most often
    {
        throw new CommandException("Weather data unknown. (Are location services enabled?)"); 
    }
}
else
{
    throw new CommandException("Weather data unknown. (Are location services enabled?)");
}

每隔一段时间,都会打印出正确的位置,但是在大多数情况下,运行注释的else语句。经过多次测试,我意识到它是否有效完全是随机的。我做错了吗?

1 个答案:

答案 0 :(得分:2)

您遇到问题的原因可能是您正在初始化新的定位器,而不是等待状态报告状态为已就绪,然后再检查位置。

bool abort = false;
GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
if (watcher.TryStart(false, TimeSpan.FromMilliseconds(3000)))
{
    DateTime start = DateTime.Now;
    while(watcher.Status != GeoPositionStatus.Ready && !abort)
    {
        Thread.Sleep(200);
        if(DateTime.Now.Subtract(start).TotalSeconds > 5)
            abort = true;
    }

    GeoCoordinate coord = watcher.Position.Location;
    if (!coord.IsUnknown)
    {
        Printer.Print(String.Format("Current Lat: {0}, Current Long: {1}", coord.Latitude, coord.Longitude));
    }
    else // Path taken most often
    {
        throw new CommandException("Weather data unknown. (Are location services enabled?)"); 
    }
}
else
{
    throw new CommandException("Weather data unknown. (Are location services enabled?)");
}

基本上,这会添加检查以查看状态是否就绪,并最多等待5秒钟。

或者,通常应将监视程序设置为模块级别并注册PositionChanged事件,以便仅在位置实际更改时更新打印输出,而不是轮询循环以重复当前操作静止时一次又一次地定位。