I am using the following code to format an address retrieved using the Google Places API. According to Googles docs they recommend looping through the response based on what you list in the componentForm
array. Is there a way to optimize this code and simplify it without having to specify the individual if statements?
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
postal_code: 'short_name'
};
var place = searchaddress.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
if (addressType == 'street_number') {
var streetNumber = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'route') {
var route = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'locality') {
var locality = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'administrative_area_level_1') {
var state = place.address_components[i][componentForm[addressType]];
}
if (addressType == 'postal_code') {
var zipcode = place.address_components[i][componentForm[addressType]];
}
}
}
document.getElementById('fullAddress').value = streetNumber + ' ' + route + ', ' + locality + ', ' + state + ' ' + zipcode;