getCityAndCountryFromPosition method

Future<String> getCityAndCountryFromPosition(
  1. Position position
)

Returns a human-readable string containing the city and country from the provided Position using the Google Geocoding API.

Returns:

  • A string in the format "City, Country" or "Country" if city is not found.
  • "Unknown location" if the response is invalid or empty.

Throws:

  • A generic Exception if the HTTP request fails.

Implementation

Future<String> getCityAndCountryFromPosition(Position position) async {
  final lat = position.latitude;
  final lng = position.longitude;
  final apiKey = dotenv.env['API_KEY'];

  final url = Uri.parse(
    'https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=$apiKey',
  );

  final response = await http.get(url);
  if (response.statusCode != 200) {
    throw Exception('Failed to fetch location: ${response.statusCode}');
  }

  final data = json.decode(response.body);
  if (data['results'] == null || data['results'].isEmpty) {
    return 'Unknown location';
  }

  String? city;
  String? country;

  for (var result in data['results']) {
    for (var component in result['address_components']) {
      final types = List<String>.from(component['types']);

      if (types.contains('locality') ||
          types.contains('sublocality') ||
          types.contains('administrative_area_level_3')) {
        city ??= component['long_name'];
      }

      if (types.contains('country')) {
        country ??= component['long_name'];
      }
    }
    if (city != null && country != null) break;
  }

  if (city != null && country != null) return '$city, $country';
  if (country != null) return country;
  return 'Unknown location';
}