Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save powerdude/b32d1618fe7f9e61db18 to your computer and use it in GitHub Desktop.
Save powerdude/b32d1618fe7f9e61db18 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.
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