0

I'm calling google maps geocode and looping over the address_components struct and tring to output the city name. I'd like to store the postal_town as the city name but if it does not exist then use the administrative_area_level_2 instead.

The problem is that even if a postal_town is returned the administrative_area_level_2 is still being used. Can anybody see what i'm doing wrong?

for(var i=0, len=result.address_components.length; i<len; i++) {
                var ac = result.address_components[i];

                if(ac.types.indexOf("postal_town") >= 0){
                    state = $('#sharesparestepAddressCity').val(ac.long_name);
                }else if(ac.types.indexOf("administrative_area_level_2") >= 0){
                    state = $('#sharesparestepAddressCity').val(ac.long_name);   
                }
            }
James Privett
  • 1,079
  • 3
  • 15
  • 23

1 Answers1

0

If both exist, your code will return the last one found. Add a break to stop processing when you find the one you want.

for(var i=0, len=result.address_components.length; i<len; i++) {
  var ac = result.address_components[i];
  if(ac.types.indexOf("postal_town") >= 0){
     state = $('#sharesparestepAddressCity').val(ac.long_name);
     break;
  } else if(ac.types.indexOf("administrative_area_level_2") >= 0){
     state = $('#sharesparestepAddressCity').val(ac.long_name);   
  }
}
geocodezip
  • 158,664
  • 13
  • 220
  • 245