【问题标题】:Google place automplete Angular, get text if not found resultsGoogle 放置自动完成 Angular,如果未找到结果则获取文本
【发布时间】:2021-10-18 21:30:04
【问题描述】:

我正在使用 Angular 9 构建一个用于使用谷歌地图服务进行地址搜索的自动完成组件。我的组件可以工作,但是当没有可用的搜索时,我需要使用 BLUR 事件或当输入失去焦点时。

目前该组件会在我选择地址时检测到,但我需要让它在找不到任何内容时也检测到我键入的文本。

我的html:

 <input #search class="form-control" [formControl]="myAddress" type="text" placeholder="Enter a location">

我的ts:

export class AddressComponent implements OnInit {

  @Output() onSelectAddress = new EventEmitter<CustomAddressModel>();

  myAddress = new FormControl('');
  selectedAddress: PlaceResult;

  @ViewChild('search')
  searchElementRef: ElementRef;

  constructor(
    private _mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone,
  ) { }

  ngOnInit(): void {

    this._mapsAPILoader.load().then(() => {

      const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {

          this.selectedAddress = autocomplete.getPlace();

          if (!this.selectedAddress.geometry) {
            return;
          }

          const result = {
              lat: this.selectedAddress.geometry.location.lat(),
              long:  this.selectedAddress.geometry.location.lng(),
              strAddress:  this.selectedAddress.formatted_address
          } as CustomAddressModel;

          this.onSelectAddress.emit(result);

        });
      });
    });
  }
}

有什么想法吗?

【问题讨论】:

    标签: javascript angular events maps


    【解决方案1】:

    通常需要订阅输入控件的值变化。

    ngOnInit() {
        this.formchanges();
      }
    
    
      formchanges()
      {
         this.yourform.controls['myAddress'].valueChanges.pipe(
          debounceTime(500),
          finalize(() => {
            
          })).subscribe(x => {
          var address = safeTrim(this.yourform.get('myAddress').value);
    
              this.getAddress(address);
            }
          });
      }
      
      getAddress()
      {
         //your call to the google maps api goes here 
      } 
    

    我不确定,我能否回答你的问题。

    【讨论】:

    • 完美!对我有用,谢谢!
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多