Geolocator Geolocator Geolocator Geolocator Class

Definition

Provides access to the current geographic location.

public : sealed class Geolocator : IGeolocator, IGeolocator2, IGeolocatorWithScalarAccuracypublic sealed class Geolocator : IGeolocator, IGeolocator2, IGeolocatorWithScalarAccuracyPublic NotInheritable Class Geolocator Implements IGeolocator, IGeolocator2, IGeolocatorWithScalarAccuracy// You can use this class in JavaScript.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Examples

This example shows how to use the Geolocator class to retrieve the device's location. For more info, see Get current location.

using Windows.Devices.Geolocation;
...
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
    case GeolocationAccessStatus.Allowed:
        _rootPage.NotifyUser("Waiting for update...", NotifyType.StatusMessage);

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

        // Subscribe to StatusChanged event to get updates of location status changes
        _geolocator.StatusChanged += OnStatusChanged;

        // Carry out the operation
        Geoposition pos = await geolocator.GetGeopositionAsync();

        UpdateLocationData(pos);
        _rootPage.NotifyUser("Location updated.", NotifyType.StatusMessage);
        break;

    case GeolocationAccessStatus.Denied:
        _rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
        LocationDisabledMessage.Visibility = Visibility.Visible;
        UpdateLocationData(null);
        break;

    case GeolocationAccessStatus.Unspecified:
        _rootPage.NotifyUser("Unspecified error.", NotifyType.ErrorMessage);
        UpdateLocationData(null);
        break;
}

Constructors

Geolocator() Geolocator() Geolocator() Geolocator()

Initializes a new Geolocator object.

public : Geolocator()public Geolocator()Public Sub New()// You can use this method in JavaScript.
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location
See Also

Properties

DefaultGeoposition DefaultGeoposition DefaultGeoposition DefaultGeoposition

Gets the location manually entered into the system by the user, to be utilized if no better options exist.

public : static IReference<BasicGeoposition> DefaultGeoposition { get; set; }public static Nullable<BasicGeoposition> DefaultGeoposition { get; set; }Public Static ReadWrite Property DefaultGeoposition As Nullable<BasicGeoposition>// You can use this property in JavaScript.
Value
IReference<BasicGeoposition> Nullable<BasicGeoposition> Nullable<BasicGeoposition> Nullable<BasicGeoposition>

The location manually entered by the user.

Attributes
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)
Capabilities
locationSystem

DesiredAccuracy DesiredAccuracy DesiredAccuracy DesiredAccuracy

The accuracy level at which the Geolocator provides location updates.

public : PositionAccuracy DesiredAccuracy { get; set; }public PositionAccuracy DesiredAccuracy { get; set; }Public ReadWrite Property DesiredAccuracy As PositionAccuracy// You can use this property in JavaScript.
Value
PositionAccuracy PositionAccuracy PositionAccuracy PositionAccuracy

The accuracy level at which the Geolocator provides location updates.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Examples

The following example shows how to set the desired accuracy in JavaScript.

var geolocator = new Windows.Devices.Geolocation.Geolocator();
geolocator.desiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.default;
geolocator.desiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.high;

The following example shows how to set the desired accuracy in C#.

Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.Default;
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;

Remarks

Set DesiredAccuracy to High only if your application requires the most accurate data available. Set DesiredAccuracy to Default to optimize for power.

Note

Some hardware may not support high accuracy location data. If your app attempts to set accuracy to a value that’s not supported, accuracy will be set to the limit that the hardware supports. Therefore, setting the DesiredAccuracy property is not guaranteed to have an effect on the accuracy of data.

The DesiredAccuracyInMeters property provides more granularity and control of the accuracy of the position results. Most applications can simply use the DesiredAccuracy property.

When neither DesiredAccuracyInMeters nor DesiredAccuracy are set, your app will use an accuracy setting of 500 meters (which corresponds to the DesiredAccuracy setting of Default). Setting DesiredAccuracy to Default or High indirectly sets DesiredAccuracyInMeters to 500 or 10 meters, respectively. When your app sets both DesiredAccuracy and DesiredAccuracyInMeters, your app will use whichever accuracy value was set last.

