getAddressFromLatLng method

Future<Map<String, String?>> getAddressFromLatLng(
  1. double lat,
  2. double lng
)

Converts geographic coordinates (latitude and longitude) into a human-readable address.

Returns a Map containing the city, country, and full address corresponding to the provided latitude and longitude. If the address cannot be determined, the map values will be null.

  • Parameters:
    • lat: The latitude of the location.
    • lng: The longitude of the location.
  • Returns: A Map with keys 'city', 'country', and 'address', each containing a string value or null if the address could not be determined.

Implementation

Future<Map<String, String?>> getAddressFromLatLng(
    double lat, double lng) async {
  try {
    List<Placemark> placemarks = await placemarkFromCoordinates(lat, lng);

    if (placemarks.isNotEmpty) {
      Placemark place = placemarks[0];

      String? city = place.locality;
      String? country = place.country;
      String? address =
          '${place.street}, ${place.locality}, ${place.country}';

      return {
        'city': city,
        'country': country,
        'address': address,
      };
    } else {
      return {
        'city': null,
        'country': null,
        'address': null,
      };
    }
  } catch (e) {
    print('Failed to get address: $e');
    return {
      'city': null,
      'country': null,
      'address': null,
    };
    // throw Exception('Failed to get address: $e');
  }
}