如果我点击一个按钮(见下文),地理定位工作正常。
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);
}
}
}
但是如果我添加如下内容:
public MainPage()
{
InitializeComponent();
GetMyLocationButtonClicked(this, EventArgs.Empty); // nothing happens
}
当我启动应用程序时,没有任何反应。该应用程序不要求位置许可。有任何想法吗? TIA.
最好在可以使用
Geolocation
的OnAppearing()
调用async
服务,而不是在constructor
。您可以参考下面的示例代码:
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);
}
}