Google Autocomplete with Apartment Number

5.9k views Asked by At

When a user adds an apartment number to their address, the autocomplete seems to think it's looking at a zipcode, and changes the suggested matches:

6250 Hollywood Boulevard #20

Is there a way to get this to work, or if not, a way to ignore the apartment number and send it along with the form submission as a separate value? (keeping in mind a user might use #, Unit, Apt, etc to define their unit number)

var placeSearch, autocomplete;

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

function initialize(){

    autocomplete = new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete-address')),
        { types: ['geocode'] });
        google.maps.event.addListener(autocomplete, 'place_changed', function(){
            fillInAddress();
        }
    );

}

function fillInAddress(){

    var place = autocomplete.getPlace();

    for(var component in componentForm){

        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;

    }

    for(var i = 0; i < place.address_components.length; i++){

        var addressType = place.address_components[i].types[0];

        if(componentForm[addressType]){

            var val = place.address_components[i][componentForm[addressType]];

            document.getElementById(addressType).value = val;

        }

    }

}
1

There are 1 answers

0
kaho On

There does not seem to exist a setting to set the Autocomplete API to ignore the apt number, however, we can trim the text before we pass the string to the API.

in your autocomplete = new google.maps.places.Autocomplete(, you can do something like:

document.getElementById('autocomplete-address').replace(/#.*/g,"");

since document.getElementById('autocomplete-address') returns a string, we can replace the #number paer with an empty string with .replace(/#.*/g,"")