1

我正在使用agm/core在角度组件中自动完成谷歌地址,并在我的服务模块中添加了以下代码。

@NgModule({
  imports:[ AgmCoreModule.forRoot({
    apiKey: 'testAPiKEY', 
    libraries: ['places']
  }),]
}

在我的组件初始化时,我添加了以下代码,

this.mapsAPILoader.load().then(() => {  
  const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
            types: ['address']
    });
  this.autoComplete.addListener('place_changed', () => {
    this.zone.run(() => {
      // get the place result
      const place: google.maps.places.PlaceResult = this.autoComplete.getPlace();
    this.form
      .get('locations.address')
      .setValue(place['formatted_address']);
    place.address_components.forEach((placeComponent) => {
      const addressType = placeComponent.types[0];

      if (addressType === 'administrative_area_level_1') {                  
        this.form
          .get('locations.state')
          .setValue(placeComponent['long_name']);
      } else if ( addressType === 'administrative_area_level_2') {                  
        this.form
          .get('locations.city')
          .setValue(placeComponent['long_name']);
      } else if (addressType === 'country') {
        this.form
          .get('locations.country')
          .setValue(placeComponent['long_name']);
      } else if (addressType === 'postal_code') {                  
        this.form
          .get('locations.zip')
          .setValue(placeComponent['long_name']);
      }
    });

    // verify result
    if (place.geometry === undefined || place.geometry === null) {
       return;
    }
    // -------------

   });
  });          
});

但是当我第二次输入地址并选择它时加载该组件后选择第一次地址时它不起作用。任何想法?

4

0 回答 0