You have the GeoLocator class in the Windows.Devices.GeoLocation namespace.
As a developer the first thing you need to be sure of is that the location capabilities in the Package.appxmanifest are enabled as shown below.
The following is a sample code to fetch the Location information.
- private Geolocator _geolocator = null;
- async private void GetGeolocation()
- {
- _geolocator = new Geolocator();
-
-
- _geolocator.DesiredAccuracyInMeters = 50;
- try
- {
-
- await _geolocator.GetGeopositionAsync();
- }
- catch
- {
-
-
- await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
- }
- }
You can set the timeout period to fetch the location information and also you can set the pool time interval before which the location API is called again.
- Geoposition pos = await _geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(15));
The preceding piece of code says that if a request is made then get the location information and then the system will check the time interval since the last request was made. If the request is made within 10 minutes then the last cached value will be returned, if not then he knows the values will be fetched and also the API will timeout if the request does not respond within 15 minutes of the request.
How to Cancel a request made to get the Geo location informationIf you have requested location information and for some reason you want to cancel the request then all you need to do is to use the
CancellationToken Object in conjunction with the
GeoLocator object as shown below.
- private CancellationTokenSource _cts = null;
- async private void GetGeolocation()
- {
- _geolocator = new Geolocator();
- _cts = new CancellationTokenSource();
- CancellationToken token = _cts.Token;
-
-
- _geolocator.DesiredAccuracyInMeters = 50;
- try
- {
-
- }
- catch
- {
-
-
- await Launcher.LaunchUriAsync(new Uri("ms-settings-location:")); }
- }
-
- {
- if (_cts != null)
- { _cts.Cancel();
- _cts = null;
- }
- }
How to Track Location Changes
If you want real-time info as soon as the user location changes then you need to subscribe to the
StatusChanged and
PositionChanged events of the
GeoLocator object.
The following is the code snippet for that:
- private Geolocator _geolocator = new Geolocator();
- TrackMyLocation()
- {
- _geolocator.StatusChanged += _geolocator_StatusChanged; _geolocator.PositionChanged += _geolocator_PositionChanged;
- }
-
- void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
- {
-
- }
-
- void _geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
- {
-
-
-
-
-
-
- }