简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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