88 lines
3.2 KiB
C#
88 lines
3.2 KiB
C#
using Microsoft.Maui.Devices.Sensors;
|
|
using Microsoft.Maui.ApplicationModel;
|
|
using Microsoft.Extensions.Logging;
|
|
using LSFE.MobApp.Services;
|
|
|
|
namespace LSFE.MobApp.Helpers
|
|
{
|
|
public class DeviceHelper
|
|
{
|
|
private readonly ILogger<DeviceHelper> _logger;
|
|
|
|
public DeviceHelper(ILogger<DeviceHelper> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
//public async Task<(double Latitude, double Longitude, string Address)>
|
|
//GetCurrentLocationAsync(AddressService addressService)
|
|
//{
|
|
// var location = await Geolocation.Default.GetLocationAsync(
|
|
// new GeolocationRequest(GeolocationAccuracy.High, TimeSpan.FromSeconds(30)));
|
|
|
|
// if (location == null)
|
|
// throw new Exception("Unable to get location.");
|
|
|
|
// var address = await addressService.GetAddressAsync(
|
|
// location.Latitude,
|
|
// location.Longitude);
|
|
|
|
// return (location.Latitude, location.Longitude, address);
|
|
//}
|
|
|
|
/*public async Task<(double Latitude, double Longitude, string Address)> GetCurrentLocationAsync()
|
|
{
|
|
try
|
|
{
|
|
Location location = await Geolocation.Default.GetLastKnownLocationAsync();
|
|
|
|
if (location == null)
|
|
{
|
|
location = await Geolocation.Default.GetLocationAsync(new GeolocationRequest
|
|
{
|
|
DesiredAccuracy = GeolocationAccuracy.High,
|
|
Timeout = TimeSpan.FromSeconds(30)
|
|
});
|
|
}
|
|
|
|
if (location == null)
|
|
throw new Exception("Unable to get GPS coordinates.");
|
|
|
|
double lat = location.Latitude;
|
|
double lng = location.Longitude;
|
|
string address = $"Lat: {lat:F6}, Long: {lng:F6}";
|
|
|
|
try
|
|
{
|
|
// Reverse geocoding (requires internet)
|
|
var placemarks = await Geocoding.Default.GetPlacemarksAsync(lat, lng);
|
|
var placemark = placemarks?.FirstOrDefault();
|
|
|
|
if (placemark != null)
|
|
address = $"{placemark.Thoroughfare}, {placemark.Locality}, {placemark.AdminArea}, {placemark.CountryName}";
|
|
}
|
|
catch (Exception geoEx)
|
|
{
|
|
_logger.LogWarning(geoEx, "Reverse geocoding failed (possibly offline).");
|
|
// fallback to raw coordinates
|
|
}
|
|
|
|
return (lat, lng, address);
|
|
}
|
|
catch (FeatureNotEnabledException)
|
|
{
|
|
_logger.LogError("Location services disabled.");
|
|
throw new Exception("Please enable GPS/location services.");
|
|
}
|
|
catch (PermissionException)
|
|
{
|
|
_logger.LogError("Location permission denied.");
|
|
throw new Exception("Location permission is required to continue.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error retrieving location.");
|
|
throw;
|
|
}
|
|
}*/
|
|
}
|
|
} |