DesiredAccuracyInMeters DesiredAccuracyInMeters DesiredAccuracyInMeters DesiredAccuracyInMeters

Gets or sets the desired accuracy in meters for data returned from the location service.

public : IReference<uint> DesiredAccuracyInMeters { get; set; }public Nullable<uint> DesiredAccuracyInMeters { get; set; }Public ReadWrite Property DesiredAccuracyInMeters As Nullable<uint>// You can use this property in JavaScript.
Value
IReference<unsigned short> Nullable<uint> Nullable<uint> Nullable<uint>

The desired accuracy in meters for data returned from the location service.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone]

IsDefaultGeopositionRecommended IsDefaultGeopositionRecommended IsDefaultGeopositionRecommended IsDefaultGeopositionRecommended

Indicates whether the user should be prompted to set a default location manually.

public : static PlatForm::Boolean IsDefaultGeopositionRecommended { get; }public static bool IsDefaultGeopositionRecommended { get; }Public Static ReadOnly Property IsDefaultGeopositionRecommended As bool// You can use this property in JavaScript.
Value
PlatForm::Boolean bool bool bool

true if the app would benefit from a manually-set location, false if a better option is available.

Attributes
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)
Capabilities
locationSystem

LocationStatus LocationStatus LocationStatus LocationStatus

The status that indicates the ability of the Geolocator to provide location updates.

public : PositionStatus LocationStatus { get; }public PositionStatus LocationStatus { get; }Public ReadOnly Property LocationStatus As PositionStatus// You can use this property in JavaScript.
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Remarks

The LocationStatus property is updated dynamically only when a tracking session is active. Otherwise, it is either NotInitialized or Disabled.

MovementThreshold MovementThreshold MovementThreshold MovementThreshold

The distance of movement, in meters, relative to the coordinate from the last PositionChanged event, that is required for the Geolocator to raise a PositionChanged event.

public : double MovementThreshold { get; set; }public double MovementThreshold { get; set; }Public ReadWrite Property MovementThreshold As double// You can use this property in JavaScript.
Value
double double double double

The distance of required movement, in meters, for location services to raise a PositionChanged event. The default value is 0.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Remarks

The default report interval is 1 second or as frequent as the hardware can support – whichever is shorter. Location updates can be set to a different frequency if you specify a MovementThreshold or set ReportInterval to a different value. If your app sets both MovementThreshold and ReportInterval, location will be updated according to MovementThreshold.

See Also

ReportInterval ReportInterval ReportInterval ReportInterval

The requested minimum time interval between location updates, in milliseconds. If your application requires updates infrequently, set this value so that location services can conserve power by calculating location only when needed.

public : unsigned short ReportInterval { get; set; }public uint ReportInterval { get; set; }Public ReadWrite Property ReportInterval As uint// You can use this property in JavaScript.
Value
unsigned short uint uint uint

The requested minimum time interval between location updates.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Remarks

The default report interval is 1 second or as frequent as the hardware can support – whichever is shorter. Location updates can be set to a different frequency if you specify a MovementThreshold or set ReportInterval to a different value. If your app sets both MovementThreshold and ReportInterval, location will be updated according to MovementThreshold.

If another application has requested more frequent updates, by specifying a smaller value for ReportInterval, your application may receive updates at a higher frequency than requested.

See Also

Methods

AllowFallbackToConsentlessPositions() AllowFallbackToConsentlessPositions() AllowFallbackToConsentlessPositions() AllowFallbackToConsentlessPositions()

Sets the Geolocator to use Consentless Location, in which position requests will return an obfuscated location when the circumstances call for it (see Remarks).

public : void AllowFallbackToConsentlessPositions()public void AllowFallbackToConsentlessPositions()Public Function AllowFallbackToConsentlessPositions() As void// You can use this method in JavaScript.
Attributes
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Remarks

