Автозаполнение API Google Адресов - сохраняйте заполнитель на языке браузера, даже если результаты отображаются на другом языке - PullRequest
1 голос
/ 05 марта 2020

Я использую автозаполнение API Google Адресов в многоязычной форме. Я хочу заполнить свои поля в Engli sh, чтобы адресная информация попала в мою базу данных в Engli sh. Кажется, самый простой способ сделать это - добавить параметр «language» в API и установить язык Engli sh. Проблема в том, что если я сделаю это, то даже в моей французской или испанской форме sh встроенный заполнитель, который Google вставит в мое поле ввода, также будет в Engli sh.

. не устанавливайте язык Engli sh и поля заполняйте на другом языке, но тогда мне как-то понадобится доступ к компонентам адреса в Engli sh, чтобы поместить их в базу данных.

In Если коротко:
Мне нужно, чтобы встроенный местозаполнитель адресов Google был на языке пользователя
Мне нужно, чтобы значения адресов в Engli sh были только включены в мою базу данных. Как мне go сделать это?

Код:

var placeSearch, autocomplete;

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

 var componentToIdOrig = {
  street_number: 'id_original_address',
  route: 'id_original_address',
  locality: 'id_original_city',
  administrative_area_level_1: 'id_original_state',
  country: 'id_original_country',
  postal_code: 'id_zip_code'
};



function initAutocomplete() {
  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      document.getElementById('id_original_address'));

  // 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.bind(null, autocomplete, componentFormOrig, componentToIdOrig));


}

function fillInAddress(autocompleteObj, componentForm, componentToId) {
console.log(autocompleteObj);
  // Get the place details from the autocomplete object.
    var place = autocompleteObj.getPlace();

    for (var item in componentToId) {
      console.log(item);
      document.getElementById(componentToId[item]).value = '';
      document.getElementById(componentToId[item]).disabled = false;
    }

    // Get each component of the address from the place details,
    // and then fill-in the corresponding field on the form.
    var fullAddress = [];
    console.log("address_components");
    for (var i = 0; i < place.address_components.length; i++) {
      console.log(place.address_components[i]);
      var addressType = place.address_components[i].types[0];
      console.log("addressType=" + addressType);
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        console.log("val=" + val);
        document.getElementById(componentToId[addressType]).value = val;
      }
      if (addressType == "street_number") {
        fullAddress[0] = val;
      } else if (addressType == "route") {
        fullAddress[1] = val;
      }
    }

    document.getElementById(componentToId['street_number']).value = fullAddress.join(" ");
    if (document.getElementById(componentToId['street_number']).value !== "") {
      document.getElementById(componentToIdOrig['street_number']).disabled = false;
    }
  }

// 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...