我正试图在一个新的Ionic应用程序中设置谷歌地图位置自动完成。
问题来了。在第一次搜索时,我在控制台中得到了这个错误:
TypeError: Cannot read property 'place_id' of undefined
终端中的这个错误:
TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'
然而,在第二次搜索中,我得到了place_id,没有任何错误。
这是我的(简化的(.ts文件
import { Component, OnInit } from '@angular/core';
import { google } from "google-maps";
import { Platform } from '@ionic/angular';
@Component({...})
export class AddaddressPage implements OnInit {
autocomplete:any;
constructor(public platform: Platform) {}
ngOnInit() {
this.platform.ready().then(() => {
this.autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
this.autocomplete.setFields(['place_id']);
});
}
fillInAddress() {
var place = this.autocomplete.getPlace();
console.log(place);
console.log(place.place_id);
}
}
我使用的输入:
<input id="autocomplete" type="text" (change)="fillInAddress()" />
我应该如何继续?
玩过之后,这里有诀窍!需要ViewChild和Ion输入。
.html
<ion-input #autocomplete type="text"></ion-input>
.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { google } from "google-maps";
import { Platform } from '@ionic/angular';
@Component(...)
export class AddaddressPage implements OnInit {
googleAutocomplete:any;
@ViewChild('autocomplete') autocompleteInput: ElementRef;
constructor(public platform: Platform) { }
ngOnInit() {
this.platform.ready().then(() => {
this.autocompleteInput.getInputElement().then((el)=>{
this.googleAutocomplete = new google.maps.places.Autocomplete(el);
this.googleAutocomplete.setFields(['place_id']);
this.googleAutocomplete.addListener('place_changed', () => {
var place = this.googleAutocomplete.getPlace();
console.log(place);
console.log(place.place_id);
});
})
});
}
}