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

53 lines
1.9 KiB

using Microsoft.Maui.ApplicationModel;
6 months ago
using System.Linq;
using System.Threading.Tasks;
namespace Justice.Helpers
{
public static class GeolocationHelper
6 months ago
{
6 months ago
/// <summary>
/// Fetches the user's current latitude, longitude, and readable address.
6 months ago
/// </summary>
/// <returns>A tuple containing Latitude, Longitude, and Address.</returns>
public static async Task<(double Latitude, double Longitude, string Address)> GetLocationAsync()
6 months ago
{
6 months ago
try
6 months ago
{
// Request the user's current location
6 months ago
var location = await Geolocation.Default.GetLocationAsync(new GeolocationRequest
{
DesiredAccuracy = GeolocationAccuracy.High,
Timeout = TimeSpan.FromSeconds(10)
});
if (location != null)
{
// Reverse geocode the location to get the address
6 months ago
var placemarks = await Geocoding.Default.GetPlacemarksAsync(location);
var placemark = placemarks.FirstOrDefault();
string address = placemark != null
? $"{placemark.Thoroughfare}, {placemark.Locality}, {placemark.AdminArea}, {placemark.CountryName}"
: "Address not found";
6 months ago
return (location.Latitude, location.Longitude, address);
}
throw new Exception("Location not available.");
6 months ago
}
catch (FeatureNotSupportedException)
{
throw new Exception("Location services are not supported on this device.");
6 months ago
}
catch (PermissionException)
{
throw new Exception("Location permissions are not granted.");
6 months ago
}
catch (Exception ex)
6 months ago
{
throw new Exception($"Unable to fetch location: {ex.Message}");
6 months ago
}
}
}
}