You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Seekers/Helpers/GeolocationHelper.cs

62 lines
2.2 KiB

6 months ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
6 months ago
using Microsoft.Maui.ApplicationModel;
6 months ago
namespace Justice.Helpers
{
public class GeolocationHelper
{
6 months ago
/// <summary>
/// Retrieves the user's current latitude, longitude, and a readable address.
/// </summary>
/// <returns>A tuple containing Latitude, Longitude, and Address.</returns>
public static async Task<(double Latitude, double Longitude, string Address)> GetCurrentLocationAsync()
6 months ago
{
6 months ago
try
6 months ago
{
6 months ago
var location = await Geolocation.Default.GetLocationAsync(new GeolocationRequest
{
DesiredAccuracy = GeolocationAccuracy.High,
Timeout = TimeSpan.FromSeconds(10)
});
6 months ago
6 months ago
if (location != null)
{
var placemarks = await Geocoding.Default.GetPlacemarksAsync(location);
var placemark = placemarks.FirstOrDefault();
string address = "Address not found";
if (placemark != null)
{
address = $"{placemark.SubLocality}, {placemark.Thoroughfare}, " +
$"{placemark.Locality}, {placemark.AdminArea}, {placemark.CountryName}";
}
return (location.Latitude, location.Longitude, address);
}
// Return a default value if location is null
return (0, 0, "Unable to fetch location.");
}
catch (FeatureNotSupportedException)
{
// Return a default value if location services are not supported
return (0, 0, "Location services are not supported on this device.");
}
catch (PermissionException)
{
// Return a default value if permissions are not granted
return (0, 0, "Location permissions are not granted.");
}
catch (Exception ex)
6 months ago
{
6 months ago
// Return a default value for other errors
return (0, 0, $"An error occurred: {ex.Message}");
6 months ago
}
}
}
}