如何在 windows 8.1 中使用 c# 首次启动 App 时获取设备的当前位置?

How to fetch current location of device when App is launched first time in windows 8.1 using c#?

我想在应用程序首次启动时获取当前位置。所以我在 App.xaml.cs 文件中添加了以下代码,但我面临的问题是获取位置需要花费大量时间。我认为发生这种情况是因为我没有允许或阻止位置跟踪的对话框。

var location=new Windows.Devices.Geolocation.Geolocator();
Geoposition pos=await location.GetGeopositionAsync();
GetLocation.Lat = pos.Coordinate.Point.Position.Latitude.ToString(); 
GetLocation.Long = pos.Coordinate.Point.Position.Longitude.ToString();

我在 App.xaml.cs 页面的 OnLaunched 事件中添加了上面的代码,GetLocation 是一个 class 我存储当前位置的地方。

任何人都可以提出可能是什么问题吗?

如果第一次你的意思是每次打开应用程序时(对于单个持仓会话),我尝试了一个解决方案并为 me.Using Windows.Devices.Geolocation 工作,我的代码如下:

public async void MyLocationFinder()
    {
        Geolocator MyGeolocator = new Geolocator();
        MyGeolocator.DesiredAccuracyInMeters = 50;
        try
        {
            Geoposition MyGeoposition = await MyGeolocator.GetGeopositionAsync(
               maximumAge: TimeSpan.FromMinutes(5),
               timeout: TimeSpan.FromSeconds(10) );
            LatitudeTextBlock.Text = MyGeoposition.Coordinate.Latitude.ToString("0.00");
            LongitudeTextBlock.Text = MyGeoposition.Coordinate.Longitude.ToString("0.00");
        }
        catch (UnauthorizedAccessException)
        {
            //The app doesn't has the right capability or the location master switch is off
            StatusTextBlock.Text = "Location is Disabled in phone storage.";
        }
    }

您可以在 app.xaml.cs 的 OnLaunched 函数中调用 MyLocationFinder() 方法,如果这样做,您必须从代码中删除 Textblock 部分,并且可以用任何全局声明的变量替换它用另一种方法将它存储到 class 中。