The Consentless Location feature allows the app to bypass the app-specific location switch (located in system settings) and obtain a "rough" location that is obfuscated with at least a 4km radius of uncertainty. The PositionSource property of the retrieved Geocoordinate will report Obfuscated.

Consentless Location, if enabled in the app, will be utilized when the app-specific location switch is set to off (that is, when precise location is not allowed). The system-wide location switch, however, must be still switched on in order for any location retrieval to take place.

This feature is enabled for any Geolocator object that calls AllowFallbackToConsentlessPositions — it is disabled by default.

Normally, an app that uses location services should first call RequestAccessAsync to check if its app-specific location is switched on, and if not, it should prompt the user to go to system settings and switch it on. However, an app that has Consentless Location capability does not need to call , as it can function whether location access is allowed or denied. The user may still turn on the app-specific location in order to use precise location, but this is not needed for the app's location functionality to work.

GetGeopositionAsync() GetGeopositionAsync() GetGeopositionAsync() GetGeopositionAsync()

Starts an asynchronous operation to retrieve the current location of the device.

public : IAsyncOperation<Geoposition> GetGeopositionAsync()public IAsyncOperation<Geoposition> GetGeopositionAsync()Public Function GetGeopositionAsync() As IAsyncOperation( Of Geoposition )// You can use this method in JavaScript.
Returns

An asynchronous operation that, upon completion, returns a Geoposition marking the found location.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone]

Remarks

This method throws an exception if the app doesn't have location permissions or if it times out with no location data retrieved. Therefore, the method should be called within a try/catch statement so that these common exception cases can be handled.

This method times out after 60 seconds, except when in Connected Standby. During Connected Standby, Geolocator objects can be instantiated but the Geolocator object will not find any sensors to aggregate and calls to GetGeopositionAsync will time out after 7 seconds. Upon time out, the StatusChanged event listeners will be called once with the NoData status, and the PositionChanged event listeners will never be called.

The user sets the privacy of their location data with the location privacy settings in the Settings app. Your app can access the user's location only when:

  • Location for this device... is turned on (not applicable to Windows 10 Mobile)
  • The location services setting, Location, is turned on
  • Under Choose apps that can use your location, your app is set to on
Important

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. Your app can then handle the no-permissions case without throwing an exception.

See Also

GetGeopositionAsync(TimeSpan, TimeSpan) GetGeopositionAsync(TimeSpan, TimeSpan) GetGeopositionAsync(TimeSpan, TimeSpan) GetGeopositionAsync(TimeSpan, TimeSpan)

Starts an asynchronous operation to retrieve the current location of the device.

public : IAsyncOperation<Geoposition> GetGeopositionAsync(TimeSpan maximumAge, TimeSpan timeout)public IAsyncOperation<Geoposition> GetGeopositionAsync(TimeSpan maximumAge, TimeSpan timeout)Public Function GetGeopositionAsync(maximumAge As TimeSpan, timeout As TimeSpan) As IAsyncOperation( Of Geoposition )// You can use this method in JavaScript.
Parameters
maximumAge
TimeSpan TimeSpan TimeSpan TimeSpan

The maximum acceptable age of cached location data. A TimeSpan is a time period expressed in 100-nanosecond units.

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

The timeout. A TimeSpan is a time period expressed in 100-nanosecond units.

Returns

An asynchronous operation that, upon completion, returns a Geoposition marking the found location.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone]

Remarks

A location will be returned immediately if the latest location is within an acceptable age. Otherwise, a location will not be returned until the next change. In some cases, your app may receive location data that is older than the specified maximumAge value. This is because an additional age value will be calculated based on the desired accuracy setting, and your app will use whichever of the two ages is larger. For example, say a default accuracy of 500 meters corresponds to a maximum age of 30 seconds. In that case, your app could receive 20 second old data even if you set maximumAge to 10 seconds.

See Also

