I Как я могу сделать, чтобы установить strictbound, чтобы показать адрес ближе к текущему местоположению? - PullRequest
0 голосов
/ 11 октября 2019

автозаполнение работает отлично для меня, проблема в том, что когда я начинаю печатать, он показывает мне направление от моего местоположения, я видел другой код, использующий обычный javascript, у него была функция для установки границ, а затем автозаполнение показывает сначалаадрес ближе всего расположен enter image description here

это код в javascript

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'
};

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

  // 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());
    });
  }

и это мой код в угловых

initAutocomplete() {
    var formGroup = {
      route: '',
      street_number: '',
      locality: ''
    }
    this.mapsAPILoader.load().then(() => {
      this.geoCoder = new google.maps.Geocoder;
      let options = {
        types: ['geocode'],
        componentRestrictions: { country: 'ar' }
      };
      console.log(this.geoCoder)
      this.autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, options);

      console.log(this.autocomplete)
      this.autocomplete.addListener("place_changed", () => {
        console.log(this)
        this.ngZone.run(() => {
          //get the place result
          let place: google.maps.places.PlaceResult = this.autocomplete.getPlace();
          console.log(place)
          //verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }
          for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            console.log(addressType)
            formGroup[addressType] = place.address_components[i]['long_name']
          }
          if (formGroup['locality'] != 'Ushuaia') {
            this.notificationService.error("Debe Elegir una direccion dentro de Ushuaia")
            return
          }
          this.direccionFormGroup.controls['calle'].setValue(formGroup['route'])
          this.direccionFormGroup.controls['numero'].setValue(formGroup['street_number'])

        });
      });


    });
  }

enter image description here

где я устанавливаю границы, извините за мой плохой английский

1 Ответ

0 голосов
/ 15 октября 2019

Используя Виджет автозаполнения JavaScript , вы можете проверить некоторые опции в этом руководстве , чтобы установить смещения и границы области поиска.

Существуют следующие способы:

  • Установить границы при создании объекта автозаполнения.
  • Изменить границы для существующего автозаполнения.
  • Установитьграницы для области просмотра карты.
  • Ограничение поиска границами.
  • Ограничение поиска определенной страной.

Вы можете использовать Strict Bounds опция, чтобы ограничить поиск областью в текущем окне просмотра или границами, которые явно установлены. Более подробная информация и примеры приведены в общедоступной документации , в которой вы можете проверить, подходит ли ваш вариант использования.

Надеюсь, это поможет!

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