MAUI 地理定位在 MainPage 构造函数中不起作用

问题描述 投票:0回答:1

如果我点击一个按钮(见下文),地理定位工作正常。

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 maui
1个回答
0
投票

最好在可以使用

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);

        }

    }


© www.soinside.com 2019 - 2024. All rights reserved.