Geolocator Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Provides access to the current geographic ___location.
public ref class Geolocator sealed
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class Geolocator final
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
class Geolocator final
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class Geolocator
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
public sealed class Geolocator
function Geolocator()
Public NotInheritable Class Geolocator
- Inheritance
- Attributes
Windows requirements
Device family |
Windows 10 (introduced in 10.0.10240.0)
|
API contract |
Windows.Foundation.UniversalApiContract (introduced in v1.0)
|
App capabilities |
___location
|
Examples
Basic ___location access with permission handling
This example shows how to request ___location access and get the current position with proper error handling.
using Windows.Devices.Geolocation;
private async Task GetCurrentLocationAsync()
{
// Always request access first
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
var geolocator = new Geolocator
{
DesiredAccuracy = PositionAccuracy.Default
};
try
{
var position = await geolocator.GetGeopositionAsync();
var coordinate = position.Coordinate;
// Use ___location data for app functionality
Console.WriteLine($"Location: {coordinate.Latitude:F6}, {coordinate.Longitude:F6}");
Console.WriteLine($"Accuracy: {coordinate.Accuracy:F0} meters");
Console.WriteLine($"Source: {coordinate.PositionSource}");
// App-specific: update map, search nearby places, etc.
}
catch (UnauthorizedAccessException)
{
// Location access was revoked during the operation
Console.WriteLine("Location access was denied or revoked");
}
catch (Exception ex) when (ex.Message.Contains("timeout") || ex.Message.Contains("unavailable"))
{
// Location service timed out or unavailable
Console.WriteLine("Location service is currently unavailable");
}
catch (Exception)
{
// Other ___location service errors
Console.WriteLine("Unable to retrieve ___location at this time");
}
break;
case GeolocationAccessStatus.Denied:
// App-specific: show explanation and guide user to settings
Console.WriteLine("Location access denied. Enable ___location in Settings > Privacy & Security > Location.");
break;
case GeolocationAccessStatus.Unspecified:
Console.WriteLine("Location access error occurred");
break;
}
}
Continuous ___location tracking with status monitoring
This C++/WinRT example demonstrates continuous ___location tracking with proper event handling and resource management.
#include <winrt/Windows.Devices.Geolocation.h>
#include <winrt/Windows.Foundation.h>
using namespace winrt;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
class LocationTracker
{
private:
Geolocator m_geolocator{ nullptr };
event_token m_positionChangedToken;
event_token m_statusChangedToken;
public:
IAsyncAction StartTrackingAsync()
{
auto accessStatus = co_await Geolocator::RequestAccessAsync();
if (accessStatus == GeolocationAccessStatus::Allowed)
{
m_geolocator = Geolocator();
m_geolocator.DesiredAccuracyInMeters(50); // 50-meter accuracy
m_geolocator.MovementThreshold(10); // Update every 10 meters
// Set up event handlers
m_positionChangedToken = m_geolocator.PositionChanged(
{ this, &LocationTracker::OnPositionChanged });
m_statusChangedToken = m_geolocator.StatusChanged(
{ this, &LocationTracker::OnStatusChanged });
}
co_return;
}
void StopTracking()
{
if (m_geolocator)
{
// Unsubscribe using remove_* pattern per C++/WinRT conventions
m_geolocator.remove_PositionChanged(m_positionChangedToken);
m_geolocator.remove_StatusChanged(m_statusChangedToken);
m_geolocator = nullptr;
}
}
private:
void OnPositionChanged(Geolocator const&, PositionChangedEventArgs const& args)
{
auto coordinate = args.Position().Coordinate();
// App-specific: update tracking display, log position, etc.
// Note: This runs on a background thread
}
void OnStatusChanged(Geolocator const&, StatusChangedEventArgs const& args)
{
switch (args.Status())
{
case PositionStatus::Ready:
// Location service is available
break;
case PositionStatus::NoData:
// Location service temporarily unavailable
break;
case PositionStatus::Disabled:
// Location service disabled by user or policy
break;
}
}
};
Remarks
The Geolocator class is the primary entry point for accessing ___location data in Windows applications. It provides both one-time ___location requests and continuous ___location tracking through events.
Key properties and methods
- RequestAccessAsync: Request permission to access ___location data. Always call this before attempting to get ___location.
- GetGeopositionAsync: Get the current ___location as a one-time request.
- PositionChanged: Event that fires when the device ___location changes during continuous tracking.
- StatusChanged: Event that fires when ___location permissions or service availability changes.
- DesiredAccuracy and DesiredAccuracyInMeters: Control the accuracy and power consumption tradeoff.
Permission and privacy considerations
Important
Always call RequestAccessAsync before attempting to access ___location data. Your app must be in the foreground when requesting access, and the request must be made from the UI thread.
Location access can be denied by the user or disabled by system policy. Handle GeolocationAccessStatus.Denied appropriately in your app logic.
Accuracy and power management
The ___location service balances accuracy with battery consumption. Use DesiredAccuracy.Default for most scenarios, or specify DesiredAccuracyInMeters when you need specific precision requirements.
Key considerations:
- Single-shot requests (GetGeopositionAsync) have lower battery impact per request.
- Continuous tracking (PositionChanged events) significantly drains battery and should be used sparingly.
- Lower ReportInterval values (< 30 seconds) increase power consumption exponentially.
- Higher MovementThreshold values (> 50 meters) reduce GNSS activation frequency.
Tip
For battery-sensitive applications, start with DesiredAccuracy.Default and a MovementThreshold of 50+ meters. Monitor actual accuracy in your scenarios and adjust only if necessary.
Important
Continuous ___location tracking can significantly impact battery life. Always provide users with clear information about ___location usage and consider offering settings to control tracking frequency.
Threading behavior
Note
Location events fire on background threads. Use appropriate thread marshalling mechanisms when updating UI or performing thread-sensitive operations in event handlers.
Version history
Windows version | SDK version | Value added |
---|---|---|
1607 | 14393 | AllowFallbackToConsentlessPositions |
1607 | 14393 | DefaultGeoposition |
1607 | 14393 | IsDefaultGeopositionRecommended |
Constructors
Geolocator() |
Initializes a new Geolocator object. |
Properties
DefaultGeoposition |
Gets the ___location manually entered into the system by the user, to be utilized if no better options exist. |
DesiredAccuracy |
The accuracy level at which the Geolocator provides ___location updates. |
DesiredAccuracyInMeters |
Gets or sets the desired accuracy in meters for data returned from the ___location service. |
IsDefaultGeopositionRecommended |
Indicates whether the user should be prompted to set a default ___location manually. |
LocationStatus |
The status that indicates the ability of the Geolocator to provide ___location updates. |
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. |
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. |
Methods
AllowFallbackToConsentlessPositions() |
Sets the Geolocator to use coarse ___location as a fallback option (see Remarks). |
GetGeopositionAsync() |
Starts an asynchronous operation to retrieve the current ___location of the device. |
GetGeopositionAsync(TimeSpan, TimeSpan) |
Starts an asynchronous operation to retrieve the current ___location of the device. |
GetGeopositionHistoryAsync(DateTime, TimeSpan) |
Important The 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. |
GetGeopositionHistoryAsync(DateTime) |
Important The 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. |
RequestAccessAsync() |
Requests permission to access ___location data. Important Location consent is now required for Wi-Fi BSSID access. For details on how this affects apps using Wi-Fi or ___location APIs, see Changes to API behavior for Wi-Fi access and ___location. |
Events
PositionChanged |
Raised when the ___location is updated. |
StatusChanged |
Raised when the ability of the Geolocator to provide updated ___location changes. |