Google地图使用角形材料自动完成

时间:2019-01-22 17:02:22

标签: angular google-maps-api-3 angular-material

当用户输入位置时,我正在尝试以有角度的材料形式使用Google地图自动完成功能。它似乎无法正确读取输入,因为出现以下错误:enter image description here

这是我的代码

html:

<mat-form-field>
             <input matInput placeholder="Event Location" [formControl]="eventLocation" required #search type="text" id= "place">
</mat-form-field>

ts:

firstFormGroup: FormGroup;
public eventLocation: FormControl;
public searchElementRef: ElementRef;
eventPost: Latlong;
eventLat: number;
eventLng: number;
@ViewChild('search')

ngOnInit() {

      this.firstFormGroup = this._formBuilder.group({
        eventName: ['', Validators.required],
        eventLocation: ['', Validators.required]
      });
      this.eventLocation = new FormControl;
      this.mapsAPILoader.load().then(() => {
        const autocomplete = new google.maps.places.Autocomplete(
          this.searchElementRef.nativeElement, {
            types: []
        });
          autocomplete.addListener('place_changed', () => {
            this.ngZone.run(() => {
              const place: google.maps.places.PlaceResult = autocomplete.getPlace();
              if (place.geometry === undefined || place.geometry === null) {
                return;
              }
              this.eventPost = {
                latitude: place.geometry.location.lat(),
                longitude: place.geometry.location.lng()
              };
              this.mydata.latlongSource.next({ ...this.eventPost });
              this.eventLat = this.eventPost.latitude;
              this.mydata.markerLatSource.next( this.eventLat);
              this.eventLng = this.eventPost.longitude;
              this.mydata.markerLngSource.next( this.eventLng);
              this.eventLocation.reset();
            });
          });
      });

1 个答案:

答案 0 :(得分:1)

nativeElement是DOM元素。您还没有OnInit钩中的DOM。使用AfterViewInit访问DOM元素:

ngAfterViewInit() {

      this.firstFormGroup = this._formBuilder.group({
        eventName: ['', Validators.required],
        eventLocation: ['', Validators.required]
      });