In my Windows Phone 8 app, I am trying to use GetGeopositionAsync on the main page to display some items based on user location.
Calling GetGeopositionAsync does not
See my sample: http://code.msdn.microsoft.com/windowsapps/How-to-use-Cimbalino-3888977e
it uses MVVM & Cimbalino Toolkit!
In my case I set ReportInterval = 5 to solve that problem.
I know this is a bit older, but I hope that others searching for this topic find this answer helpful.
Make sure to get the user's consent before attempting to access the location services.
I was running into this problem but fixed it by calling the OnNavigatedTo event when opening the page to get their consent.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
{
// User has opted in or out of Location
return;
}
else
{
MessageBoxResult result =
MessageBox.Show("This app accesses your phone's location. Is that ok?",
"Location",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
}else
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
}
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
This is strange but GetGeoPositionAsync only returns the current position when the Geolocator is initialized with either MovementThreshold and/or ReportInterval.
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
geolocator.MovementThreshold = 5;
geolocator.ReportInterval = 500;
Geoposition geoposition = null;
try
{
geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10));
}
catch (UnauthorizedAccessException ex)
{
// location services disabled or other error
// user should setup his location
}
I found that if you created the Geolocator locally, the task will end up being cancelled. It works when I created a permanent Geolocator instance.
Well it looks like everyone hacked away until it worked... Here's what worked for me:
/// <summary>
/// HACK: For some reason Geolocator.GetGeopositionAsync hangs indefinitely.
/// The workaround is to add a PositionChanged handler.
/// </summary>
private Geoposition GetGeoposition()
{
var geolocator = new Geolocator();
var semaphoreHeldUntilPositionReady = new SemaphoreSlim(initialCount: 0);
Geoposition position = null;
geolocator.ReportInterval = 1000;
geolocator.PositionChanged += (sender, args) =>
{
position = args.Position;
semaphoreHeldUntilPositionReady.Release();
};
semaphoreHeldUntilPositionReady.Wait();
return position;
}
I found one thing. If I set accuracy to bigger one then geolocator starts return coordinates. So it dosen't work for 50 meters but works for 500 so try to use the line below instead.
geolocator.DesiredAccuracyInMeters = 500;