Search code examples
c#xamlgeolocationwin-universal-appuwp

Windows Universal (UWP) Geolocation API Permissions


The new API for Geolocation in Windows Universal (Windows 10 apps) has a new way for allowing access to a user's location.

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.

I'm running some very simple code for Geolocation, on the UI thread as shown below, but I get location permission "denied" every time and no prompt to allow location permissions. Has anyone else run into this? How do I get the prompt to allow location permissions for geolocation in a Windows 10 app?

Geolocation method

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;
        }
    }

Where it's called:

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

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

        uxForecastList.Visibility = Visibility.Visible;
    }

Solution

  • You have to set the "Location" capability. You can do this in the appmanifest.

    In the screenshot you find where to set the capability: enter image description here

    Find more info here:

    https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.aspx (Scroll all down to find info on capabilities)