I have an input where a user enters his location. From this location, I want to fetch city, state and zip and enter these information into another inputs (inputs for city, state and zip), so the user doesn't need to fill these information manually.
I found an example of what I am trying to achieve here and trying to modify it to my needs.
So here I go:
var placeSearch, autocomplete_origin_address, autocomplete_destination_address;
var componentForm_origin = {
user_origin_city: 'user_origin_city',
user_origin_state: 'user_origin_state',
user_origin_zip: 'user_origin_zip'
};
function initAutocomplete() {
console.log('in "initAutocomplete"');
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('user_origin_address'),
types: ['geocode']}
);
autocomplete_origin_address.addListener("place_changed",
fillInAddress(autocomplete_origin_address,
"user_origin_address",
"user_origin_city",
"user_origin_state",
"user_origin_zip"));
}
function fillInAddress(autocomplete_resource, address, city, state, zip) {
console.log("! !x");
// Get the place details from the autocomplete object.
var place = autocomplete_resource.getPlace();
// origin fields to populate with the selected address
var fetched_street_number = fetchAddressDetails(place, "street_number", "long_name");
var fetched_address = fetchAddressDetails(place, "route", "long_name");
$("#"+address).val(fetched_street_number + " " + address);
var fetched_city = fetchAddressDetails(place, "locality", "long_name");
$("#"+city).val(fetched_city);
var fetched_state = fetchAddressDetails(place, "administrative_area_level_1", "short_name");
$("#"+state).val(fetched_state);
var fetched_zip = fetchAddressDetails(place, "postal_code", "long_name");
$("#"+zip).val(fetched_zip);
}
function fetchAddressDetails(autocomplete_place, detail_type, name_type){
console.log("in fetchAddressDetails");
var item = $.grep(autocomplete_place.address_components,
function(e){ return e.types[0] == detail_type; });
var item_data = item[0][name_type];
console.log("item_data: "+item_data);
return item_data;
}
initAutocomplete();
But when I load the page, I get this error:
in "initAutocomplete"
! !x
in fetchAddressDetails
Uncaught TypeError: Cannot read property 'address_components' of undefined
I am trying to google the issue, but cannot get rid of it and make it code work. What I am generally trying - I have 4 inputs on the page, where users enter the address. So I want - when the enter an address to each of those 4 inputs - ruby the google autocomplete functionality, fetch the address and put the city/state/zip information to the respective inputs.
Can you advise, please, why it currently doesn't fetch anything?
Thank you in advance.