我一直在尝试在离子2项目中添加谷歌地图自动完成以更新用户位置。但是,addEventListener似乎没有工作,没有控制台错误,任何人都可以告诉我我要去哪里错?
ngAfterViewInit() {
let input = < HTMLInputElement > document.getElementById("auto");
console.log('input', input);
let options = {
componentRestrictions: {
country: 'IN',
types: ['(regions)']
}
}
let autoComplete = new google.maps.places.Autocomplete(input, options);
console.log('auto', autoComplete);
google.maps.event.addListener(autoComplete, 'place_changed', function() {
this.location.loc = autoComplete.getPlace();
console.log('place_changed', this.location.loc);
});
}
&#13;
<ion-label stacked>Search Location</ion-label>
<input type="text" id="auto" placeholder="Enter Search Location" [(ngModel)]="location.loc" />
&#13;
的index.html
<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxx&libraries=places"></script>
&#13;
答案 0 :(得分:1)
您可以使用箭头功能保留this
和ChangeDetectionRef
以检测更改,因为Google地图事件会在角度区域外触发:
constructor(private cd: ChangeDetectorRef) { }
google.maps.event.addListener(autoComplete, 'place_changed', () => { // arrow function
this.location.loc = autoComplete.getPlace();
this.cd.detectChanges(); // detect changes
console.log('place_changed', this.location.loc);
});
autoComplete.getPlace();
返回Object,因此您可以按如下方式获取地址:
var place = autoComplete.getPlace();
this.location.loc = place.formatted_address;
<强> Plunker Example 强>
答案 1 :(得分:0)
尝试使用以下组件检查place_changed
上的autoComplete
事件:
import {Component, ViewChild, ChangeDetectorRef} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input #auto />
{{ location?.formatted_address | json}}
</div>
`,
})
export class App {
@ViewChild('auto') auto:any;
location: any;
constructor(private ref: ChangeDetectorRef) {
}
ngAfterViewInit(){
let options = {
componentRestrictions: {
country: 'IN'
}
};
let autoComplete = new google.maps.places.Autocomplete(this.auto.nativeElement, options);
console.log('auto', autoComplete);
autoComplete.addListener('place_changed', () => {
this.location = autoComplete.getPlace();
console.log('place_changed', this.location);
this.ref.detectChanges();
});
}
}
由于place_changed
是角度js之外的触发器,我们需要手动触发ChangeDetectorRef
角度变化检测。