Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CrossGeolocator's GetPositionAsync does not work

Tags:

c#

mobile

xamarin

I am using CrossGeolocator to retrieve the current latitude and longitude of the device. However I am using it inside an OnAppearing override method and it is not working. The GetPositionAsync method hangs the App.

 protected override void OnAppearing()
 {
     base.OnAppearing();

     var position = GetPosition().Result;
     var lat = position.Latitude;
     var lon = position.Longitude;
 }

 private static async Task<Position> GetPosition()
 {
     var locator = CrossGeolocator.Current;
     locator.DesiredAccuracy = 50;

     var position = await locator.GetPositionAsync(10000);
     return position;
 }

Detail is that I am using this same GetPosition method in buttons in the application and works perfectly.

Could someone help me in this matter?

like image 990
Danilo Pádua Avatar asked Jan 20 '17 12:01

Danilo Pádua


1 Answers

Try this:

Create a global variable:

private Position _position;

Then call ur method to get the position on constructor. Re-write ur method like this:

public async void GetPosition()
{
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;
    var myPosition = await locator.GetPositionAsync();
    _position = new Position(myPosition.Latitude, myPosition.Longitude);
}

Then make a while where u want to use this:

while(_position == new Postion(0,0))
      GetPosition();
like image 64
Pedro Franco Avatar answered Sep 19 '22 15:09

Pedro Franco