Home > Mobile >  .NET MAUI GeolocationRequest - What settings to provide?
.NET MAUI GeolocationRequest - What settings to provide?

Time:01-03

I am using the following code to get the Lat/Long and display.

        labelLatLong.Text = "Checking Lat Long. Please wait...";
        var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(15));
        CancellationTokenSource cts = new CancellationTokenSource();
        try
        {
            var location = Geolocation.GetLocationAsync(request, cts.Token);
            if (location != null)
            {
                labelLatLong.Text = $"Latitude: {location.Result.Latitude}, Longitude: {location.Result.Longitude}, Altitude: {location.Result.Altitude}";
            }
        }
        catch {
            labelLatLong.Text = "Unable to get location.";
        }

For some reason, I am not getting the location value and there is no exception thrown and I cannot debug beyond the line 'GetLocationAsync', and the application says "App not responding"

I am using Visual Studio 17.4.3, Pixel 5 (API 33) android emulator.

I already gave permissions 'All the time' in the android emulator.

My laptop also has the location enabled.

Are there any other settings, I should be looking at?

Any suggestions? Appreciate your help. Thank you!

CodePudding user response:

In your xaml.cs:

private async void Button_Clicked(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)
            {
                labelLatLong.Text = "Unable to get location.";
            }
            else
            {
                labelLatLong.Text = $"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}";
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
}
  • Related