简体   繁体   中英

How to make google address autofill using API, to replace full address with number & street?

I am using a google API to auto-fill an address form. Right now i found code to fill out the full address, which auto-populates all of the fields in picture link #1 as shown. I have hidden the street number and route fields as they are not needed.

What i am looking for, is after i select the address, i want the address bar i was typing in to not display the city, state and country in that field bar. I want the auto-fill to look like what is shown in picture link #2, where the address field replaces the full address with only the number and street, and does not include the city, state, country. While typing i selected the address shown in picture link #3, and it autofills what is shown in picture link #2.

Does anyone know how to replace the full address with just the number & street after clicking on an address? I used html and jscript from this link here: https://github.com/solodev/address-auto-complete

Picture Link #1: https://imgur.com/a/oCAAs4C

Picture Link #2: https://imgur.com/a/psaz3J4

Picture Link #3: https://imgur.com/a/xQMNjpy

Try modifying the fillInAddress as follows:

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  var streetAddress = '';
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {

      if (addressType === 'street_number') {
        streetAddress += place.address_components[i][componentForm[addressType]];
      } else if (addressType === 'route') {
        if (streetAddress.length) {
          streetAddress += ' ';
        }
        streetAddress += place.address_components[i][componentForm[addressType]];
      }

      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
      document.getElementById('autocomplete').value = streetAddress;
    }
  }
}

Working jsfiddle based off of the demo .

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM