谷歌地图地点自动完成添加事件侦听器不起作用



我一直在尝试在 ionic 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);
});
}
<ion-label stacked>Search Location</ion-label>
<input type="text" id="auto" placeholder="Enter Search Location" [(ngModel)]="location.loc" />

索引.html

<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxx&libraries=places"></script>

您可以使用箭头函数来保留thisChangeDetectionRef并使用箭头函数来检测更改,因为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;

普伦克示例

尝试使用以下组件检查place_changedautoComplete上的事件:

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触发角度变化检测。

相关内容

  • 没有找到相关文章

最新更新