|
|
|
|
using Microsoft.Maui.ApplicationModel;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Justice.Helpers
|
|
|
|
|
{
|
|
|
|
|
public static class GeolocationHelper
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Fetches the user's current latitude, longitude, and readable address.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <returns>A tuple containing Latitude, Longitude, and Address.</returns>
|
|
|
|
|
public static async Task<(double Latitude, double Longitude, string Address)> GetLocationAsync()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
// Request the user's current location
|
|
|
|
|
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
|
|
|
|
|
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";
|
|
|
|
|
|
|
|
|
|
return (location.Latitude, location.Longitude, address);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new Exception("Location not available.");
|
|
|
|
|
}
|
|
|
|
|
catch (FeatureNotSupportedException)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Location services are not supported on this device.");
|
|
|
|
|
}
|
|
|
|
|
catch (PermissionException)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Location permissions are not granted.");
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception($"Unable to fetch location: {ex.Message}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|