c# - Windows 通用 (UWP) 地理定位 API 权限

标签 c# xaml geolocation win-universal-app uwp

Windows Universal(Windows 10 应用程序)中用于地理定位的新 API 提供了一种允许访问用户位置的新方法。

Starting in Windows 10, call the RequestAccessAsync method before accessing the user’s location. At that time, your app must be in the foreground and RequestAccessAsync must be called from the UI thread.

我在 UI 线程上运行了一些非常简单的地理定位代码,如下所示,但我每次都获得位置权限“被拒绝”并且没有提示允许位置权限。还有其他人遇到过这个吗? 如何获得允许在 Windows 10 应用中进行地理定位的位置权限的提示?

地理定位方法

private async Task<ForecastRequest> GetPositionAsync()
    {
        try
        {

            // Request permission to access location
            var accessStatus = await Geolocator.RequestAccessAsync();

            if (accessStatus == GeolocationAccessStatus.Allowed)
            {
                // Get cancellation token
                _cts = new CancellationTokenSource();
                CancellationToken token = _cts.Token;

                // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = _desireAccuracyInMetersValue };

                // Carry out the operation
                _pos = await geolocator.GetGeopositionAsync().AsTask(token);

                return new ForecastRequest()
                {
                    Lat = (float)_pos.Coordinate.Point.Position.Latitude,
                    Lon = (float)_pos.Coordinate.Point.Position.Longitude,
                    Unit = Common.Unit.us
                };
            }
            else
                throw new Exception("Problem with location permissions or access");

        }
        catch (TaskCanceledException tce)
        {
            throw new Exception("Task cancelled" + tce.Message);
        }
        finally
        {
            _cts = null;
        }
    }

在哪里调用:

protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        ForecastViewModel vm = await ForecastViewModel.BuildViewModelAsync(await GetPositionAsync());
        DataContext = vm.Forecast;

        uxForecastList.Visibility = Visibility.Visible;
    }

最佳答案

您必须设置“位置”功能。您可以在应用程序 list 中执行此操作。

在屏幕截图中,您可以找到设置功能的位置: enter image description here

在此处查找更多信息:

https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.aspx (向下滚动以查找有关功能的信息)

关于c# - Windows 通用 (UWP) 地理定位 API 权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323942/

相关文章:

c# - C#中的MDI子窗体问题

c# - SQL 数据库中的多个条目而不是一个条目。 (可能是由于 session ?)

c# - Windows 应用商店应用程序中的文字描边

database - 是否有可以查询本地城市名称的公共(public)地理定位系统?

c# - 为什么我仍然可以序列化没有属性 [System.SerializableAttribute()] 的类?

c# - C#如何获取单词对应的发音音素?

c# - 设置源数据时删除过渡

c# - 如何在 WPF 中获取视觉对象的渲染大小?

javascript - 变量被绑定(bind)到 getCurrentLocation 函数的回调。为什么这个关闭不起作用?

Android 4.1 Geocoder.getLocationFromName() 抛出 IOException : Unable to parse response from server ONLY over 3G