Как очистить поле ввода поиска с помощью javascript при использовании формы автозаполнения Google Maps v3

Я использую Google Maps v3 API для автозаполнения формы адреса, но я не хочу использовать общее поле поиска, как в примере (https://google-developers.appspot.com/maps/documentation/javascript/examples/full/places-autocomplete-addressform) .

Я пытаюсь сделать поле адреса улицы полем поиска, а также только поле номера улицы и названия улицы. Я нашел этот пример на скрипте JS (https://jsfiddle.net/smartystreets/0c9fy73v/) Я не могу это воспроизвести.

Я попытался отключить autocomplete=off, но не работает в chrome (для elementId('autocomplete'))

Я попытался скрыть элементы ввода маршрута и улицы и установить пустое значение идентификатора ввода.

document.getElementById('autocomplete').value = ''; 

Затем, используя скрытые поля ввода, перестроить эту форму ввода с

document.getElementById('autocomplete').value = document.getElementById('street_number') + ' ' + document.getElementById('route');

Любые идеи, что я делаю неправильно? Почему поле поиска не очищается?

Это мой HTML для моего поля поиска/адреса:

<!-- address -->
   <div class="col-md-6 col-lg-6">
      <label class="light text-capitalize">address:</label>
      <input type="text"   id="autocomplete"
         name="street" placeholder="Street address, PO Box, etc.">
      <input type="hidden" id="route" disabled="false">
      <input type="hidden" id="street_number" disabled="false"> 
      <input type="text"  name="address1" placeholder="(Optional) Apartment, Suite, Floor, etc.">
   </div>
<!-- address end -->

Это мой встроенный JS

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

  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {types: ['geocode']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
  }

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


    for (var component in componentForm) {

    document.getElementById('street_number').value = '';
    document.getElementById('route').value = '';
    document.getElementById('locality').value = '';
    document.getElementById('administrative_area_level_1').value = '';
//  document.getElementById('country').value = '';
    document.getElementById('postal_code').value = '';

    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
   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;
      }
    }
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
</script>

person arrydavid    schedule 04.10.2017    source источник
comment
когда вы хотите очистить поле поиска?   -  person James Solomon Belda    schedule 04.10.2017
comment
Привет, Джеймс, я хочу очистить его после того, как пользователь нажмет на адрес, соответствующий его поиску.   -  person arrydavid    schedule 04.10.2017


Ответы (1)


Если вы действительно хотите очистить поле ввода поиска после того, как пользователь нажмет на адрес из автозаполнения, попробуйте установить значение ввода (id=autocomplete) пустым после того, как вы получите место.

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

    /* Your other code */

    document.getElementById('autocomplete').value = '';
}

Я просто сделал демонстрацию для вас, чтобы проверить поведение. Вы можете увидеть это здесь http://jsbin.com/mugasav/1/edit?html,js,output

person James Solomon Belda    schedule 05.10.2017
comment
Джеймс, ты легенда. Работает идеально, как и предполагалось, я часами стучал головой о стену, пытаясь понять это! - person arrydavid; 05.10.2017
comment
Если мой ответ помог вам, вы также можете принять мой ответ, чтобы он мог помочь мне и другим :) - person James Solomon Belda; 05.10.2017