GetGeopositionHistoryAsync(DateTime) GetGeopositionHistoryAsync(DateTime) GetGeopositionHistoryAsync(DateTime) GetGeopositionHistoryAsync(DateTime)

Starts an asynchronous operation to retrieve the location history of the device.

Note

This API is not available to all Windows apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime.

public : static IAsyncOperation<IVectorView<Geoposition>> GetGeopositionHistoryAsync(DateTime startTime)public static IAsyncOperation<IReadOnlyList<Geoposition>> GetGeopositionHistoryAsync(DateTimeOffset startTime)Public Static Function GetGeopositionHistoryAsync(startTime As DateTimeOffset) As IAsyncOperation( Of IReadOnlyListGeoposition )// You can use this method in JavaScript.
Parameters
startTime
DateTime DateTimeOffset DateTimeOffset DateTimeOffset

Represents the beginning of the time span for which positions are to be returned.

Returns
IAsyncOperation<IVectorView<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>>

Positions (of type Geoposition ) that were collected during the specified time span.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
locationHistory

Remarks

The GetGeopositionHistoryAsync method allows your app to asynchronously fetch a list of positions that have been collected by location services. Only positions that have been collected since the specified startTime will be returned. If no positions are available from that time span, an empty list will be returned.

This method returns only positions that have already been collected by location services in the last 24 hours; it does not resolve new positions. Specifying a time span that exceeds this 24-hour window will not yield any additional positions.

Location services collects positions only when an app or services queries for the user's location - but no more than once per second. Location history is limited to 3600 positions; if location history isn't cleared by the user, each position will be stored in location history between 1 and 24 hours.

Note

If you use a background task to call this method frequently, it's important to consider the impact that will have on the battery. Although this method doesn't trigger the GPS receiver, processor resources are still required to run the background task.

See Also

GetGeopositionHistoryAsync(DateTime, TimeSpan) GetGeopositionHistoryAsync(DateTime, TimeSpan) GetGeopositionHistoryAsync(DateTime, TimeSpan) GetGeopositionHistoryAsync(DateTime, TimeSpan)

Starts an asynchronous operation to retrieve the location history of the device.

Note

This API is not available to all Windows apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime.

public : static IAsyncOperation<IVectorView<Geoposition>> GetGeopositionHistoryAsync(DateTime startTime, TimeSpan duration)public static IAsyncOperation<IReadOnlyList<Geoposition>> GetGeopositionHistoryAsync(DateTimeOffset startTime, TimeSpan duration)Public Static Function GetGeopositionHistoryAsync(startTime As DateTimeOffset, duration As TimeSpan) As IAsyncOperation( Of IReadOnlyListGeoposition )// You can use this method in JavaScript.
Parameters
startTime
DateTime DateTimeOffset DateTimeOffset DateTimeOffset

Represents the beginning of the time span for which positions are to be returned.

duration
TimeSpan TimeSpan TimeSpan TimeSpan

Represents the length of time after startTime for which positions are to be returned.

Returns
IAsyncOperation<IVectorView<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>> IAsyncOperation<IReadOnlyList<Geoposition>>

Positions (of type Geoposition ) that were collected during the specified time span.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
locationHistory

Remarks

Only positions that were collected during the specified duration after startTime will be returned.

See Also

RequestAccessAsync() RequestAccessAsync() RequestAccessAsync() RequestAccessAsync()

Requests permission to access location data.

public : static IAsyncOperation<GeolocationAccessStatus> RequestAccessAsync()public static IAsyncOperation<GeolocationAccessStatus> RequestAccessAsync()Public Static Function RequestAccessAsync() As IAsyncOperation( Of GeolocationAccessStatus )// You can use this method in JavaScript.
Returns
Attributes

Remarks

The RequestAccessAsync method prompts the user for permission to access their location. The user is only prompted once (per app). After the first time they grant or deny permission, this method no longer prompts for permission. To help the user change location permissions after they've been prompted, we recommend providing a link to the location settings on their device.

Tip

To link to location settings from your app, call the LaunchUriAsync method with the URI "ms-settings:privacy-location ". For more info, see Launch the Windows Settings app.

See Also

Events

PositionChanged PositionChanged PositionChanged PositionChanged

Raised when the location is updated.

public : event TypedEventHandler PositionChanged<Geolocator,  PositionChangedEventArgs>public event TypedEventHandler PositionChanged<Geolocator,  PositionChangedEventArgs>Public Event PositionChanged<Geolocator,  PositionChangedEventArgs>// You can use this event in JavaScript.
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Remarks

You can access information about the event with the PositionChangedEventArgs object that is passed to your event handler.

Tip

When using an emulator, you must manually change the emulated location in order to trigger the PositionChanged event.

See Also

StatusChanged StatusChanged StatusChanged StatusChanged

Raised when the ability of the Geolocator to provide updated location changes.

public : event TypedEventHandler StatusChanged<Geolocator,  StatusChangedEventArgs>public event TypedEventHandler StatusChanged<Geolocator,  StatusChangedEventArgs>Public Event StatusChanged<Geolocator,  StatusChangedEventArgs>// You can use this event in JavaScript.
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_LOCATION [Windows Phone] location

Examples

This code example demonstrates how the StatusChanged event is handled. The Geolocator object triggers the StatusChanged event to indicate that the user's location settings changed. That event passes the corresponding status via the argument's Status property (of type PositionStatus ). Note that this method is not called from the UI thread and the Dispatcher object invokes the UI changes. For more info, see Get current location.


using Windows.UI.Core;
...
async private void OnStatusChanged(Geolocator sender, StatusChangedEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        // Show the location setting message only if status is disabled.
        LocationDisabledMessage.Visibility = Visibility.Collapsed;

        switch (e.Status)
        {
            case PositionStatus.Ready:
                // Location platform is providing valid data.
                ScenarioOutput_Status.Text = "Ready";
                _rootPage.NotifyUser("Location platform is ready.", NotifyType.StatusMessage);
                break;

            case PositionStatus.Initializing:
                // Location platform is attempting to acquire a fix. 
                ScenarioOutput_Status.Text = "Initializing";
                _rootPage.NotifyUser("Location platform is attempting to obtain a position.", NotifyType.StatusMessage);
                break;

            case PositionStatus.NoData:
                // Location platform could not obtain location data.
                ScenarioOutput_Status.Text = "No data";
                _rootPage.NotifyUser("Not able to determine the location.", NotifyType.ErrorMessage);
                break;

            case PositionStatus.Disabled:
                // The permission to access location data is denied by the user or other policies.
                ScenarioOutput_Status.Text = "Disabled";
                _rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);

                // Show message to the user to go to location settings
                LocationDisabledMessage.Visibility = Visibility.Visible;

                // Clear cached location data if any
                UpdateLocationData(null);
                break;

            case PositionStatus.NotInitialized:
                // The location platform is not initialized. This indicates that the application 
                // has not made a request for location data.
                ScenarioOutput_Status.Text = "Not initialized";
                _rootPage.NotifyUser("No request for location is made yet.", NotifyType.StatusMessage);
                break;

            case PositionStatus.NotAvailable:
                // The location platform is not available on this version of the OS.
                ScenarioOutput_Status.Text = "Not available";
                _rootPage.NotifyUser("Location is not available on this version of the OS.", NotifyType.ErrorMessage);
                break;

            default:
                ScenarioOutput_Status.Text = "Unknown";
                _rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
                break;
        }
    });
}

Remarks

You can access information about the event with the StatusChangedEventArgs object that is passed to your event handler.

When using a geofence, use the GeofenceMonitor 's StatusChanged event to monitor changes in location permissions instead of this event from the Geolocator class. A GeofenceMonitorStatus of Disabled is equivalent to a **Disabled **PositionStatus - both indicate that the app does not have permission to access location.

See Also

See Also