async Task GetClosestAsync() { if (IsBusy || Monkeys.Count == 0) { return; } try { var location = await Geolocation.GetLastKnownLocationAsync(); if (location == null) { location = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(30) }); } var first = Monkeys.OrderBy(m => location.CalculateDistance( new Location(m.Latitude, m.Longitude), DistanceUnits.Miles)) .FirstOrDefault(); await Application.Current.MainPage.DisplayAlert("", first.Name + " " + first.Location, "OK"); } catch (Exception ex) { Debug.WriteLine($"Unable to query location: {ex.Message}"); await Application.Current.MainPage.DisplayAlert("Error!", ex.Message, "OK"); } }
private async Task FindMonkeyClosestToCurrentLocation() { if (IsBusy || Monkeys.Count == 0) { return; } IsBusy = true; try { var location = await Geolocation.GetLastKnownLocationAsync() ?? await Geolocation.GetLocationAsync(new GeolocationRequest() { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(GpsLocationPingTimeoutInSeconds) }); var firstClosestMonkey = Monkeys.OrderBy(monkey => location.CalculateDistance(new Location(monkey.Latitude, monkey.Longitude), DistanceUnits.Kilometers)) .First(); await Application.Current.MainPage.DisplayAlert("Closest Monkey", $"{firstClosestMonkey.Name} at {firstClosestMonkey.Location}", "OK"); } catch (Exception ex) { Debug.WriteLine($"Unable to query location: {ex.Message}"); await Application.Current.MainPage.DisplayAlert("Error!", ex.Message, "OK"); } finally { IsBusy = false; } }