getgepositionasync需要很长时间才能完成

本文关键字:长时间 getgepositionasync | 更新日期: 2023-09-27 18:10:38

当前我使用这个代码来获取GPS:

Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.Default;
geolocator.DesiredAccuracyInMeters = 50;
try
{
    Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(30));
    MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
}
catch (Exception ex)
{
    if (ex.Message.Contains("This operation returned because the timeout period expired."))
    {
        MessageBox.Show("GPS is taking too long too complete. Pleaes try again.");
        this.SetProgressIndicator(false);
        RadBusyIndicator.IsRunning = false;
        return;
    }
    else
    {                           
        this.SetProgressIndicator(false);
        RadBusyIndicator.IsRunning = false;
        return;
    }
};

但是它总是需要很长时间才能完成,正如你可以看到的,我设置了timeout 30s,但不确定为什么当超过30秒时,它不会显示超时异常。我被这个问题难住了。有人知道吗?

getgepositionasync需要很长时间才能完成

确保wifi或手机设备处于开启状态,这样可以在GPS设备找不到信号时使用回退方法。

一个或多或少有相同问题的人在这里做了另一个帖子:
getgepositionasync不返回

关于GeoLocator类的更多信息:http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator属性

我也不知道为什么,但是TimeSpan真的很慢,但是用ReportInterval做这件事很好:

geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
    Dispatcher.BeginInvoke(() =>
    {
        myPosition = args.Position.Coordinate.ToGeoCoordinate();
    });
}
catch(Exception ex)
{
    if (ex.Data == null) throw;
    else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}