Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Autocomplete with Apartment Number

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;

        }

    }

}
like image 251
HWD Avatar asked Jun 26 '15 18:06

HWD


People also ask

How do I create an autocomplete address in Google Maps?

To enable the Address Autocomplete Feature, go to the Advanced tab of the Address field. Scroll down till you see the Enable Address Autocomplete option. Toggle on this setting to enable address autocomplete in your form.

How do I use Google Places autocomplete API?

Go to the Google Cloud Console. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open. From the list of APIs on the Dashboard, look for Places API. If you see the API in the list, you're all set.


1 Answers

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,"")

like image 99
kaho Avatar answered Sep 23 '22 04:09

kaho