fluttergoogle-geocoder

Getting city and country from GoogleGeocoder response


I need to make use of the google_geocoding package.

My code for it is:

Future<GeocodingResponse> getDatosGeocoding () async {
    var resultado= (await googleGeocoding.geocoding.getReverse(LatLon(40.714224,-73.961452))) ;
    
    return resultado;

  }

I have been searching the package readme and I was unable to find out how to get the city and country from the GeocodingResponse.


Solution

  • The interface unfortunately is not that granular to directly get city and country as separate values.

    But maybe this code snippet will help you:

    final response = await googleGeocoding.geocoding.getReverse(LatLon(lat, lng));
    
    if (response != null && response.results != null) {
      final geocodingResponse = response.results;
      if (geocodingResponse != null) {
        if (geocodingResponse.isNotEmpty) {
          final address = geocodingResponse[0].formattedAddress;
          if (address != null) {
            // address is available
          }
        }
      }
    }
    

    Instead of formattedAddress you could maybe also try to see what values addressComponents contains. Unfortunately the documentation is not very specific.