Insparkspokalen-ui/lib/services/locationService.dart
2025-05-20 09:47:02 +02:00

79 lines
2.2 KiB
Dart

import 'package:geolocator/geolocator.dart';
import 'package:google_geocoding_api/google_geocoding_api.dart';
class LocationService {
final String googleApiKey;
LocationService(this.googleApiKey);
Future<Position?> getCurrentPosition() async {
try {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
throw Exception("Platstjänster är avstängda.");
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
throw Exception("Platsbehörighet nekades.");
}
}
if (permission == LocationPermission.deniedForever) {
throw Exception("Platsbehörighet är permanent nekad.");
}
return await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
),
);
} catch (e) {
print("Fel vid platsuppslagning: $e");
return null;
}
}
Future<String> getAddressFromPosition(Position position) async {
try {
final api = GoogleGeocodingApi(googleApiKey, isLogged: true);
final results = await api.reverse(
'${position.latitude},${position.longitude}',
language: 'sv',
);
final address = results.results.firstOrNull?.mapToPretty();
if (address != null) {
final parts =
[
address.streetName,
address.city,
address.state,
].where((part) => part != null && part.isNotEmpty).toList();
return parts.join(', ');
}
return "Okänd plats";
} catch (e) {
print("Fel vid adressuppslagning: $e");
return "Okänd plats";
}
}
Future<Map<String, dynamic>> getCurrentLocationAndAddress() async {
final position = await getCurrentPosition();
if (position == null) {
return {"latitude": 0.0, "longitude": 0.0, "place": "Okänd plats"};
}
final place = await getAddressFromPosition(position);
return {
"latitude": position.latitude,
"longitude": position.longitude,
"place": place,
};
}
}