Skip to content

Instantly share code, notes, and snippets.

@supreettare
Created December 1, 2015 07:31
Show Gist options
  • Save supreettare/0433e34f9fdf4d750bb2 to your computer and use it in GitHub Desktop.
Save supreettare/0433e34f9fdf4d750bb2 to your computer and use it in GitHub Desktop.

Revisions

  1. supreettare created this gist Dec 1, 2015.
    58 changes: 58 additions & 0 deletions GetCurrentLocationAndroid.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    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;
    }
    }