Как добавить краткую форму автозаполнения? [Дубликат]

Пожалуйста, проверьте, как только выбранная база данных не была вызвана, потому что некоторая база данных не выбрана

Проверьте

mysql_select_db('database name ')or DIE('Database name is not available!');

перед запросом MySQL, а затем перейдите к следующему шагу

$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');

f($result === FALSE) {
    die(mysql_error());
4
задан geocodezip 5 November 2015 в 15:43
поделиться

3 ответа

Вам нужно передать два входа автозаполнения. Вот обобщенная версия fillInAddress, которая будет обрабатывать несколько объектов автозаполнения с полями с уникальным расширением («2» в вашей второй версии формы):

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

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

    // 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] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
        }
    }
}

Вызвать это следующим образом:

// 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', function () {
    fillInAddress(autocomplete, "");
});

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

фрагмент рабочего кода:

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
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'
};

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', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

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

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

  // 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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

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 src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
</div>

13
ответ дан geocodezip 26 August 2018 в 15:13
поделиться

Это старый вопрос, но я думал, что опубликую свое решение, если оно будет полезно другим в будущем. Мое решение обрабатывает любое количество полей api autocomplete на странице. Вам нужно будет пометить все поля автозаполнения с именем класса, в моем случае я использовал имя класса «адрес».

Теперь возьмите коллекцию полей:

var input = document.getElementsByClassName('address');

for (var x = 0; x < input.length; x++) {
        addListener(input[x]);
    }

, который вызывает функцию «addListener»

function addListener(el) {
  var autocomplete = new google.maps.places.Autocomplete(el);

  google.maps.event.addListener(autocomplete, 'place_changed', function ()    {
 // Do whatever you want in here e.g.
 // var place = autocomplete.getPlace();
  });
}

. Поскольку это коллекция, вы должны иметь возможность добавлять любое количество полей автозаполнения на страницу. Хотя, естественно, вы должны проверить наличие неопределенного в коллекции на случай, если на странице не будет полей автозаполнения.

0
ответ дан Bruce 26 August 2018 в 15:13
поделиться

Это работает как прелесть:)

thanks jQuery.

function initMultiComplete() {
   jQuery('.maps-complete').each(function(){

    var id = jQuery(this).prop('id');
    var $this = jQuery(this);
    var parent = jQuery(this).parent('div');

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

    jautocomplete.addListener('place_changed', function ()    {

        var place = jautocomplete.getPlace();
        var address = $this.val();
        var lat = place.geometry.location.lat();
        var lng = place.geometry.location.lng();

        jQuery( '.maps-autocomplete-lat', parent ).val(lat);
        jQuery( '.maps-autocomplete-lng', parent ).val(lng);

    });

});
}

скрипт вызывает initMultiComplete как обратный вызов и загружается w / async defer:

https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete
1
ответ дан frafor 26 August 2018 в 15:13
поделиться
Другие вопросы по тегам:

Похожие вопросы: