简体   繁体   English

GeoCoordinateWatcher仅偶尔运行一次

[英]GeoCoordinateWatcher only works once in a while

The following code attempts to get the location of the computer the code is being run on: 以下代码尝试获取在其上运行代码的计算机的位置:

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?)");
}

Every once in a while, the right location is printed, but most of the time, the commented else statement is run. 偶尔会打印正确的位置,但是大多数情况下,运行注释的else语句。 After multiple tests, I realized that whether it not it works is completely random. 经过多次测试,我意识到它是否有效完全是随机的。 Am I doing this wrong? 我做错了吗?

Probably the reason you're encountering issues is that you're initializing a new locator, but not waiting for the status to report back that it is ready before checking the location. 您可能遇到问题的原因可能是您正在初始化一个新的定位器,但没有等待状态报告已准备就绪,然后再检查位置。

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?)");
}

Basically this adds a check to see if the status is ready and waits up to 5 seconds. 基本上,这会添加检查以查看状态是否就绪,并等待最多5秒钟。

Alternatively, the watcher should typically be set up at a module level and register the PositionChanged event so that you only update your print-out when the position actually changes, rather than a polling loop that will reiterate the current position again and again while stationary. 另外,通常应将观察者设置在模块级别并注册PositionChanged事件,以便仅在位置实际更改时更新打印输出,而不是在固定时一次又一次地重复当前位置的轮询循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM