One solution to this problem is to loop through the address_components array and check the types property of each component to find the correct one. Here's an updated version of the script that does this:
<script>
function initialize() {
var input = document.getElementById('addressLookUp');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
console.log(place);
// loop through address components to find correct values
for (var i = 0; i < place.address_components.length; i++) {
var component = place.address_components[i];
if (component.types.indexOf('street_number') !== -1) {
document.getElementById('street_number').value = component.long_name;
} else if (component.types.indexOf('route') !== -1) {
document.getElementById('route').value = component.long_name;
} else if (component.types.indexOf('locality') !== -1) {
document.getElementById('locality').value = component.long_name;
} else if (component.types.indexOf('administrative_area_level_1') !== -1) {
document.getElementById('administrative_area_level_1').value = component.short_name;
} else if (component.types.indexOf('neighborhood') !== -1) {
document.getElementById('neighborhood').value = component.short_name;
} else if (component.types.indexOf('postal_town') !== -1) {
document.getElementById('county').value = component.short_name;
} else if (component.types.indexOf('postal_code') !== -1) {
document.getElementById('postal_code').value = component.long_name;
}
}
document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lng').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
In this version of the script, we loop through each component in the address_components array and check its types property to see if it matches one of the fields we want to populate. If it does, we set the value of the corresponding form field to the long_name or short_name property of the component. If it doesn't match any of the fields we're looking for, we ignore it.
This approach should be more robust than relying on the order of the components in the array, since the order can vary depending on the address format.