在wp8中使用async和await的问题

时间:2014-07-28 17:36:12

标签: c# windows-phone-8

我正在启用位置设置(如果已禁用)并尝试使用以下代码获取当前位置。

    if (locator.LocationStatus == PositionStatus.Disabled)
        {
            MessageBox.Show("Please enable the Location services", "Alert", MessageBoxButton.OK);
            await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
        }
        if (locator.LocationStatus == PositionStatus.Ready)
        {
            Geoposition geoposition;
            Geocoordinate geocoordinate;
            GeoCoordinate geoCor = null;
            geoposition = await locator.GetGeopositionAsync();
            geocoordinate = geoposition.Coordinate;
            geoCor = CoordinateConverter.ConvertGeocoordinate(geocoordinate);
            ReverseGeocodeQuery reverseQuery = new ReverseGeocodeQuery
            {
                GeoCoordinate = geoCor
            };
        }

执行“await”后,只需转到下一个语句即可。所以没有得到正确的结果。我知道等待将异步工作但是下一个基于等待结果的语句怎么样?

geoposition = await geolocator.GetGeopositionAsync();
            geocoordinate = geoposition.Coordinate;
            geoCor = CoordinateConverter.ConvertGeocoordinate(geocoordinate);
            ReverseGeocodeQuery reverseQuery = new ReverseGeocodeQuery
            {
                GeoCoordinate = geoCor
            };
            reverseQuery.QueryCompleted += (s, e) =>
                {
                    if (e.Error != null)
                        return;
                    if (e.Result != null && e.Result.Count > 0 && e.Result[0].Information != null && e.Result[0].Information.Address != null)
                        city = e.Result[0].Information.Address.City;
                };
            reverseQuery.QueryAsync();
            this.mapWithMyLocation.Center = geoCor;
            this.mapWithMyLocation.ZoomLevel = 10;

它正确显示地理坐标......但没有得到地址。

1 个答案:

答案 0 :(得分:-1)

如果我理解您的问题是正确的,那么您应该注意位置更改事件或指定所需的报告间隔。例如:

{
    ...
    locator.DesiredAccuracy = PositionAccuracy.High;
    locator.MovementThreshold = 5d;
    // locator.ReportInterval = (uint)TimeSpan.FromSeconds(5).TotalMilliseconds; 
    locator.PositionChanged += RaiseLocationChanged;
    ...
}

private void RaiseLocationChanged(Geolocator sender, PositionChangedEventArgs args)
{
    // Your reverse geocode etc. logic might go here...
    var location = CoordinateConverter.ConvertGeocoordinate(args.Position.Coordinate);
}