Автозаполнение для двоих <Input> - PullRequest
0 голосов
/ 21 мая 2019

Я получаю код от Google для автозаполнения адресных полей.Это хорошо работает для одного «Тип ввода = текст».Я использую его для «Отъезда»

Проблема в том, что я дублирую этот код, чтобы иметь второй «Тип ввода = текст» как «Прибытие»: он работает только для одного из них.

IПопытался изменить ввод id = "autocomparr" и некоторые переменные без успеха.

С уважением

             <input id="autocompdep"
             placeholder="Enter your address"
             onFocus="geolocate()"
             type="text"/>

<script>
var placeSearch, autocomplete;

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

var options = {
  componentRestrictions: {country: 'fr'}
};

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

  // Avoid paying for data that you don't need by restricting the set of
  // place fields that are returned to just the address components.
  autocomplete.setFields(['address_component']);

  // When the user selects an address from the drop-down, 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(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details,
  // and then fill-in 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>


<script src="https://maps.googleapis.com/maps/api/js?key=***&libraries=places&callback=initAutocomplete"
        async defer></script>````

1 Ответ

0 голосов
/ 23 мая 2019

Ответьте себе (и другим, у кого будет эта проблема)

Теперь работает на 2 поля ввода текста на той же странице. Geolococate предназначен для Франции и Французской Ривьеры, чтобы быть более точным для моих нужд.

Привет

<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?key=****&sensor=true&libraries=places"></script>
    </head>
    <body>
        <label for="locationTextField1">Departure</label>
        <input id="locationTextField1" type="text" size="50" >

        <script>

            var defaultBounds = new google.maps.LatLngBounds(
            new google.maps.LatLng(43.093595, 6.153839),
            new google.maps.LatLng(43.467646, 6.237595));
            var options = {
                bounds: defaultBounds,
                componentRestrictions: {country: 'fr'}
            };
            function initDep() {

                var autocomplete = new google.maps.places.Autocomplete(
                document.getElementById('locationTextField1'), options, {types: ['geocode']});
            }

            google.maps.event.addDomListener(window, 'load', initDep);
        </script>
        <br />
        <br />
        <label for="locationTextField2">Arrival</label>
        <input id="locationTextField2" type="text" size="50">

        <script>
            function initArr() {

                var autocomplete = new google.maps.places.Autocomplete(
                document.getElementById('locationTextField2'), options, {types: ['geocode']});
            }

            google.maps.event.addDomListener(window, 'load', initArr);
        </script>

    <script>
</script>   


    </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...