Skip to content

Instantly share code, notes, and snippets.

@yanandrey
Last active July 15, 2021 14:18
Show Gist options
  • Save yanandrey/c2ed7ecdc1c5e4c708677a4bbc7a5213 to your computer and use it in GitHub Desktop.
Save yanandrey/c2ed7ecdc1c5e4c708677a4bbc7a5213 to your computer and use it in GitHub Desktop.
public async Task<Location> GetGeocoding(Address address)
{
var apiClient = new HttpClient();
var key = Environment.GetEnvironmentVariable("GOOGLE_KEY");
var addressToUse = BindAddress(address);
var url = "https://maps.googleapis.com/maps/api/geocode/json?" +
$"address={addressToUse}" +
$"&language=pt-BR" +
$"&key={key}";
using HttpResponseMessage responseMessage = await apiClient.GetAsync(url);
if (!responseMessage.IsSuccessStatusCode) throw new Exception(responseMessage.ReasonPhrase);
Coordenates coordinates = await responseMessage.Content.ReadAsAsync<Coordenates>();
return coordinates.Results[0].Geometry.Location;
}
private string BindAddress(Address address)
{
var city = _context.Cities
.Include(c => c.State)
.FirstOrDefault(c => c.Id == address.CityId);
var stringToUse = $"{address.Number}+" +
$"{address.Street.Replace(" ", "+")}+" +
$"{address.Neighborhood.Replace(" ", "+")},+" +
$"{city?.Name.Replace(" ", "+")},+" +
$"{city?.State.Name.Replace(" ", "+")}";
return stringToUse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment