3
\$\begingroup\$

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;
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  1. Use if.else if.else if ladder: Instead of multiple conditions of if.if.if, you should use if.else if.else if ladder. The advantage of latter is that once a condition is met, the next conditions are skipped. But using only if.if.if means all the ifs are walked through irrespective of any if matching the condition. Read more about it here

  1. It is generally a good idea to save repeating variables like place.address_components[i][componentForm[addressType]] in a variable to avoid its repetition and errors

  1. Use object to store address avoiding all if conditions: Use object to store the address. place.address_components[i][componentForm[addressType]] is common value to be store. The only thing changing is addressType. So, make addressType as key with value place.address_components[i][componentForm[addressType]]. This will skip the need for if conditions.

You will get address object of like:

{
  "street_number": "1600",
  "route": "Amphitheatre Pkwy",
  "locality": "Mountain View",
  "administrative_area_level_1": "CA",
  "postal_code": "94043"
}

And this can be printed where ever you want by using Object.key

If you want to preserve the naming conventions in code such as state instead of administrative_area_level_1 that can also be done by creating another mapping object


Updated Code

var place = {"address_components":[{"long_name":"1600","short_name":"1600","types":["street_number"]},{"long_name":"Amphitheatre Pkwy","short_name":"Amphitheatre Pkwy","types":["route"]},{"long_name":"Mountain View","short_name":"Mountain View","types":["locality","political"]},{"long_name":"Santa Clara County","short_name":"Santa Clara County","types":["administrative_area_level_2","political"]},{"long_name":"California","short_name":"CA","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]},{"long_name":"94043","short_name":"94043","types":["postal_code"]}],"formatted_address":"1600 Amphitheatre Parkway, Mountain View, CA 94043, USA","geometry":{"location":{"lat":37.4224764,"lng":-122.0842499},"location_type":"ROOFTOP","viewport":{"northeast":{"lat":37.4238253802915,"lng":-122.0829009197085},"southwest":{"lat":37.4211274197085,"lng":-122.0855988802915}}},"place_id":"ChIJ2eUgeAK6j4ARbn5u_wAGqWA","types":["street_address"]}

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  postal_code: 'short_name'
};

var addressObj = {}

for (var i = 0; i < place.address_components.length; i++) {
  var addressType = place.address_components[i].types[0];
  if (componentForm[addressType]) {
      addressObj[addressType] = place.address_components[i][componentForm[addressType]]
  }
}

console.log(addressObj)

document.getElementById('fullAddress').innerHTML = addressObj.street_number + ' ' + addressObj.route + ', ' + addressObj.locality + ', ' + addressObj.administrative_area_level_1 + ' ' + addressObj.postal_code;
<div id="fullAddress"></div>

The above json is copied from https://developers.google.com/maps/documentation/geocoding/intro

Hope it helps. Revert for any doubts.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.