Created
December 1, 2015 07:31
-
-
Save supreettare/0433e34f9fdf4d750bb2 to your computer and use it in GitHub Desktop.
Get current location of the device using Xamarin Mobile component. This uses dependency service in Xamarin Forms. This version fixes the TaskCancelledException you generally get on Android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GetCurrentLocationAndroid : IGetCurrentLocation | |
{ | |
/// <summary> | |
/// Instance of the Geoloactor | |
/// </summary> | |
private Geolocator _locator; | |
/// <summary> | |
/// The get current location. | |
/// </summary> | |
/// <returns> | |
/// The <see cref="Task"/>. | |
/// </returns> | |
public async Task<LocationCoordinates> GetCurrentLocation() | |
{ | |
System.EventHandler<PositionEventArgs> handler = null; | |
var result = new LocationCoordinates(); | |
var tcs = new TaskCompletionSource<LocationCoordinates>(); | |
this._locator = new Geolocator(Forms.Context) { DesiredAccuracy = 10 }; | |
try | |
{ | |
if (!this._locator.IsListening) | |
{ | |
this._locator.StartListening(1, 1); | |
} | |
handler = async (object sender, PositionEventArgs e) => | |
{ | |
result.Status = e.Position.Timestamp; | |
result.Latitude = e.Position.Latitude; | |
result.Longitude = e.Position.Longitude; | |
result.Accuracy = e.Position.Accuracy; | |
_locator.PositionChanged -= handler; | |
tcs.SetResult(result); | |
}; | |
this._locator.PositionChanged += handler; | |
await this._locator.GetPositionAsync(timeout: 10000).ContinueWith( | |
t => | |
{ | |
}); | |
} | |
catch (System.Exception ex) | |
{ | |
if (ex.InnerException.GetType().ToString() == "Xamarin.Geolocation.GeolocationException") | |
{ | |
tcs.SetException(ex); | |
} | |
else | |
{ | |
tcs.SetException(ex); | |
} | |
} | |
return tcs.Task.Result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment