Geolocation works fine if I click a button (see below).
MainPage.xaml.cs:
namespace ABC;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void GetMyLocationButtonClicked(object sender, EventArgs e)
{
try
{
var location = await Geolocation.GetLastKnownLocationAsync();
if (location == null)
{
location = await Geolocation.GetLocationAsync(new GeolocationRequest()
{
DesiredAccuracy = GeolocationAccuracy.High,
Timeout = TimeSpan.FromSeconds(30)
});
}
if (location == null)
{
LatLonLabel.Text = "Something went wrong. Cannot get your location.";
}
else
{
LatLonLabel.Text = $"My Latitude and Longtidue: {location.Latitude}, {location.Longitude}";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
But if I add something as follows:
public MainPage()
{
InitializeComponent();
GetMyLocationButtonClicked(this, EventArgs.Empty); // nothing happens
}
When I start up app, nothing happens. The app doesn't ask for location permission. Any ideas? TIA.
It's better to call the Geolocation
service in OnAppearing()
where you can use async
than in constructor
. You can refer to the sample code below:
protected override async void OnAppearing()
{
base.OnAppearing();
await GetCurrentLocationAsync();
}
public async Task GetCurrentLocationAsync()
{
try
{
var location = await Geolocation.GetLastKnownLocationAsync();
if (location == null)
{
location = await Geolocation.GetLocationAsync(new GeolocationRequest()
{
DesiredAccuracy = GeolocationAccuracy.High,
Timeout = TimeSpan.FromSeconds(30)
});
}
if (location == null)
{
LatLonLabel.Text = "Something went wrong. Cannot get your location.";
}
else
{
LatLonLabel.Text = $"My Latitude and Longtidue: {location.Latitude}, {location.Longitude}";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}